// 库存转移明细录入列表
import React from 'react';
import { Card, Row, Col, Form, Icon, Table, message } from 'antd';
import { Util } from 'tools';
import { Resizable } from 'react-resizable';
import { $http } from 'containers/config/https';
import store from 'store';
import InventoryFormModal from './../../../common/InventoryFormModal';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const ResizeableTitle = props => {
    const { onResize, width, ...restProps } = props;
    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};

const ShiftDetailList = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                unitData: [], // 单位下拉框数据
                modalData: [], // 弹框列表数据
                // data: [], // 列表数据
                detailInfo: [], // 入库制单回显至明细列表数据
                tacitlyApproveData: {}, // 初始化数据
                stockID: '', // 回显的描述id
                frLocID: '',
                toLocDr: '',
                stkCatID: '',
                pageSize: 10,
                page: 1,
                inputData: '',
                getBatchDetail: {},
                unitDesc: '',
                unitDate: [],
                columns: [],
                detailWidthTotal: '',
                show: false, //收缩图标
                ChineseEnglishSize: {}, //中英翻译
                language: JSON.parse(window.sessionStorage.userData),
                SelectData: {}, //下拉数据
            };
            this.columns = [
                {
                    title: '单号',
                    dataIndex: 'adjNO',
                    key: 'adjNO',
                    align: 'center',
                    width: 150
                }, {
                    title: '药品--批次',
                    dataIndex: 'stock',
                    key: 'stock',
                    width: 150,
                    align: 'center',
                    render: (text, record) => {
                        return text ? text.stkBatNo ? text.stockDesc + '--' + text.stkBatNo : text.stockDesc : '';
                    }
                }, {
                    title: '调前售价',
                    dataIndex: 'priorSp',
                    key: 'priorSp',
                    width: 50,
                    align: 'center',
                }, {
                    title: '调后售价',
                    dataIndex: 'resultSp',
                    key: 'resultSp',
                    width: 50,
                    align: 'center',
                }, {
                    title: '调价单位',
                    dataIndex: 'unitDesc',
                    key: 'unit',
                    width: 100,
                    align: 'center',
                }, {
                    title: '单价(基本)',
                    dataIndex: 'resultBaseSp',
                    key: 'resultBaseSp',
                    width: 100,
                    align: 'center'
                }, {
                    title: '计划生效日期',
                    dataIndex: 'preExeDate',
                    key: 'preExeDate',
                    width: 150,
                    align: 'center',
                }, {
                    title: '调价原因',
                    dataIndex: 'reasonDesc',
                    key: 'reason',
                    width: 100,
                    align: 'center',
                }, {
                    title: '备注',
                    dataIndex: 'remark',
                    key: 'remark',
                    width: 100,
                    align: 'center'
                }, {
                    title: '批准文号',
                    dataIndex: 'warrentNO',
                    key: 'warrentNO',
                    width: 150,
                    align: 'center',
                }, {
                    title: '批文日期',
                    dataIndex: 'WNODate',
                    key: 'WNODate',
                    width: 150,
                    align: 'center',
                }, {
                    title: '状态',
                    dataIndex: 'state',
                    key: 'state',
                    width: 100,
                    align: 'center',
                    render: (text, record) => {
                        return text ? text.desc : '';
                    }
                }, {
                    title: '医院',
                    dataIndex: 'hosp',
                    key: 'hosp',
                    width: 150,
                    align: 'center',
                    render: (text, record) => {
                        return text ? text.desc : '';
                    }
                }, {
                    title: '创建人',
                    dataIndex: 'createUser',
                    key: 'createUser',
                    width: 100,
                    align: 'center',
                    render: (text, record) => {
                        return text ? text.desc : '';
                    }
                }, {
                    title: '审核日期',
                    dataIndex: 'auditDate',
                    key: 'auditDate',
                    width: 100,
                    align: 'center',
                }, {
                    title: '审核时间',
                    dataIndex: 'auditTime',
                    key: 'auditTime',
                    width: 100,
                    align: 'center',
                }, {
                    title: '审核人',
                    dataIndex: 'auditUser',
                    key: 'auditUser',
                    width: 100,
                    align: 'center',
                    render: (text, record) => {
                        return text ? text.desc : '';
                    }
                }
            ];
        }

        components = {
            header: {
                cell: ResizeableTitle,
            },
        };

        componentDidMount() {
            this.props.onRef(this);
            //下拉数据
            this.getSelectData();
            this.getDetailTableColumns();
            let leftList = document.querySelectorAll('.shiftHeight  .ant-table-body');
            if (leftList.length > 0) {
                leftList[0].style.height = store.getState().tableHeight.y + 19 + 'px';
            }
        }

        componentWillReceiveProps(props) {
            this.setState({ stkCatID: props.stkCat, frLocID: props.inOpLocDr, toLocDr: props.toLocDr });
            if (this.state.tacitlyApproveData) {
                this.setState({ tacitlyApproveData: props.handleThis.state.tacitlyApproveData });
            }
            if (props.detailInfo !== this.state.detailInfo) {
                let arr = [...props.detailInfo];
                this.setState({ data: arr, detailInfo: props.detailInfo });
            }
        }

        // 获取下拉框的数据
        getSelectData() {

            $http.post('urlS', this, {
                code: "02020038",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({ SelectData: res.result });
                    } else {
                        this.setState({ SelectData: {} })
                    }
                }
            })
        }

        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let { language } = this.state;
            let data = {
                params: [{
                    reactCode: ['PriceAdjustmentFormEnt'],
                    compontName: 'PriceAdjustmentFormEnt',
                    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>,
                                ellipsis: true,
                                render: (text, record, index) => {
                                    if (item.code === 'index') {
                                        return index;
                                    } else {
                                        return text;
                                    }

                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ columns: filterArr, detailWidthTotal: res.totalWidth, ChineseEnglishSize: language.language == 'EN' ? res.result.language.EN : res.result.language.CN }, () => {
                            this.props.handleThis.getChineseEnglishSize(this.state.ChineseEnglishSize)
                        })
                    }
                }
            })
        }

        // 点击删除时阻止事件冒泡
        handlePopconfirm = (e) => {
            e.stopPropagation();
        }

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

        // 保存成功后清空data数据
        deleteData() {
            this.setState({ data: [], detailInfo: [] });
        }

        // 获取描述列表数据
        getModalListData(alias) {
            let data = {
                params: [
                    {
                        stockAlias: alias, // 库存项描述别名
                        stkCatID: this.state.stkCatID ? this.state.stkCatID : undefined,
                        locID: this.state.frLocID ? this.state.frLocID : undefined,
                    }
                ],
                pagination: [
                    {
                        pageSize: this.state.pageSize,
                        currentPage: this.state.page,
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020103",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        for (var i = 0; i < res.result.rows.length; i++) {
                            res.result.rows[i].key = i
                        }
                        this.setState({ modalData: res.result, inputData: alias })
                    } else {
                        this.setState({ modalData: [], inputData: '' })
                    }
                }
            })
        }

        // 新增明细录入
        addHandle = (obj) => {
            let inOpStatusDr = this.props.handleThis.state.userInfo ? this.props.handleThis.state.userInfo.stateID : '';
            if (+inOpStatusDr < 20 || inOpStatusDr === undefined) {
                let arr = [...this.state.data];
                if (obj.key) {
                    for (let i = 0, len = arr.length; i < len; i++) {
                        if (arr[i].key === obj.key) {
                            arr[i] = obj;
                        }
                    }
                } else {
                    arr.push(obj);
                    for (let i = 0; i < arr.length; i++) {
                        !arr[i].key ? arr[i].key = i + 'detail' : '';
                    }
                }
                this.setState({ data: arr }, () => {
                    this.childDesc.resetFields();
                    this.resetFields();
                    if (this.state.stockID && +inOpStatusDr < 20) {
                        this.props.handleThis.saveHandle()
                    }
                });
            } else {
                message.error("当单据状态为保存时才可以进行操作");
            }
        }

        // 重置表单
        resetFields = () => {
            this.props.form.resetFields(); //清空所有
            this.setState({ userInfo: {}, rowKey: '', stockID: '', inputData: '', getBatchDetail: {} });
            this.childDesc.resetFields();
        }

        // 删除
        handleDelete = (record, e) => {
            e.stopPropagation();
            if (record.transDetailID) {
                // 当inOpDetailID存在的话则删除接口明细、不存在的话切割数组当中的一个对象
                let inOpStatusDr = this.props.handleThis.state.userInfo ? this.props.handleThis.state.userInfo.stateID : '';
                if (+inOpStatusDr < 20 || inOpStatusDr === undefined) {
                    let data = {
                        params: {
                            detail: [{
                                transDetailID: record.transDetailID ? record.transDetailID : undefined,
                            }]

                        }
                    };
                    $http.post('urlS', this, {
                        code: "02020100",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                message.success(res.errorMessage);
                                // this.props.handleThis.resetFieldsAll();
                                this.deleteRow(record.key);
                            }
                        }
                    })
                } else {
                    message.error("当单据状态为保存时才可以进行操作");
                }
            } else {
                this.deleteRow(record.key);
            }
        }

        // 本地删除数据
        deleteRow = (key) => {
            const dataSource = JSON.parse(JSON.stringify(this.state.data));
            let filterData = dataSource.filter(item => item.key !== key);
            this.setState({ data: Util.addKeyValueToDataSource(filterData), userInfo: {}, rowKey: '', stockID: '', getBatchDetail: {} });
        }

        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    // this.resetFields();
                    if (this.state.rowKey === '') {
                        this.setState({ rowKey: record.key, userInfo: record, stockID: record.adjID, unitData: record.unit });
                    } else {
                        if (this.state.rowKey !== record.key) {
                            this.setState({ rowKey: record.key, userInfo: record, stockID: record.adjID, unitData: record.unit }
                            );

                        } else {
                            this.setState({ rowKey: '', userInfo: {}, stockID: '', unitData: [], unitDesc: '' });
                            this.resetFields();
                            this.childDesc.resetFields();
                        }
                    }
                }
            }
        };

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

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

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

        //药品名称为空时清除表单数据
        clearData = (val) => {
            if (!val.target.value) {
                this.setState({ userInfo: {}, getBatchDetail: {} });
            }
        }

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

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

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

        handleResize = index => (e, { size }) => {
            this.setState(({ columns }) => {
                const nextColumns = [...columns];
                nextColumns[index] = {
                    ...nextColumns[index],
                    width: parseInt(size.width),
                };
                return { columns: nextColumns };
            });
        }

        render() {
            let { detailWidthTotal, ChineseEnglishSize } = this.state;
            const columns = this.state.columns.map((col, index) => ({
                ...col,
                onHeaderCell: column => ({
                    width: parseInt(column.width),
                    onResize: this.handleResize(index),
                }),
            }));
            return (
                <div>
                    <Row>
                        <Col span={10} 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.StockTransferMakingForminventoryMakingEntry ? ChineseEnglishSize.StockTransferMakingForminventoryMakingEntry.descripts : '调价制单录入'}</div>}
                            >
                                <div style={{ height: store.getState().tableHeight.y + 65 + 'px', overflow: 'auto' }} className="InPurPlan-detail-left">
                                    <InventoryFormModal parameter='PriceAdjustment' APICode='02020346' DetailCode='02020347' formCode='02020348' unitData={this.state.unitData} SelectData={this.state.SelectData} rowKey={this.state.rowKey} userInfo={this.state.userInfo} handelThis={this} onRef={this.childDesc} />
                                </div>
                            </Card>
                        </Col>
                        <Col span={this.state.show ? 24 : 14}>
                            <Card
                                size="small"
                                title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />{ChineseEnglishSize.StockTransferMakingForminventoryMaking ? ChineseEnglishSize.StockTransferMakingForminventoryMaking.descripts : '调价制单列表'}</span>}
                                extra={<span style={{ color: '#666' }} className='span' onClick={() => { this.columnRef.onOpenModel(); }}><Icon type="setting" title={ChineseEnglishSize.StockTransferMakingFormcolumnSettings ? ChineseEnglishSize.StockTransferMakingFormcolumnSettings.descripts : '列权限设置'} /></span>}
                            >
                                <div>
                                    <Table
                                        columns={columns.length > 0 ? columns : this.columns}
                                        components={this.components}
                                        dataSource={this.state.data}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: detailWidthTotal ? detailWidthTotal : 1900, y: store.getState().tableHeight.y + 19 }}
                                        onRow={this.onClickRow}
                                        rowClassName={this.setRowClassName}
                                        className="shiftHeight"
                                    />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PriceAdjustmentFormEnt'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);

export default ShiftDetailList;