import React from 'react';
import { Modal, Row, Col, Button, Table, Select , DatePicker, Pagination, message, Form, Input, Card, Checkbox } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';

const { Option } = Select;
var newNum =0;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const FormItem = Form.Item;
const InquireWarehouseVoucher = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                visible: false,
                tableData: [],
                startDate: undefined, // 开始日期
                endDate: undefined, // 截止日期
                status: undefined, // 单据状态
                rowId: '', // 选中行id
                total: 0, // 总条数
                page: 1, // 页数
                pageSize: 10, // 每页的条数
                stateCode: {},
                WaListData:{},
                checked: false,
                saveTableData: [],
                sendListData: [],
                selectedRowKeys: [],
                language: JSON.parse(window.sessionStorage.userData),
                ChineseOrEnglish:{},
                columnsRight:[],
                columns:[],
                columnsWidth:'',
                detailWidthTotal :''
            };
            // 药品的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '供应商',
                    dataIndex: 'descripts',
                    align: "center",
                    width: '100%'
                }
            ];
            this.columnsRight = [
                {
                    key: 1,
                    title: '入库/退货单号',
                    dataIndex: 'NO',
                    align: "center",
                    width: '180px'
                },
                {
                    key: 8,
                    title: '供应商',
                    dataIndex: 'vendorDesc',
                    align: "center",
                    width: '180px'
                },
                {
                    key: 2,
                    title: '类型',
                    dataIndex: 'type',
                    align: "center",
                    width: '80px',
                },
                {
                    key: 3,
                    title: '进价金额',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 4,
                    title: '未付金额',
                    dataIndex: 'NoPay',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 5,
                    title: '将付金额',
                    dataIndex: 'willPay',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 6,
                    title: '科室',
                    dataIndex: 'locDesc',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 7,
                    title: '日期',
                    dataIndex: 'auditDate',
                    align: "center",
                    width: '150px',
                }
            ];
                this.columnsRight2 = [
                    {
                        key: 1,
                        title: '入库/退货单号',
                        dataIndex: 'NO',
                        align: "center",
                        width: '180px'
                    },
                    {
                        key: 8,
                        title: '发票号',
                        dataIndex: 'invNo',
                        align: "center",
                        width: '180px'
                    },
                    {
                        key: 9,
                        title: '供应商',
                        dataIndex: 'vendorDesc',
                        align: "center",
                        width: '180px'
                    },
                    {
                        key: 2,
                        title: '类型',
                        dataIndex: 'type',
                        align: "center",
                        width: '80px',
                    },
                    {
                        key: 3,
                        title: '进价金额',
                        dataIndex: 'rpAmt',
                        align: "center",
                        width: '150px',
                    },
                    {
                        key: 4,
                        title: '未付金额',
                        dataIndex: 'NoPay',
                        align: "center",
                        width: '150px',
                    },
                    {
                        key: 5,
                        title: '将付金额',
                        dataIndex: 'willPay',
                        align: "center",
                        width: '150px',
                    },
                    {
                        key: 6,
                        title: '科室',
                        dataIndex: 'locDesc',
                        align: "center",
                        width: '150px',
                    },
                    {
                        key: 7,
                        title: '日期',
                        dataIndex: 'auditDate',
                        align: "center",
                        width: '150px',
                    }
                ]
        }

        componentDidMount() {
            // 获取列表数据
            this.props.onRef(this);
            let leftList = document.querySelectorAll('.leftListHeight  .ant-table-body');
            if(leftList.length>0){
                leftList[0].style.height = store.getState().tableHeight.y - 105 + 'px';
            }
            let listData = document.querySelectorAll('.listHeight  .ant-table-body');
            if(listData.length>0){
                listData[0].style.height = store.getState().tableHeight.y - 105 + 'px';
            }
            this.getDetailTableColumns();
            this.getColumnsLeft();
        }

        //props变化是即使更新props
        componentWillReceiveProps(props){
            this.setState({WaListData: props.SelectData,ChineseOrEnglish:props.ChineseOrEnglish})
        }

        // 打开弹框
        showModal = () => {
            this.setState({
                visible: true
           });
        };

        // 确定
        handleOk = (e) => {
            let {ChineseOrEnglish} = this.state;
            if (this.state.rowId) {
                this.props.handleThis.getEchoData(this.state.rowId);
                this.handleCancel()
            } else {
                message.error(ChineseOrEnglish.MaterialPaymentManagementselectOperatedDataTips ? ChineseOrEnglish.MaterialPaymentManagementselectOperatedDataTips.descripts:"请选择一条需要操作的数据");
            }
        };

        // 关闭
        handleCancel = (e) => {
            this.setState({
                visible: false,
                status: undefined,
            });
        };

        // 获取列表数据
        getTableData() {
            let {ChineseOrEnglish} = this.state;
            let locDesc = this.props.form.getFieldValue('locDesc');
            let EndData = this.props.form.getFieldValue('end');
            let StartDate = this.props.form.getFieldValue('start');
            let NO = this.props.form.getFieldValue('NO');
            let {page, pageSize} = this.state;
            let data = {
                params: [
                    {
                        NO: NO ? NO : undefined,
                        begin: StartDate ? Moment(StartDate).format('YYYY-MM-DD') : '',
                        end: EndData ? Moment(EndData).format('YYYY-MM-DD') : '',
                        locID: locDesc ? locDesc : undefined,
                        vendorID: this.state.rowId ? this.state.rowId : undefined,
                        invFlag: this.state.checked ? 1 : 0,
                    }
                ],
                pagination: [
                    {
                        pageSize: pageSize,
                        currentPage: page,
                        sort: "",
                        dir: "",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02060101",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if(res.result.length > 0){
                            for(var i = 0; i < res.result.length; i++) {
                                res.result[i].key = i+'data';
                            }
                            this.setState({tableData: res.result, total: res.total});
                        }else {
                            this.setState({tableData: [], total: 0});
                            message.error(ChineseOrEnglish.MaterialPaymentManagementnoData ? ChineseOrEnglish.MaterialPaymentManagementnoData.descripts:'没数据');
                        }
                    }
                }
            })
        }


        // 取消选中
        handleUncheck() {
            this.setState({rowId: ''});
        }

        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: () => {
                    if (this.state.rowId === '') {
                        // 保存行数据以及ID
                        this.setState({rowId: record.id },()=>{
                            this.getTableData();
                        })
                    } else {
                        if (this.state.rowId !== record.id ) {
                            this.setState({rowId: record.id },() => {
                                this.getTableData();
                            })
                        }
                        // else {
                        //     this.setState({rowId: '' })
                        // }
                    }
                }
            }
        };

        // 表格行的类名
        setRowClassName = (record) => {
            return record.id  === this.state.rowId ? 'clickRowStyle' : '';
        };

        // 页码改变的回调，参数是改变后的页码及每页条
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: pageSize}, () => {
                this.getTableData()
            })
        };

        // 条数改变的回调
        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                this.getTableData();
            })
        };

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        //勾选按发票查询
        onChangeInvFlag = e => {
            this.setState({
                checked: e.target.checked,
            },()=> {
                this.getTableData();
            });
            this.state.checked?this.getDetailTableColumns():this.getDetailTableColumns2();
        };


        //页面中英文翻译
        getDetailTableColumns = (list) => {
            let {language} = this.state;
            let data = {
                params: [{
                    compontName: list?list:'MaterialPaymentSupplementaryPa',
                    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>{language.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columnsRight: filterArr, detailWidthTotal: res.totalWidth})
                    }
                }
            })
        };

        //页面中英文翻译
        getDetailTableColumns2 = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    compontName: 'MaterialPaymentNewReprotAccInv',
                    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>{language.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columnsRight2: filterArr, detailWidthTotal2: res.totalWidth})
                    }
                }
            })
        };


        //页面中英文翻译
        getColumnsLeft = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    compontName: 'MaterialPaymentManAddLeftC',
                    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>{language.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, columnsWidth: res.totalWidth})
                    }
                }
            })
        };


        // 保存
        saveTableData =()=> {
            let data = {
                params: [
                    {
                        vendorID: this.state.rowId ? this.state.rowId : undefined,
                        remark: undefined,
                        detail: this.state.sendListData ? this.state.sendListData : undefined ,
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02060102",
                data: data,
                success: function (res) {
                    if (res.errorCode == '0'){
                        this.setState({selectedRowKeys: []});
                        message.success(res.errorMessage);
                        this.props.handleThis.getWarehouseList('1');
                        this.getTableData();
                        this.handleCancel();
                    }else {
                        this.setState({selectedRowKeys: []});
                    }
                }
            })
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            let {ChineseOrEnglish,columns,columnsRight,columnsRight2} = this.state;
            const rowSelection = {
                selectedRowKeys: this.state.selectedRowKeys,
                onChange: (selectedRowKeys, selectedRows) => {
                    newNum = 0;
                    for (var i=0; i<selectedRows.length; i++){
                        newNum += selectedRows[i].willPay
                    }
                    this.setState({
                        sendListData: selectedRows,
                        selectedRowKeys
                    })
                }
            };
            return (
                <Modal
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    width={1300}
                    className="addPayment"
                    footer={null}
                >
                    <div className="aa">
                        <Row>
                            <Card
                                size="small"
                                title={ChineseOrEnglish.MaterialPaymentManagementaddPayDoc ? ChineseOrEnglish.MaterialPaymentManagementaddPayDoc.descripts:'新增付款单据'}
                            >
                                <Col span={18}>
                                    <Form>
                                        <Row >
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label={ChineseOrEnglish.MaterialPaymentManagementNO ? ChineseOrEnglish.MaterialPaymentManagementNO.descripts:'单号'}>
                                                    {getFieldDecorator('NO',{
                                                        initialValue: undefined,
                                                    })(
                                                        <Input placeholder={ChineseOrEnglish.MaterialPaymentManagementNoTips ? ChineseOrEnglish.MaterialPaymentManagementNoTips.descripts:'搜索入库单或退货单'} />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label={ChineseOrEnglish.MaterialPaymentManagementloc ? ChineseOrEnglish.MaterialPaymentManagementloc.descripts:'科室'}>
                                                    {getFieldDecorator('locDesc',{
                                                        initialValue: undefined,
                                                    })(
                                                        <Select allowClear={true}>
                                                            {this.state.WaListData.loc && this.state.WaListData.loc.map((item, i) => {
                                                                return <Option value={item.id} key={i}>{item.descripts} </Option>
                                                            })}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={4} className="queryTime" style={{marginLeft: '30px'}}>
                                                <FormItem>
                                                    {getFieldDecorator('start',{
                                                        initialValue: Moment(),
                                                        rules:[{ required : ChineseOrEnglish.MaterialPaymentManagementStartData ? ChineseOrEnglish.MaterialPaymentManagementStartData.required =='Y'? true:false: false, message: ChineseOrEnglish.MaterialPaymentManagementStartData ? ChineseOrEnglish.MaterialPaymentManagementStartData.message:'起始日期不能为空'}]
                                                    })(
                                                        <DatePicker  style={{width: '100%'}}  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={1} style={{    textAlign: 'center', lineHeight: '37px'}}>
                                                <span>到</span>
                                            </Col>
                                            <Col span={4}  className="queryTime">
                                                <FormItem>
                                                    {getFieldDecorator('end',{
                                                        initialValue: Moment(),
                                                        rules:[{ required : ChineseOrEnglish.MaterialPaymentManagementdeadline ? ChineseOrEnglish.MaterialPaymentManagementdeadline.required =='Y'? true:false: false, message: ChineseOrEnglish.MaterialPaymentManagementdeadline ? ChineseOrEnglish.MaterialPaymentManagementdeadline.message:'截至日期不能为空'}] 
                                                    })(
                                                        <DatePicker  style={{width: '100%'}}  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Form>
                                </Col>
                                <Col span={3}  style={{marginLeft: '-50px'}}>
                                    <Row style={{marginTop: '4px'}} className="buttonLeft">
                                        <Button onClick={()=> {this.getTableData()}}>{ChineseOrEnglish.MaterialPaymentManagementsearch ? ChineseOrEnglish.MaterialPaymentManagementsearch.descripts:'查询'}</Button>
                                    </Row>
                                </Col>
                                <Col span={3} style={{textAlign: 'right'}}>
                                    <Row style={{marginTop: '4px'}} className="buttonRight">
                                        <Button onClick={this.saveTableData}>{ChineseOrEnglish.MaterialPaymentManagementsave ? ChineseOrEnglish.MaterialPaymentManagementsave.descripts:'保存'}</Button>
                                    </Row>
                                </Col>
                            </Card>
                        </Row>
                        <Row>
                            <Col span={7}></Col>
                            <Col span={17} style={{textAlign: 'center'}}>
                                <span style={{float: 'left',marginLeft: '12px'}}>
                                    <Checkbox
                                    checked={this.state.checked}
                                    onChange={this.onChangeInvFlag}>
                                        {ChineseOrEnglish.MaterialPaymentManagementaccToInvoice ? ChineseOrEnglish.MaterialPaymentManagementaccToInvoice.descripts:'按发票'}
                                    </Checkbox>
                                </span>
                                <span>{ChineseOrEnglish.MaterialPaymentManagementtotalAmount ? ChineseOrEnglish.MaterialPaymentManagementtotalAmount.descripts:'付款单总金额：'} <span>{newNum}</span></span>
                                <span  style={{float: 'right',paddingRight: '58px'}}>{ChineseOrEnglish.MaterialPaymentManagementselectedOrReturn ? ChineseOrEnglish.MaterialPaymentManagementselectedOrReturn.descripts:'已选入库/退货单：'} <span>{this.state.selectedRowKeys.length}</span></span>
                            </Col>
                        </Row>
                        <Row style={{margin: '0 20px', paddingBottom: '20px'}}>
                            <Col span={7} style={{height: store.getState().tableHeight.y -75 + 'px', border: '1px silver solid'}}>
                                        <Table
                                            columns={columns.length>0  ? columns : this.columns}
                                            dataSource={this.state.WaListData.vendor ? this.state.WaListData.vendor : []}
                                            pagination={false}
                                            bordered
                                            scroll={{ y: store.getState().tableHeight.y - 167}}
                                            style={{overflow: 'auto', height: store.getState().tableHeight.y - 117}}
                                            rowKey={record => record.key}
                                            className='leftListHeight'
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                            </Col>
                            <Col span={17} style={{height: store.getState().tableHeight.y -75 + 'px', border: '1px silver solid'}}>
                                <Table
                                    rowSelection={rowSelection}
                                    columns={this.state.checked?columnsRight2:columnsRight}
                                    dataSource={this.state.tableData}
                                    pagination={false}
                                    bordered
                                    scroll={{x:this.state.checked ? 1370 : 1190, y: store.getState().tableHeight.y - 167}}
                                    style={{overflow: 'auto', height: store.getState().tableHeight.y - 117}}

                                    className='listHeight'
                                />
                            </Col>
                        </Row>
                    </div>
                </Modal>
            )
        }
    }
)
export default InquireWarehouseVoucher