import React from 'react';
import { Modal, Row, Col, Button, Table, Select , DatePicker, Pagination, message } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import Moment from 'moment';

const { Option } = Select;

export default class InquireWarehouseVoucher extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            tableData: [],
            startDate: undefined, // 开始日期
            endDate: undefined, // 截止日期
            status: undefined, // 单据状态
            rowId: '', // 选中行id
            total: 0, // 总条数
            page: 1, // 页数
            pageSize: 10, // 每页的条数
            stateCode: {},
            locId: '',
            vendor: '',
            showDetailList: false,
            detailWidth: '',
            columns: [],
            language: JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize: {},
        };
        this.columns = [
            {
                key: 1,
                title: '退货科室',
                dataIndex: 'locDesc',
                align: "center",
                width: '20%'
            },
            {
                key: 2,
                title: '退货原因',
                dataIndex: 'reasonDesc',
                align: "center",
                width: '20%',
            },
            {
                key: 3,
                title: '状态',
                dataIndex: 'stateDesc',
                align: "center",
                width: '15%',
            },
            {
                key: 4,
                title: '退货单号',
                dataIndex: 'stkReturnNO',
                align: "center",
                width: '20%',
            },
            {
                key: 5,
                title: '备注',
                dataIndex: 'remark',
                align: "center",
                width: '25%',
            }
        ]
    }

    componentDidMount() {
        // 获取列表数据
        this.props.onRef(this);
        this.getCheckPopup();
    }

    //props变化是即使更新props
    componentWillReceiveProps(props){
        this.setState({locId: props.inOpLocDr , stateCode: props.SelectData, vendor: props.vendor})
    }

    // 获取明系列表头数据
    getCheckPopup = () => {
        let {language} = this.state;
        let data = {
            params: [{
                compontName: 'SalesReturnVouchingCheck',
                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();}}>{language.language== 'EN' ? item.enDescripts : item.title}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({columns: filterArr, detailWidth: res.totalWidth})
                }
            }
        })
    };

    // 设置默认日期
    setTacitlyApproveDate() {
        let data = this.props.SelectData.params;
        if (data) {
            this.setState({startDate: Moment(data.startDate), endDate: Moment(data.endDate)});
        } else {
            this.setState({startDate: Moment(), endDate: Moment()});
        }
    }

    // 打开弹框
    showModal = (v) => {
        this.setState({
            visible: true,
            ChineseEnglishSize:v
        }, () => {
            this.handleQuery();
            // 当this.state.startDate有值则不需要重新加载
            if (this.state.startDate === undefined) {
                this.setTacitlyApproveDate();
            }
        });
    };

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

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

    // 获取列表数据
    getTableData(startDate, endDate, state) {
        this.setState({loading: true})
        let {page, pageSize,ChineseEnglishSize} = this.state;
        let data = {
            params: [
                {
                    begin: startDate ? Moment(startDate).format('YYYY-MM-DD') : '',
                    end: endDate ? Moment(endDate).format('YYYY-MM-DD') : '',
                    stateID: state,
                    locID: this.state.locId ? this.state.locId : undefined,
                    vendorID: this.state.vendor ? this.state.vendor : undefined,

                }
            ],
            pagination: [
                {
                    pageSize: pageSize,
                    currentPage: page,
                    sort: "",
                    dir: "",
                }
            ],
        };
        $http.post('urlS', this, {
            code: "02060052",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    if(res.rows.length > 0){
                        for(var i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                        }
                        this.setState({tableData: res.rows, total: res.total, loading: false});
                    }else {
                        this.setState({tableData: [], total: 0});
                        message.error(ChineseEnglishSize.MaterialReturnOrdernoData ? ChineseEnglishSize.MaterialReturnOrdernoData.descripts:'没数据');
                    }
                }
            }
        })
    }

    // 查询列表数据
    handleQuery = () => {
        this.setState({page: 1, pageSize: 10}, () => {
            let {startDate, endDate, status} = this.state;
            this.getTableData(startDate, endDate, status);
        })
    };

    // 查询条件---开始日期
    handleStartDate = (e) => {
        this.setState({startDate: e})
    };

    // 查询条件---截止日期
    handleEndDate = (e) => {
        this.setState({endDate: e})
    };

    // 查询条件---单据状态
    handleStatus = (e) => {
        this.setState({status: e})
    };

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

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

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

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

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

    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    //组件权限编辑器
    onColumnRef = (ref) => {
        this.columnRef = ref;
    };
    render() {
        let {ChineseEnglishSize} = this.state;
        return (
            <Modal
            title={ChineseEnglishSize.MaterialReturnOrderreturnFormInquiry ? ChineseEnglishSize.MaterialReturnOrderreturnFormInquiry.descripts:'查询退货单'}
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            okText={ChineseEnglishSize.MaterialReturnOrderdetermine ? ChineseEnglishSize.MaterialReturnOrderdetermine.descripts:'确定'}
            cancelText={ChineseEnglishSize.MaterialReturnOrdercancel ? ChineseEnglishSize.MaterialReturnOrdercancel.descripts:'取消'}
            width={800}
            >
            <div style={{height: '445px'}}>
            <Row style={{marginBottom: '24px'}}>
            {ChineseEnglishSize.MaterialReturnOrderstartDate ? ChineseEnglishSize.MaterialReturnOrderstartDate.descripts:'起始日期：'}<DatePicker allowClear={false} style={{width: '130px', marginRight: '20px'}} format="YYYY-MM-DD" value={this.state.startDate} onChange={this.handleStartDate} />
            {ChineseEnglishSize.MaterialReturnOrderendDate ? ChineseEnglishSize.MaterialReturnOrderendDate.descripts:'截止日期：'}<DatePicker allowClear={false} style={{width: '130px', marginRight: '20px'}} format="YYYY-MM-DD" value={this.state.endDate} onChange={this.handleEndDate} />
            {ChineseEnglishSize.MaterialReturnOrderstatus ? ChineseEnglishSize.MaterialReturnOrderstatus.descripts:'单据状态：'}<Select allowClear placeholder={ChineseEnglishSize.MaterialReturnOrderstatus ? ChineseEnglishSize.MaterialReturnOrderstatus.descripts:'单据状态'} style={{width: '130px', marginRight: '20px'}} value={this.state.status} onChange={this.handleStatus} >
                    {this.state.stateCode.state && this.state.stateCode.state.map(item => {
                            return <Option key={item.id} value={item.id} title={item.descripts + item.descriptsSPCode}>{item.descripts}</Option>
                        })}
                    </Select>
                    <Button onClick={this.handleQuery} style={{background: 'rgba(255,255,255,1)'}}>{ChineseEnglishSize.MaterialReturnOrdersearch ? ChineseEnglishSize.MaterialReturnOrdersearch.descripts:'查询'}</Button>
                </Row>
                <Table
                    columns={this.state.columns.length>0 ? this.state.columns : this.columns}
                    dataSource={this.state.tableData}
                    pagination={false}
                    style={{overflow: 'auto', height: '350px'}}
                    onRow={this.onClickRow}
                    rowClassName={this.setRowClassName}
                />
                <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                  onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                                  loading={this.state.loading} onChange={this.onChange.bind(this)} />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='SalesReturnVouchingCheck'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getCheckPopup}
                />
            </div>
        </Modal>
    )
    }
}