// 物资付款管理
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 AddPayment from './component/AddPayment';
import './style/index.less';
import {printStkPay} from '../commonPrint/stkPrint';
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 PaymentManagement = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                detailsId: '',//付款单ID
                detailsListData:[], //付款单明细数据
                WaListData: [], //付款单数据
                size: 'small',
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                page2: 1,
                total:0,
                detailTotal: 0,
                show: false,
                paymentID: '',
                modalColumns: [],
                detailWidthTotal: '',
                ChineseEnglishSize: [],
                columns:[],
                columnsWidth:'',
            };

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

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            this.getColumnsLeft();
            let leftList = document.querySelectorAll('.waListHeight  .ant-table-body');
            if(leftList.length>0){
                leftList[0].style.height = store.getState().tableHeight.y - 5 + 'px';
            }
            let listData = document.querySelectorAll('.detailsHeight  .ant-table-body');
            if(listData.length>0){
                listData[0].style.height = store.getState().tableHeight.y - 5 + 'px';
            }
        }
        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    reactCode: ['MaterialPaymentManagement'],
                    compontName: 'MaterialPaymentManagement',
                    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: 'MaterialPaymentManagementLeftC',
                    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})
                    }
                }
            })
        };

        //清空表格内容
        handleReset = () => {
            this.setState({WaListData: [],detailsListData: [],total: 0, detailsId: ''});
            this.props.form.setFieldsValue({stockDr: undefined});
            this.props.form.resetFields();
        };

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02060100",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({SelectData: res})
                    }
                }
            })
        }

        // 获取药品列表数据
        getWarehouseList=(num)=>{
            let {ChineseEnglishSize} = this.state;
            this.setState({loading:true})
            let qStkCatDr = this.props.form.getFieldValue('stkCatDr');
            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: qStkCatDr ? qStkCatDr : undefined
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        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,page2: 1,loading:false });
                        standingNumber = 0;
                        // this.getWarehouseEntryDetails(res.rows[0].stkLocID)
                    }else {
                        this.setState({WaListData: [], detailsListData: [],});
                        if(num !== '1'){
                            message.error(ChineseEnglishSize.MaterialPaymentManagementnoData ? ChineseEnglishSize.MaterialPaymentManagementnoData.descripts:"没数据")
                        }
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };
        complete=()=>{
            const {record}=this.state;
            let post={};
            if (record.stateID==10){
                post.code='02060105';
            }else if(record.stateID==20){
                post.code='02060106';
            }else{
                return;
            }
            post.data={
                params:[{
                    stkPayID:record.stkPayID
                }]
            }
            $http.post('urlS', this, {
                ...post,
                success: function (res) {
                    if (res.errorCode==0){
                        message.success(res.errorMessage);
                        this.getWarehouseList('1');
                        this.setState({paymentID:'',record:{}});
                    }else{
                        message.error(res.errorMessage);
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        }

        // 获取到付款部门的值
        getInOpLocDr() {
            let inOpLocDr = this.props.form.getFieldValue('locDr');
            this.setState({inOpLocDr: inOpLocDr});
            return inOpLocDr
        }

        //点击行，渲染当前行样式
        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 '';
            }
        };
        setPaymentClassName= (record) => {
            if(record){
                if(this.state.paymentID == record.stkPayID) return 'clickRowStyle';
                else return '';
            }else {
                return '';
            }
        };

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

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


        onRef = (ref) => {
            this.childModal = ref;
        };

        addPaymentReceipt=()=>{
            this.childModal.showModal();
        };

        removePayment=()=> {
                let data = {
                    params: {
                        main: [
                            {
                                stkPayID: this.state.paymentID ? this.state.paymentID: ''
                            }
                        ]
                    }

                };
                $http.post('urlS', this, {
                    code: "02060104",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(res.errorMessage);
                            this.setState({
                                paymentID: ''
                            })
                            this.getWarehouseList('1');
                        }
                    }
                })
        }
        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };

        render() {
            let {ChineseEnglishSize,userInfo,columns, modalColumns} = this.state;
            const { getFieldDecorator} = this.props.form;

            //下拉列表
            let stkCat = [];
            this.state.SelectData.state && this.state.SelectData.state.map((item, i) => {
                stkCat.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            return (
                <div className="paymentManagement">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.MaterialPaymentManagementpayManagement ? ChineseEnglishSize.MaterialPaymentManagementpayManagement.descripts:'付款管理'}</div>}
                        >
                            <Col span={13}>
                                <Form>
                                    <Row >
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialPaymentManagementstate ? ChineseEnglishSize.MaterialPaymentManagementstate.descripts:'状态'}>
                                                {getFieldDecorator('stkCatDr',{
                                                    initialValue: undefined,
                                                    rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingvendorID ? ChineseEnglishSize.MaterialStorageOrderMakingvendorID.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingvendorID ? ChineseEnglishSize.MaterialStorageOrderMakingvendorID.message:'状态不能为空'}]    
                                                })(
                                                    <Select allowClear={true}>
                                                        {stkCat}
                                                    </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(),
                                                    rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingvendorID ? ChineseEnglishSize.MaterialStorageOrderMakingvendorID.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingvendorID ? ChineseEnglishSize.MaterialStorageOrderMakingvendorID.message:'起初日期不能为空'}]    
                                                })(
                                                    <DatePicker />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={1} style={{    textAlign: 'center', lineHeight: '37px'}}>
                                            <span>{ChineseEnglishSize.MaterialPaymentManagementto ? ChineseEnglishSize.MaterialPaymentManagementto.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(),
                                                    rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingvendorID ? ChineseEnglishSize.MaterialStorageOrderMakingvendorID.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingvendorID ? ChineseEnglishSize.MaterialStorageOrderMakingvendorID.message:'截至日期不能为空'}]    
                                                })(
                                                    <DatePicker />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={4}  style={{marginLeft: '30px'}}>
                                            <Row style={{marginTop: '4px'}} className="buttonLeft">
                                                <Button onClick={this.getWarehouseList}>{ChineseEnglishSize.MaterialPaymentManagementsearch ? ChineseEnglishSize.MaterialPaymentManagementsearch.descripts:'查询'}</Button>
                                            </Row>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>

                            <Col span={10} style={{textAlign: 'right'}}>
                                <Row style={{marginTop: '4px'}} className="buttonRight">
                                    {userInfo.language == 'EN'?
                                 <Button onClick={this.complete} disabled={this.state.record&&(this.state.record.stateID==10||this.state.record.stateID==20) ? false : true}>{this.state.record&&this.state.record.stateID?this.state.record.stateID==10?'Completed':'Cancel completed':'Completed'}</Button>   :
                                 <Button onClick={this.complete} disabled={this.state.record&&(this.state.record.stateID==10||this.state.record.stateID==20) ? false : true}>{this.state.record&&this.state.record.stateID?this.state.record.stateID==10?'完成':'取消完成':'完成'}</Button>
                                }
                                    <Button style={{margin: '0 0 0 30px'}} type="dashed" onClick={printStkPay.bind(this,this.state.paymentID)}>{ChineseEnglishSize.MaterialPaymentManagementprint ? ChineseEnglishSize.MaterialPaymentManagementprint.descripts:'打印'}</Button>
                                    <Button disabled={this.state.paymentID ? false : true} style={{margin: '0 30px'}} onClick={this.removePayment}>{ChineseEnglishSize.MaterialPaymentManagementdelete ? ChineseEnglishSize.MaterialPaymentManagementdelete.descripts:'删除'}</Button>
                                    <Button onClick={this.addPaymentReceipt}>{ChineseEnglishSize.MaterialPaymentManagementadd ? ChineseEnglishSize.MaterialPaymentManagementadd.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={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.MaterialPaymentManagementsupplier ? ChineseEnglishSize.MaterialPaymentManagementsupplier.descripts:'供应商'}</div>}
                            >
                                <div className="drugList " style={{height: store.getState().tableHeight.y +87 + 'px'}}>
                                    <Table
                                        columns={columns.length>0 ? columns : this.columns}
                                        dataSource={this.state.SelectData ? this.state.SelectData.vendor : []}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: 200, y: store.getState().tableHeight.y - 6}}
                                        style={{height: (store.getState().tableHeight.y + 75)}}
                                        rowClassName={this.setRowClassName}
                                        rowKey={record => record.key}
                                        className='waListHeight'
                                        onRow={(record) => {
                                            return {
                                                onClick: (e) => {
                                                    standingNumber = 9999;
                                                    e.stopPropagation();
                                                    if (this.state.detailsId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({detailsId: record.id, page: 1},()=>{
                                                            this.getWarehouseList()
                                                        });
                                                    } else {
                                                        if (this.state.detailsId !== record.id) {
                                                            this.setState({detailsId: record.id, page: 1},()=> {
                                                                this.getWarehouseList()
                                                            });
                                                        } 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.MaterialPaymentManagementreceipt ? ChineseEnglishSize.MaterialPaymentManagementreceipt.descripts:'付款单'}</span>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => { this.columnRef.onOpenModel();}}><Icon type="setting" title={ChineseEnglishSize.MaterialPaymentManagementcolumnSettings ? ChineseEnglishSize.MaterialPaymentManagementcolumnSettings.descripts:'列权限设置'} /></span>}
                            >
                                <div style={{height: store.getState().tableHeight.y + 37 + 'px'}}>
                                    <Table
                                        columns={modalColumns.length>0 ? modalColumns : this.modalColumns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        style={{height: (store.getState().tableHeight.y + 50)}}
                                        scroll={{x: this.state.detailWidthTotal ? this.state.detailWidthTotal : 1620, y: store.getState().tableHeight.y - 6 }}
                                        rowKey={record => record.key}
                                        className='detailsHeight'
                                        rowClassName={this.setPaymentClassName}
                                        onRow={(record) => {
                                            return {
                                                onClick: (e) => {
                                                    e.stopPropagation();
                                                    if (this.state.paymentID === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({paymentID: record.stkPayID},()=>{
                                                        });
                                                        this.setState({record:record});
                                                    } else {
                                                        if (this.state.paymentID !== record.stkPayID) {
                                                            this.setState({paymentID: record.stkPayID},()=> {
                                                            });
                                                            this.setState({record:record});
                                                        } else {
                                                            this.setState({paymentID: ''});
                                                            this.setState({record:{}});
                                                        }
                                                    }
                                                },
                                            };
                                        }}
                                    />
                                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.WaListData}
                                                      loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <AddPayment SelectData={this.state.SelectData} onRef={this.onRef}  handleThis={this} ChineseOrEnglish = {this.state.ChineseEnglishSize}/>

                    {/*//显示表头修改弹窗*/}
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='MaterialPaymentManagement'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);
export default PaymentManagement;