// 退货审核
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Table, Switch, message, Icon } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less';
var serialNumber = 0; //退货单序列号

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span: 16 },
    wrapperCol: { span: 8 },
};

const SalesReturnCheck = 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: [], //退货单数据
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                page2: 1,
                total: 0,
                detailTotal: 0,
                warehouseListId: '',
                noData: false,
                stateID: '',
                detailWidthTotal: '',
                columns: [],
                modalColumns: [],
                modificationList: false,  //默认隐藏修改表头弹窗
                showDetailPopup: false,  //默认隐藏修改表头弹窗
                listLength: '',  //列表长度
                ChineseEnglishSize: {}, //中英数据
            }
            // 退货单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '退货单号',
                    dataIndex: 'stkReturnNO',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 2,
                    title: '科室名称',
                    dataIndex: 'locDesc',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 3,
                    title: '制单日期',
                    dataIndex: 'createDate',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 4,
                    title: '制单时间',
                    dataIndex: 'createTime',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 5,
                    title: '制单人',
                    dataIndex: 'createUserName',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 6,
                    title: '单据状态',
                    dataIndex: 'stateDesc',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 7,
                    title: '审核人',
                    dataIndex: 'auditUserName',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 8,
                    title: '审核日期',
                    dataIndex: 'auditDate',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 9,
                    title: '审核时间',
                    dataIndex: 'auditTime',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 10,
                    title: '进价金额',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 11,
                    title: '售价金额',
                    dataIndex: 'spAmt',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 12,
                    title: '退货原因',
                    dataIndex: 'reasonDesc',
                    align: "center",
                    width: '8%'
                },
                {
                    key: 13,
                    title: '备注',
                    dataIndex: 'remark',
                    align: "center",
                    width: '8%'
                },
            ]
            // 退货单详细表头
            this.modalColumns = [
                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'NO',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 2,
                    title: '药品名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 3,
                    title: '规格',
                    dataIndex: 'spec',
                    align: "center",
                    width: '8%'
                },
                {
                    key: 4,
                    title: '厂家',
                    dataIndex: 'manfDesc',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 5,
                    title: '批号/效期',
                    dataIndex: 'batExp',
                    align: "center",
                    width: '9%'
                },
                {
                    key: 6,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '6%'
                },
                {
                    key: 7,
                    title: '退货数量',
                    dataIndex: 'qty',
                    align: "center",
                    width: '8%'
                },
                {
                    key: 8,
                    title: '进价',
                    dataIndex: 'rp',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 9,
                    title: '售价',
                    dataIndex: 'sp',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 10,
                    title: '进价金额',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 11,
                    title: '售价金额',
                    dataIndex: 'spAmt',
                    align: "center",
                    width: '7%'
                },
                {
                    key: 12,
                    title: '备注',
                    dataIndex: 'remark',
                    align: "center",
                    width: '8%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            this.getDetailListTableColumns();
            let leftList = document.querySelectorAll('.tableListHeight  .ant-table-body');
            if (leftList.length > 0) {
                leftList[0].style.height = (store.getState().tableHeight.y) / 2 + 'px';
            }
            let listData = document.querySelectorAll('.tableDetailHeight  .ant-table-body');
            if (listData.length > 0) {
                listData[0].style.height = (store.getState().tableHeight.y) / 2 + 'px';
            }
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state, callback) => { return; }
        }

        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let { userInfo } = this.state;
            let data = {
                params: [{
                    reactCode: ['DrugReturnReview'],
                    compontName: 'SalesReturnCheckList',
                    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.setState({ parameterCode: 'SalesReturnCheckList' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}>{userInfo.language == 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ columns: filterArr, detailWidthTotal: res.totalWidth, ChineseEnglishSize: userInfo.language == 'EN' ? res.result.language.EN : res.result.language.CN })
                    }
                }
            })
        };

        // 获取明系列表头数据
        getDetailListTableColumns = () => {
            let { userInfo } = this.state;
            let data = {
                params: [{
                    compontName: 'SalesReturnDetailList',
                    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.setState({ parameterCode: 'SalesReturnDetailList' }, () => {
                                        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, listLength: res.totalWidth })
                    }
                }
            })
        };

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

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

        searchInformation = () => {
            this.setState({ page: 1 }, () => {
                this.getWarehouseList()
            })
        };

        // 获取退货主菜单列表数据
        getWarehouseList = () => {
            let { ChineseEnglishSize } = this.state;
            this.setState({ detailsId: '', loading: true });
            let frLoc = this.props.form.getFieldValue('Loc');
            let StartDate = this.props.form.getFieldValue('StartDate');
            let EndData = this.props.form.getFieldValue('EndData');
            let approve = this.props.form.getFieldValue('approve');
            let vendor = this.props.form.getFieldValue('vendor');
            let data = {
                params: [{
                    begin: Moment(StartDate).format('YYYY-MM-DD'),
                    end: Moment(EndData).format('YYYY-MM-DD'),
                    locID: frLoc,
                    stateID: approve ? 30 : 20,
                    vendorID: vendor ? vendor : undefined,

                }],
                pagination: [
                    {
                        pageSize: this.state.pageSize,
                        currentPage: this.state.page,
                        sort: "ID",
                        dir: "asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020168",
                data: data,
                success: function (res) {
                    if (res.rows.length > 0) {
                        for (let i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                        }
                        this.setState({ WaListData: res.rows, total: res.total, warehouseListId: res.rows[0].stkReturnID, page2: 1, stateID: res.rows[0].stateID, loading: false });
                        serialNumber = 0;
                        this.getWarehouseEntryDetails(res.rows[0].stkReturnID);

                    } else {
                        this.setState({ detailsListData: [], WaListData: [], stateID: '' });
                        if (!this.state.noData) {
                            message.error(ChineseEnglishSize.DrugReturnReviewnoData ? ChineseEnglishSize.DrugReturnReviewnoData.descripts : "没数据");
                        } else {
                            this.setState({ noData: false })
                        }
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

        // 获取退货单明细
        getWarehouseEntryDetails(id) {
            this.setState({ detailsLoading: true })
            let data = {
                params: [{
                    stkReturnID: id ? id : this.state.warehouseListId,
                }],
                pagination: [
                    {
                        pageSize: this.state.pageSize2,
                        currentPage: this.state.page2,
                        sort: "ID",
                        dir: "asc",
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02020170",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        serialNumber = this.state.detailsId ? this.state.detailsId : 0;
                        for (let i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                        }
                        this.setState({ detailsListData: res.rows, detailTotal: res.total, detailsLoading: false });
                    }
                }
            })
        }

        // 提交审核确定.
        approveDetermine = () => {
            let { ChineseEnglishSize } = this.state;
            let data = {
                params: [{
                    stkReturnID: this.state.detailsId ? this.state.detailsId : this.state.warehouseListId
                }]
            };

            //是否有审核的内容
            if (this.state.detailsId || this.state.warehouseListId) {
                $http.post('urlS', this, {
                    code: "02020173",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode == '0') {
                            this.setState({ noData: true });
                            this.getWarehouseList();
                            message.success(res.errorMessage);
                        }
                    },
                    error: function (err) {
                        message.error(err.errorMessage);
                    }
                });
            } else {
                message.error(ChineseEnglishSize.DrugReturnReviewselectAuditObject ? ChineseEnglishSize.DrugReturnReviewselectAuditObject.descripts : '请选择审核对象')
            }
        };

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

        // 页码改变的回调，参数是改变后的页码及每页条数 退货单
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                this.getWarehouseList();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                this.onChange(current, size);
            })
        };

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

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

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

        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            const { modalColumns, columns, listLength, detailWidthTotal } = this.state;
            let userInfo = this.state.userInfo ? this.state.userInfo : {};
            //退货部门列表
            let inOpLocDrSelect = [];
            let vendor = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.SelectData.vendor && this.state.SelectData.vendor.map((item, i) => {
                vendor.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            let { ChineseEnglishSize } = this.state;
            return (
                <div className="InventoryBreakageCheck">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.DrugReturnReviewreturnsReview ? ChineseEnglishSize.DrugReturnReviewreturnsReview.descripts : '退货审核'}</div>}
                        >
                            <Col span={18}>
                                <Form>
                                    <Row >
                                        <Col span={7}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.DrugReturnReviewloc ? ChineseEnglishSize.DrugReturnReviewloc.descripts : '科室'}>
                                                {getFieldDecorator('Loc', {
                                                    initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
                                                    rules: [{ required: ChineseEnglishSize.DrugReturnReviewloc ? ChineseEnglishSize.DrugReturnReviewloc.required == 'Y' ? true : false : false, message: ChineseEnglishSize.DrugReturnReviewloc ? ChineseEnglishSize.DrugReturnReviewloc.message : '科室不能为空' }]
                                                })(
                                                    <Select allowClear>
                                                        {inOpLocDrSelect}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={7}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.DrugReturnReviewStartDate ? ChineseEnglishSize.DrugReturnReviewStartDate.descripts : '起初日期'}>
                                                {getFieldDecorator('StartDate', {
                                                    initialValue: this.state.SelectData.params && this.state.SelectData.params.startDate ? Moment(this.state.SelectData.params.startDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                    rules: [{ required: true, message: ChineseEnglishSize.DrugReturnReviewStartDate ? ChineseEnglishSize.DrugReturnReviewStartDate.message : '起初日期不能为空' }]
                                                })(
                                                    <DatePicker />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={7}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.DrugReturnReviewdeadline ? ChineseEnglishSize.DrugReturnReviewdeadline.descripts : '截至日期'}>
                                                {getFieldDecorator('EndData', {
                                                    initialValue: this.state.SelectData.params && this.state.SelectData.params.endDate ? Moment(this.state.SelectData.params.endDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                    rules: [{ required: true, message: ChineseEnglishSize.DrugReturnReviewdeadline ? ChineseEnglishSize.DrugReturnReviewdeadline.message : '截至日期不能为空' }]
                                                })(
                                                    <DatePicker />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={7}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.DrugReturnReviewsupplier ? ChineseEnglishSize.DrugReturnReviewsupplier.descripts : '供应商'}>
                                                {getFieldDecorator('vendor', {
                                                    initialValue: undefined,
                                                    rules: [{ required: ChineseEnglishSize.DrugReturnReviewsupplier ? ChineseEnglishSize.DrugReturnReviewsupplier.required == 'Y' ? true : false : false, message: ChineseEnglishSize.DrugReturnReviewsupplier ? ChineseEnglishSize.DrugReturnReviewsupplier.message : '供应商不能为空' }]
                                                })(
                                                    <Select allowClear>
                                                        {vendor}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={3}>
                                            <FormItem {...formItemSwitch} label={ChineseEnglishSize.DrugReturnReviewCheck ? ChineseEnglishSize.DrugReturnReviewCheck.descripts : '审核'}>
                                                {getFieldDecorator('approve', {
                                                    valuePropName: 'checked',
                                                    initialValue: false,
                                                    rules: [{ required: false }]
                                                })(
                                                    userInfo.language == 'EN' ? <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={6}>
                                <Row className="button">
                                    <Button onClick={this.searchInformation}>{ChineseEnglishSize.DrugReturnReviewsearch ? ChineseEnglishSize.DrugReturnReviewsearch.descripts : '查询'}</Button>
                                    <Button style={{ margin: '5px 15px 0 15px' }} type="primary" onClick={this.handleReset}>{ChineseEnglishSize.DrugReturnReviewclean ? ChineseEnglishSize.DrugReturnReviewclean.descripts : '清屏'}</Button>
                                    <Button type="primary" disabled={this.state.stateID == 20 ? false : true} onClick={this.approveDetermine}>{ChineseEnglishSize.DrugReturnReviewreturnReview ? ChineseEnglishSize.DrugReturnReviewreturnReview.descripts : '退货审核'}</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.DrugReturnReviewreturnForm ? ChineseEnglishSize.DrugReturnReviewreturnForm.descripts : '退货单'}</div>}
                                extra={<span style={{ color: '#666' }} className='span' onClick={() => {
                                    this.setState({ parameterCode: 'SalesReturnCheckList' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}><Icon type="setting" title={ChineseEnglishSize.DrugReturnReviewcolumnSettings ? ChineseEnglishSize.DrugReturnReviewcolumnSettings.descripts : '列权限设置'} /></span>}
                            >
                                <div>
                                    <Table
                                        columns={columns.length > 0 ? columns : this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: detailWidthTotal ? detailWidthTotal : 1500, y: (store.getState().tableHeight.y) / 2 - 85 }}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName}
                                        className="tableListHeight"
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    serialNumber = 9999;
                                                    this.setState({ detailsId: record.stkReturnID, page2: 1, stateID: record.stateID });
                                                    this.getWarehouseEntryDetails(record.stkReturnID)
                                                },

                                            };
                                        }}
                                    />
                                    <CommonPagination size='small' 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>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.DrugReturnReviewreturnOrderDetail ? ChineseEnglishSize.DrugReturnReviewreturnOrderDetail.descripts : '退货单明细'}</div>}
                                extra={<span style={{ color: '#666' }} className='span' onClick={() => {
                                    this.setState({ parameterCode: 'SalesReturnDetailList' }, () => {
                                        this.columnRef.onOpenModel();
                                    })
                                }}><Icon type="setting" title={ChineseEnglishSize.DrugReturnReviewcolumnSettings ? ChineseEnglishSize.DrugReturnReviewcolumnSettings.descripts : '列权限设置'} /></span>}
                            >
                                <div>
                                    <Table
                                        columns={modalColumns.length > 0 ? modalColumns : this.modalColumns}
                                        dataSource={this.state.detailsListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: listLength ? listLength : 1500, y: (store.getState().tableHeight.y) / 2 - 85 }}
                                        rowKey={record => record.key}
                                        className="tableDetailHeight"
                                    />
                                    <CommonPagination size='small' current={this.state.page2} total={this.state.detailTotal} search='search'
                                        onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.detailsListData}
                                        loading={this.state.detailsLoading} onChange={this.onChange2.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName={this.state.parameterCode}
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={() => {
                            if (this.state.parameterCode == 'SalesReturnCheckList') {
                                this.getDetailTableColumns()
                            } else if (this.state.parameterCode == 'SalesReturnDetailList') {
                                this.getDetailListTableColumns()
                            }
                        }}
                    />
                </div>
            )
        }
    }
);

export default SalesReturnCheck;