// 采购计划制单-依据请求单
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 '../style/index.less';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span:12 },
    wrapperCol: { span: 12 },
};
const AccordingToWarehouse = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                vendor: '',
                detailsListData:[], //请求单单明细数据
                WaListData: [], //请求单数据
                size: 'small',
                pageSize: 10,
                page: 1,
                total:0,
                show: false,
                paymentID: '',
                modalColumns: [],
                visible: false,
                detailWidthTotal: '', // 明细表头长度
                stockID: '', //主表格id
                rowKey: '', //行key值
                ChineseEnglishSize:{},
                columns:[],
                parameterCode: '',
                columnsWidth:''
            };

            // 药品的数据表头
            this.columns = [
                {
                    key: 5,
                    title: '单号',
                    dataIndex: 'PONO',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 1,
                    title: '录入人',
                    dataIndex: 'createUserName',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 2,
                    title: '单据状态',
                    dataIndex: 'stateDesc',
                    align: "center",
                    width: '20%',
                },
                {
                    key: 3,
                    title: '供应商',
                    dataIndex: 'vendorDesc',
                    align: "center",
                    width: '20%',
                },
                {
                    key: 4,
                    title: '备注',
                    dataIndex: 'remark',
                    align: "center",
                    width: '20%',
                }
            ]
            // 付款单详细表头
            this.modalColumns = [
                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 8,
                    title: '名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 2,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 3,
                    title: '本科室数量',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 4,
                    title: '请求数量',
                    dataIndex: 'willPay',
                    align: "center",
                    width: '150px'
                },
                {
                    key: 5,
                    title: '已转移数量',
                    dataIndex: 'createDate',
                    align: "center",
                    width: '150px'
                }
            ]
        }

        componentDidMount() {
            this.props.onRef(this);
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            this.getTableColumns();
        }
        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    compontName: 'purchaseOEList',
                    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: 'purchaseOEList'},()=>{
                                    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})
                    }
                }
            });
        };
        // 获取明系列表头数据
        getTableColumns = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    compontName: 'Order',
                    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: 'Order'},()=>{
                                    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, columnsWidth: res.totalWidth})
                    }
                }
            });
        };
        //清空表格内容
        handleReset = () => {
            this.setState({WaListData: [],detailsListData: [],total: 0});
            this.props.form.setFieldsValue({stockDr: undefined});
            this.props.form.resetFields();
        };

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

        // 获取请求单数据
        getWarehouseList=()=>{
            let {userInfo} = this.state;
            let leftList = document.querySelectorAll('.waListHeight  .ant-table-body');
            if(leftList.length>0){
                leftList[0].style.height = store.getState().tableHeight.y + 10 + 'px';
            }
            this.setState({loading:true});
            this.props.form.validateFields((err , val)=> {
                let obj = JSON.parse(JSON.stringify(val));
                if (err == null) {
                    let data = {
                        params: [{
                            begin: obj.StartDate ? Moment(obj.StartDate).format('YYYY-MM-DD') : '',
                            end: obj.EndDate ? Moment(obj.EndDate).format('YYYY-MM-DD') : '',
                            locID:  obj.locDr ? obj.locDr : undefined,
                            stateCode: '20'
                        }],
                        pagination: [
                            {
                                pageSize:this.state.pageSize,
                                currentPage:this.state.page,
                                sort:"ID",
                                dir:"asc",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02060071",
                        data: data,
                        success: function (res) {
                            if(res.rows.length > 0){
                                for(var i = 0; i < res.rows.length; i++){
                                    res.rows[i].key = i;
                                }
                                this.setState({ WaListData: res.rows,total: res.total,loading:false });
                            }else {
                                this.setState({WaListData: [], detailsListData: [],});
                                message.error(userInfo.language=='EN'?'No relevant data was found.':"没数据")
                            }
                        }
                    });
                }
            });

        };

        // 获取请求单详情
        getRequestForm=()=>{
            let {userInfo} = this.state;
            let listData = document.querySelectorAll('.detailsHeight  .ant-table-body');
            if(listData.length>0){
                listData[0].style.height = store.getState().tableHeight.y - 255 + 'px';
            }
            let data = {
                params: [{
                    POID: this.state.stockID ? this.state.stockID : undefined,
            }]};
            $http.post('urlS', this, {
                code: "02060073",
                data: data,
                success: function (res) {
                    if(res.rows.length > 0){
                        for(var i = 0; i < res.rows.length; i++){
                            res.rows[i].key = i;
                        }
                        this.setState({ detailsListData: res.rows});
                    }else {
                        this.setState({detailsListData: []});
                        message.error(userInfo.language=='EN' ? 'No relevant data was found.':"没数据")
                    }
                }
            });
        };

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

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

        // 收起明细录入
        packUpHandle = () => {
            this.setState({show: !this.state.show, span: 24})
        };
        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };
        // 关闭
        handleCancel = (e) => {
            this.setState({
                visible: false,
                getBatchDetail: [],
                total2: 0,
                rowKey: '',
                rowId: '',
                data: [],//主列表数据
                total: 0,
                page: 1,
                pageSize: 10,
                locId: '',
                toLocID: '',
                stockID: '',
            });
        };
        // 确定
        handleOk = (e) => {
            this.handleCancel()
        };
        // 打开弹框
        showModal = (v) => {
            this.setState({
                visible: true,
                ChineseEnglishSize:v
            });
        };

        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.key, stockID: record.POID},()=>{
                            this.getRequestForm();
                        });
                    } else {
                        if (this.state.rowKey !== record.key) {
                            this.setState({rowKey: record.key, stockID: record.POID},()=>{
                                this.getRequestForm();
                            });
                        } else {
                            this.setState({rowKey: '', stockID: '', detailsListData: []});
                        }
                    }
                }
            }
        };

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

        //保存
        saveData=()=>{
            let {ChineseEnglishSize} = this.state;
            if(this.state.stockID){
                let data = {
                    params: [{
                        POID: this.state.stockID ? this.state.stockID : undefined,
                    }]};
                $http.post('urlS', this, {
                    code: "02060164",
                    data: data,
                    success: function (res) {
                        if(res.errorCode == 0){
                            // this.props.handleThis.childAccordingToData(res);
                            this.props.handleThis.getEchoData(res.main.inOperID);
                            this.handleCancel();
                        }
                    }
                });
            }else {
                message.error(ChineseEnglishSize.MaterialStorageOrderMakingpleaseSelectTheDate ? ChineseEnglishSize.MaterialStorageOrderMakingpleaseSelectTheDate.descripts:'请选择数据')
            }

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

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

            return (
                <Modal
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    width='75%'
                    footer={null}
                    className="AccordingToWarehouse"
                >
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.MaterialStorageOrderMakingreceiptFormbaseOnOrders ? ChineseEnglishSize.MaterialStorageOrderMakingreceiptFormbaseOnOrders.descripts:'入库制单-依据订单'}</div>}
                        >
                            <Col >
                                <Form>
                                    <Col span={20}>
                                        <Row >
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialStorageOrderMakingloc ? ChineseEnglishSize.MaterialStorageOrderMakingloc.descripts:'科室'}>
                                                    {getFieldDecorator('locDr',{
                                                        initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
                                                        rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingloc ? ChineseEnglishSize.MaterialStorageOrderMakingloc.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingloc ? ChineseEnglishSize.MaterialStorageOrderMakingloc.message:'科室不能为空'}] 
                                                    })(
                                                        <Select allowClear={true}>
                                                            {loc}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialStorageOrderMakingstartDate ? ChineseEnglishSize.MaterialStorageOrderMakingstartDate.descripts:'起始日期'}>
                                                    {getFieldDecorator('StartDate',{
                                                        initialValue: this.state.queryCondition.startDate ? Moment(this.state.queryCondition.startDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                        rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingstartDate ? ChineseEnglishSize.MaterialStorageOrderMakingstartDate.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingstartDate ? ChineseEnglishSize.MaterialStorageOrderMakingstartDate.message:'起初日期不能为空'}] 
                                                    })(
                                                        <DatePicker style={{width: '100%'}}  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialStorageOrderMakingendDate ? ChineseEnglishSize.MaterialStorageOrderMakingendDate.descripts:'截止日期'}>
                                                    {getFieldDecorator('EndDate',{
                                                        initialValue: this.state.queryCondition.endDate ? Moment(this.state.queryCondition.endDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                        rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingendDate ? ChineseEnglishSize.MaterialStorageOrderMakingendDate.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingendDate ? ChineseEnglishSize.MaterialStorageOrderMakingendDate.message:'截止日期不能为空'}] 
                                                    })(
                                                        <DatePicker  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialStorageOrderMakingsupplier ? ChineseEnglishSize.MaterialStorageOrderMakingsupplier.descripts:'供应商'}>
                                                    {getFieldDecorator('vendor',{
                                                        initialValue:  undefined,
                                                        rules:[{ required : ChineseEnglishSize.MaterialStorageOrderMakingsupplier ? ChineseEnglishSize.MaterialStorageOrderMakingsupplier.required =='Y'? true:false: false, message: ChineseEnglishSize.MaterialStorageOrderMakingsupplier ? ChineseEnglishSize.MaterialStorageOrderMakingsupplier.message:'供应商不能为空'}] 
                                                    })(
                                                        <Select showSearch allowClear placeholder={ChineseEnglishSize.MaterialStorageOrderMakingvendorIDTips ? ChineseEnglishSize.MaterialStorageOrderMakingvendorIDTips.descripts:'请选择供应商'} >
                                                            {this.state.SelectData.vendor && this.state.SelectData.vendor.map(item => {
                                                                return <Option key={item.id} value={item.id} >{item.descripts}</Option>
                                                            })}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item {...formItemLayout} label={ChineseEnglishSize.MaterialStorageOrderMakingnotWarehouse ? ChineseEnglishSize.MaterialStorageOrderMakingnotWarehouse.descripts:'未入库'}>
                                                    {getFieldDecorator('notWarehouse',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                        rules:[{required: false}]
                                                    })(
                                                        <Switch checkedChildren={ChineseEnglishSize.MaterialStorageOrderMakingY ? ChineseEnglishSize.MaterialStorageOrderMakingY.descripts:'是'} 
                                                        unCheckedChildren={ChineseEnglishSize.MaterialStorageOrderMakingN ? ChineseEnglishSize.MaterialStorageOrderMakingN.descripts:'否'} />
                                                    ) }
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item {...formItemLayout} label={ChineseEnglishSize.MaterialStorageOrderMakingpartWarehouse ? ChineseEnglishSize.MaterialStorageOrderMakingpartWarehouse.descripts:'部分入库'}>
                                                    {getFieldDecorator('partWarehouse',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                        rules:[{required: false}]
                                                    })(
                                                        <Switch checkedChildren={ChineseEnglishSize.MaterialStorageOrderMakingY ? ChineseEnglishSize.MaterialStorageOrderMakingY.descripts:'是'} 
                                                        unCheckedChildren={ChineseEnglishSize.MaterialStorageOrderMakingN ? ChineseEnglishSize.MaterialStorageOrderMakingN.descripts:'否'} />
                                                    ) }
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </Col>
                                    <Col span={4}>
                                        <Row style={{marginTop: '4px'}} className="buttonLeft">
                                            <Button onClick={this.getWarehouseList}>{ChineseEnglishSize.MaterialStorageOrderMakingsearch ? ChineseEnglishSize.MaterialStorageOrderMakingsearch.descripts:'查询'}</Button>
                                            <Button style={{margin: '0 20px'}} onClick={this.saveData}>{ChineseEnglishSize.MaterialStorageOrderMakingsave ? ChineseEnglishSize.MaterialStorageOrderMakingsave.descripts:'保存'}</Button>
                                        </Row>
                                        <Row style={{marginTop: '20px'}} >
                                            <Button  onClick={this.handleReset}>{ChineseEnglishSize.MaterialStorageOrderMakingclean ? ChineseEnglishSize.MaterialStorageOrderMakingclean.descripts:'清空'}</Button>
                                        </Row>
                                    </Col>
                                </Form>
                            </Col>
                        </Card>
                    </Row>
                    <Row>
                        <Col span={12} 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.MaterialStorageOrderMakingorder ? ChineseEnglishSize.MaterialStorageOrderMakingorder.descripts:'订单'}</div>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => {this.setState({parameterCode: 'Order'},()=>{
                                    this.columnRef.onOpenModel();
                                }) }}><Icon type="setting" title={ChineseEnglishSize.MaterialStorageOrderMakingcolumnSettings ? ChineseEnglishSize.MaterialStorageOrderMakingcolumnSettings.descripts:'列权限设置'} /></span>}
                            >
                                <div className="drugList " style={{height: store.getState().tableHeight.y - 200 + 'px'}}>
                                    <Table
                                        columns={columns.length>0?columns:this.columns}
                                        dataSource={this.state.WaListData ? this.state.WaListData : []}
                                        pagination={false}
                                        bordered
                                        scroll={{x: columnsWidth? columnsWidth: 600,y: store.getState().tableHeight.y - 295}}
                                        style={{height: (store.getState().tableHeight.y - 238)}}
                                        rowKey={record => record.key}
                                        className='waListHeight'
                                        current={this.state.page ? this.state.page : 1}
                                        onRow={this.onClickRow}
                                        rowClassName={this.setRowClassName}
                                    />
                                    <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>
                        <Col span={this.state.show ? 24 : 12}>
                            <Card
                                size="small"
                                title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />{ChineseEnglishSize.MaterialStorageOrderMakingorderDetails ? ChineseEnglishSize.MaterialStorageOrderMakingorderDetails.descripts:'订单明细'}</span>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => {this.setState({parameterCode: 'purchaseOEList'},()=>{
                                    this.columnRef.onOpenModel();
                                }) }}><Icon type="setting" title={ChineseEnglishSize.MaterialStorageOrderMakingcolumnSettings ? ChineseEnglishSize.MaterialStorageOrderMakingcolumnSettings.descripts:'列权限设置'} /></span>}
                            >
                                <div style={{height: store.getState().tableHeight.y -200 + 'px'}}>
                                    <Table
                                        columns={modalColumns.length>0 ? modalColumns : this.modalColumns}
                                        dataSource={this.state.detailsListData}
                                        pagination={false}
                                        bordered
                                        style={{height: (store.getState().tableHeight.y - 300)}}
                                        scroll={{x:  this.state.detailWidthTotal ? this.state.detailWidthTotal : 900, y: store.getState().tableHeight.y - 295}}
                                        rowKey={record => record.key}
                                        className='detailsHeight'
                                    />
                                </div>
                            </Card>
                        </Col>
                    </Row>

                    {/*//显示表头修改弹窗*/}
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName={ this.state.parameterCode}
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={() => {
                            if (this.state.parameterCode == 'purchaseOEList') {
                                this.getDetailTableColumns()
                            }else if(this.state.parameterCode == 'Order'){
                                this.getTableColumns()
                            }
                        }
                        }
                    />
                </Modal>
            )
        }
    }
);
export default AccordingToWarehouse;