// 物资财务确认
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, Table, Switch, message, Pagination, Input, Checkbox, Icon } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less'
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
var standingNumber = 0; //确认单序列号

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span:15 },
    wrapperCol: { span: 8 },
};
const FinancialConfirmation = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                detailsId: '',//确认单ID
                WaListData: [], //确认单数据
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                page2: 1,
                total:0,
                detailTotal: 0,
                show: false,
                vouchingId: [],
                selectedRowKeys: [],
                id: '40',
                stateData: [],  //状态下拉框
                stateBoolean: false,
                modalColumns: [],
                detailWidthTotal: '',
                columns:[],
                columnsWidth:'',
                ChineseEnglishSize: [],
            };

            // 药品的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '供应商',
                    dataIndex: 'descripts',
                    align: "center",
                    width: '100%'
                }
            ];
            // 确认单详细表头
            this.modalColumns = [
                {
                    key: 1,
                    title: '确认单号',
                    dataIndex: 'stkPayNO',
                    align: "center",
                    width: '16%'
                },
                {
                    key: 2,
                    title: '状态',
                    dataIndex: 'stateDesc',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 3,
                    title: '进价金额',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 4,
                    title: '将付金额',
                    dataIndex: 'willPay',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 5,
                    title: '制单日期',
                    dataIndex: 'createDate',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 6,
                    title: '采购确认',
                    dataIndex: 'purCheckUser',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 7,
                    title: '财务确认',
                    dataIndex: 'finaCheckUser',
                    align: "center",
                    width: '14%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            this.getColumnsLeft();
            let dom = document.querySelectorAll('.waListHeight  .ant-table-body');
            dom[0].style.height = store.getState().tableHeight.y - 55 + 'px';
            let detailsHeight = document.querySelectorAll('.detailsHeight  .ant-table-body');
            detailsHeight[0].style.height = store.getState().tableHeight.y - 55 + 'px';
        }
        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    reactCode: ['MaterialFinancialConfirmation'],
                    compontName: 'MaterialFinancialConfirmation',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => { this.columnRef.onOpenModel();}}>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({modalColumns: filterArr, detailWidthTotal: res.totalWidth,ChineseEnglishSize:userInfo.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            });
        };

        //页面中英文翻译
         getColumnsLeft = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    compontName: 'MaterialFinanceConLeftC',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, columnsWidth: res.totalWidth})
                    }
                }
            })
        };

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02060100",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = ['40','50'];
                        let newArr = [];
                        if(res.state.length>0){
                            for(var i = 0; i< arr.length; i++){
                                newArr.push(res.state.find(item => item.id == arr[i]))
                            }
                        }
                        this.setState({SelectData: res, stateData: newArr })
                    }
                }
            })
        }

        // 获取待审核数据
        getVouchingList=(num)=>{
            let {ChineseEnglishSize} = this.state;
            this.setState({loading:true})
            let state = this.props.form.getFieldValue('state');
            let EndData = this.props.form.getFieldValue('EndData');
            let StartDate = this.props.form.getFieldValue('StartDate');
            let data = {
                params: [{
                    begin: Moment(StartDate).format('YYYY-MM-DD'),
                    end: Moment(EndData).format('YYYY-MM-DD'),
                    vendorID:this.state.detailsId ? this.state.detailsId : undefined ,
                    stateID: state ? state : undefined
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize2,
                        currentPage:this.state.page2,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02060103",
                data: data,
                success: function (res) {
                    if(res.rows.length > 0){
                        for(var i = 0; i < res.rows.length; i++){
                            res.rows[i].key = i;
                            res.rows[i].purCheckUser =  res.rows[i].purCheckUserName  +  res.rows[i].purCheckDate ;
                            res.rows[i].finaCheckUser =  res.rows[i].finaCheckUserName  +  res.rows[i].finaCheckDate ;
                        }
                        this.setState({ WaListData: res.rows,total: res.total, selectedRowKeys: [], loading:false });
                        standingNumber = 0;
                    }else {
                        this.setState({WaListData: [], selectedRowKeys: [] });
                        if(num !== '1'){
                            message.error(ChineseEnglishSize.MaterialFinancialConfirmationnoData ? ChineseEnglishSize.MaterialFinancialConfirmationnoData.descripts:"没数据")
                        }
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

        // 确认
        dataVouching=()=> {
            let {ChineseEnglishSize} = this.state;
            let { vouchingId } = this.state;
            if(vouchingId.length > 0){
                let arr = vouchingId&&vouchingId.map(item => {
                    return {
                        stkPayID: item.stkPayID
                    }
                });
                let data = {
                    params: arr
                };
                $http.post('urlS', this, {
                    code: "02060109",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(res.errorMessage);
                            this.setState({vouchingId: []})
                            this.getVouchingList('1');
                        }
                    }
                })
            }else {
                message.error(ChineseEnglishSize.MaterialFinancialConfirmationselectConfiData ? ChineseEnglishSize.MaterialFinancialConfirmationselectConfiData.descripts:'请选择确认数据')
            }

        };

        //点击行，渲染当前行样式
        setRowClassName = (record) => {
            standingNumber = standingNumber + 1;
            if(record){
                if(this.state.detailsId == record.id) return 'clickRowStyle';
                // else if (standingNumber == 1) return 'clickRowStyle';
                else return '';
                // return this.state.detailsId == record.inOperateID ? 'clickRowStyle ': '';
            }else {
                return '';
            }
        };



        // 页码改变的回调，参数是改变后的页码及每页条数
        // onChange = (page, pageSize) => {
        //     this.setState({page: page, pageSize: pageSize}, () => {
        //         // 重新调用查询方法
        //         this.getVouchingList();
        //     });
        // };
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        // onShowSizeChange = (current, size) => {
        //     this.setState({page: current, pageSize: size}, () => {
        //         // 重新调用查询方法
        //         this.onChange(current,size);
        //     })
        // };

        // 页码改变的回调，参数是改变后的页码及每页条数 确认单详情
        onChange2 = (page, pageSize) => {
            this.setState({page2: page, pageSize2: pageSize}, () => {
                // 重新调用查询方法
                this.getVouchingList();
            });
        };

        onShowSizeChange2 = (current, size) => {
            this.setState({page2: current, pageSize2: size}, () => {
                // 重新调用查询方法
                this.onChange2(current,size);
            })
        };

        // 收起明细录入
        packUpHandle = () => {
            this.setState({show: !this.state.show, span: 24})
        };

        setPaymentClassName= (record) => {
            // 选中行class名
            return (("^" + this.state.selectedRowKeys.join("^") + "^").indexOf("^" + record.key + "^") > -1) ? 'clickRowStyle' : '';
        };

        onClickRow = (record) => {
            return {
                onClick: () => {
                    let {selectedRowKeys, vouchingId} = this.state;
                    let findFlag = false;
                    let start = 0;
                    if (selectedRowKeys) {
                        selectedRowKeys.find(function (value, key) {
                            if (value === record.key) {
                                //遍历找到选中的数据，并记录下选中数据在数组中的key
                                findFlag = true;
                                start = key;
                            }
                        })
                    }
                    if (findFlag) {
                        //再次点击移除选中
                        selectedRowKeys.splice(start, 1);
                        vouchingId.splice(start, 1);
                    } else {
                        //将点击的行添加到选中
                        selectedRowKeys.push(record.key);
                        vouchingId.push(record);
                    }
                    if (this.state.rowId === "") {
                        this.setState({
                            rowId: record.key,
                            selectedRowKeys,
                            vouchingId
                        });
                    } else {
                        if (this.state.rowId !== record.key) {
                            this.setState({
                                rowId: record.key,
                                selectedRowKeys,
                                vouchingId
                            });
                        } else {
                            this.setState({
                                rowId: "",
                                selectedRowKeys,
                                vouchingId
                            });
                        }
                    }
                    let result = this.state.vouchingId.some(function (item) {
                        if (item.stateID == '50') {
                            return true;
                        }
                    });
                    this.setState({stateBoolean: result})
                }
            }
        };
        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };
        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo: {};
            let {ChineseEnglishSize} = this.state;
            //确认部门下拉列表
            let loc = [];
            let state = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                loc.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.stateData.length>0 && this.state.stateData.map((item, i) => {
                state.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            const rowSelection = {
                selectedRowKeys: this.state.selectedRowKeys,
                selectedRows: this.state.vouchingId,
                onChange: (selectedRowKeys, selectedRows) => {
                    let rowId= "";
                    if (selectedRowKeys.length !== 0) {
                        rowId=selectedRowKeys[selectedRowKeys.length-1];
                    }
                    this.setState({selectedRowKeys: selectedRowKeys, vouchingId: selectedRows, rowId: rowId})
                }
            };
            return (
                <div className="paymentVouching">
                    <Row>
                        <Card
                            size="small"
                            title={ChineseEnglishSize.MaterialFinancialConfirmationfinanceCon ? ChineseEnglishSize.MaterialFinancialConfirmationfinanceCon.descripts:'财务确认'}
                        >
                            <Col span={13}>
                                <Form>
                                    <Row >
                                        {/*<Col span={6}>*/}
                                        {/*<FormItem {...formItemLayout} label="科室">*/}
                                        {/*{getFieldDecorator('locDr',{*/}
                                        {/*initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,*/}
                                        {/*rules:[{ required : true, message: '科室不能为空'}]*/}
                                        {/*})(*/}
                                        {/*<Select allowClear={true}>*/}
                                        {/*{loc}*/}
                                        {/*</Select>*/}
                                        {/*) }*/}
                                        {/*</FormItem>*/}
                                        {/*</Col>*/}
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialFinancialConfirmationstate ? ChineseEnglishSize.MaterialFinancialConfirmationstate.descripts:'状态'}>
                                                {getFieldDecorator('state',{
                                                    initialValue: this.state.id ? this.state.id : undefined,
                                                    rules:[{ required : ChineseEnglishSize.MaterialFinancialConfirmationstate ? ChineseEnglishSize.MaterialFinancialConfirmationstate.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialFinancialConfirmationstate ? ChineseEnglishSize.MaterialFinancialConfirmationstate.message:'状态不能为空'}]
                                                })(
                                                    <Select  className="abcd">
                                                        {state}
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={4} className="queryTime" style={{marginLeft: '30px'}}>
                                            <FormItem>
                                                {getFieldDecorator('StartDate',{
                                                    initialValue: this.state.queryCondition.startDate ? Moment(this.state.queryCondition.startDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                    rules:[{ required : ChineseEnglishSize.MaterialFinancialConfirmationStartData ? ChineseEnglishSize.MaterialFinancialConfirmationStartData.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialFinancialConfirmationStartData ? ChineseEnglishSize.MaterialFinancialConfirmationStartData.message:'起初日期不能为空'}]
                                                })(
                                                    <DatePicker />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={1} style={{    textAlign: 'center', lineHeight: '37px'}}>
                                            <span>{ChineseEnglishSize.MaterialFinancialConfirmationto ? ChineseEnglishSize.MaterialFinancialConfirmationto.descripts:'到'}</span>
                                        </Col>
                                        <Col span={4}  className="queryTime">
                                            <FormItem>
                                                {getFieldDecorator('EndData',{
                                                    initialValue: this.state.queryCondition.endDate ? Moment(this.state.queryCondition.endDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                    rules:[{ required : ChineseEnglishSize.MaterialFinancialConfirmationdeadline ? ChineseEnglishSize.MaterialFinancialConfirmationdeadline.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialFinancialConfirmationdeadline ? ChineseEnglishSize.MaterialFinancialConfirmationdeadline.message:'截至日期不能为空'}]
                                                })(
                                                    <DatePicker />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={4}  style={{marginLeft: '30px'}}>
                                            <Row style={{marginTop: '4px'}} className="buttonLeft">
                                                <Button onClick={this.getVouchingList}>{ChineseEnglishSize.MaterialFinancialConfirmationsearch ? ChineseEnglishSize.MaterialFinancialConfirmationsearch.descripts:'查询'}</Button>
                                            </Row>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={10} style={{textAlign: 'right'}}>
                                <Row style={{marginTop: '4px'}} className="buttonRight">
                                    <Button disabled={this.state.selectedRowKeys.length>0 && this.props.form.getFieldValue('state')!=='50' ? false : true } onClick={this.dataVouching}>{ChineseEnglishSize.MaterialFinancialConfirmationfinanceCon ? ChineseEnglishSize.MaterialFinancialConfirmationfinanceCon.descripts:'财务确认'}</Button>
                                </Row>
                            </Col>
                        </Card>
                    </Row>
                    <Row>
                        <Col span={6} style={{display: this.state.show ? 'none' : ''}} className={!this.state.show ? "animate-wrap active down-in" : "animate-wrap"}>
                            <Card
                                size="small"
                                title={ChineseEnglishSize.MaterialFinancialConfirmationsupplier ? ChineseEnglishSize.MaterialFinancialConfirmationsupplier.descripts:'供应商'}
                            >
                                <div className="drugList " style={{height: store.getState().tableHeight.y +85 + 'px'}}>
                                    <Table
                                        columns={this.state.columns.length>0?this.state.columns:this.columns}
                                        dataSource={this.state.SelectData ? this.state.SelectData.vendor : []}
                                        pagination={false}
                                        bordered
                                        scroll={{ y: store.getState().tableHeight.y - 52}}
                                        style={{height: (store.getState().tableHeight.y - 5)}}
                                        rowClassName={this.setRowClassName}
                                        rowKey={record => record.key}
                                        className='waListHeight'
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    standingNumber = 9999;
                                                    if (this.state.detailsId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({detailsId: record.id},()=>{
                                                            this.getVouchingList()
                                                        });

                                                    } else {
                                                        if (this.state.detailsId !== record.id) {
                                                            this.setState({detailsId: record.id},()=> {
                                                                this.getVouchingList()
                                                            });
                                                        } else {
                                                            this.setState({detailsId: ''});
                                                        }
                                                    }
                                                },
                                            };
                                        }}
                                    />
                                </div>
                            </Card>
                        </Col>
                        <Col span={this.state.show ? 24 : 18}>
                            <Card
                                size="small"
                                title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />{ChineseEnglishSize.MaterialFinancialConfirmationfinanceConForm ? ChineseEnglishSize.MaterialFinancialConfirmationfinanceConForm.descripts:'财务确认单'}</span>}
                            >
                                <div style={{height: store.getState().tableHeight.y+ 85 + 'px'}}>
                                    <Table
                                        rowSelection={rowSelection}
                                        columns={this.state.modalColumns.length>0 ? this.state.modalColumns : this.modalColumns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        style={{height: (store.getState().tableHeight.y - 5)}}
                                        scroll={{x: this.state.detailWidthTotal ? this.state.detailWidthTotal : 1600, y: store.getState().tableHeight.y - 52 }}
                                        rowKey={record => record.key}
                                        className='detailsHeight'
                                        onRow={this.onClickRow}
                                        rowClassName={this.setPaymentClassName}
                                    />
                                    <CommonPagination size='small' current={this.state.page2} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.WaListData}
                                                      loading={this.state.loading} onChange={this.onChange2.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    {/*//显示表头修改弹窗*/}
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='MaterialFinancialConfirmation'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);
export default FinancialConfirmation;
