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

const { Option } = Select;
const { TextArea } = Input;
const SelectRequisition = Form.create()(
    class extends React.Component {
        constructor(){
            super();
            this.state = {
                visible: false,
                data: [],//主列表数据
                getBatchDetail: [],//详情列表数据
                total: 0,
                total2: 0,
                page: 1,
                page2: 1,
                pageSize: 10,
                pageSize2:10,
                locId: JSON.parse(window.sessionStorage.userData).locID,
                toLocID: '',
                rowKey: '',
                rowId: '',//双击行id
                defaultTime: {},
                language: JSON.parse(window.sessionStorage.userData),
                ChineseEnglishSize: {},
            };
            this.columns = [
                {
                    key: 1,
                    title: '请求单号',
                    dataIndex: 'stkReqNO',
                    align: "center",
                    width: '200px'
                },
                {
                    key: 2,
                    title: '请求科室',
                    dataIndex: 'toLocDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 3,
                    title: '供给科室',
                    dataIndex: 'frLocDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 5,
                    title: '请求日期',
                    dataIndex: 'createDate',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 6,
                    title: '单据类型',
                    dataIndex: 'stateDesc',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 7,
                    title: '制单人',
                    dataIndex: 'createUserName',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 8,
                    title: '转移状态',
                    dataIndex: 'tranStatus',
                    align: "center",
                    width: '100px',
                },
            ];
            this.columnsDetail = [
                {
                    key: 2,
                    title: '药品代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 3,
                    title: '药品名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 5,
                    title: '供应方库存',
                    dataIndex: 'frQtyUom',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 6,
                    title: '请求数量',
                    dataIndex: 'qty',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 7,
                    title: '已转移数量',
                    dataIndex: 'transQtyUom',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 8,
                    title: '未转移数量',
                    dataIndex: 'leftQtyUom',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 9,
                    title: '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 10,
                    title: '售价',
                    dataIndex: 'sp',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 11,
                    title: '生产厂家',
                    dataIndex: 'avaQty1',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 12,
                    title: '规格',
                    dataIndex: 'avaQty2',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 13,
                    title: '通用名',
                    dataIndex: 'avaQty3',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 14,
                    title: '剂型',
                    dataIndex: 'avaQty4',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 15,
                    title: '备注',
                    dataIndex: 'remark',
                    align: "center",
                    width: '200px',
                },
            ];
            this.myRef14 = React.createRef();
        }

        componentDidMount() {
            this.props.onRef(this);
        }

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

        // 获取列表数据
        getTableData=(startDate, endDate, state) => {
            let {ChineseEnglishSize} =this.state;
            this.props.form.validateFields((errors, values) => {
                let obj = JSON.parse(JSON.stringify(values));
                if(errors == null){
                    let {page, pageSize} = this.state;
                    let data = {
                        params: [
                            {
                                begin: obj.StartDate ? Moment(obj.StartDate).format('YYYY-MM-DD') : this.state.defaultTime.params ? Moment(this.state.defaultTime.params.startDate).format('YYYY-MM-DD') : '',
                                end: obj.EndDate ? Moment(obj.EndDate).format('YYYY-MM-DD') : this.state.defaultTime.params ? Moment(this.state.defaultTime.params.endDate).format('YYYY-MM-DD') : '',
                                stateID: '20',
                                toLocID: obj.ReLoc ? obj.ReLoc : undefined,
                                frLocID: obj.geLoc ? obj.geLoc : undefined,
                                transStatus: obj.approve2 ? 1 : obj.approve ? 2 : 0
                            }
                        ],
                        pagination: [
                            {
                                pageSize: pageSize,
                                currentPage: page,
                                sort: "",
                                dir: "",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02060080",
                        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({data: res.rows, total: res.total});
                                }else {
                                    this.setState({data: [], total: 0});
                                    message.error(ChineseEnglishSize.MaterialInventoryRequestFormdelete ? ChineseEnglishSize.MaterialInventoryRequestFormdelete.descripts:'没数据');
                                }
                            }
                        }
                    })
                }
            });

        }


        // 打开弹框
        showModal = (time,chi) => {
            this.setState({
                visible: true,
                defaultTime: time,
                ChineseEnglishSize:chi
            }, () => {
                this.getTableData();
            });
        };
        // 关闭
        handleCancel = (e) => {
            this.setState({
                visible: false,
                getBatchDetail: [],
                total2: 0,
                rowKey: '',
                rowId: '',
                data: [],//主列表数据
                total: 0,
                page: 1,
                page2: 1,
                pageSize: 10,
                pageSize2:10,
                locId: '',
                toLocID: '',
            });
        };

        // 重置表单
        resetFields = () => {
            this.props.form.resetFields(); //清空所有
            this.setState({
                getBatchDetail: [],
                total2: 0,
                rowKey: '',
                rowId: '',
                data: [],//主列表数据
                total: 0,
            });
        };

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

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

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

        // 条数改变的回调
        onShowSizeChange2 = (current, size) => {
            this.setState({page: 1, pageSize2: size}, () => {
                let {startDate, endDate, status} = this.state;
                this.onChange2(current, size)
            })
        };
        BatchDetail=(id )=>{

            let data = {
                params: [
                    {
                        stkReqID: id
                    }
                ],
                pagination: [
                    {
                        pageSize: this.state.pageSize2,
                        currentPage: this.state.page2,
                        sort: "",
                        dir: "",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02060082",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        for(var i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                        }
                        this.setState({getBatchDetail: res.rows, total2: res.total});
                    }else {
                        this.setState({getBatchDetail: [], total2: 0});
                    }
                }
            })

        };

        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.key, rowId: record.stkReqID});
                        this.BatchDetail(record.stkReqID);
                    } else {
                        if (this.state.rowKey !== record.key) {
                            this.setState({rowKey: record.key,rowId: record.stkReqID});
                            this.BatchDetail(record.stkReqID);
                        } else {
                            this.setState({rowKey: '', rowId: '', getBatchDetail: [], total2: 0});
                        }
                    }
                },
                onDoubleClick: () => {
                    // 保存行数据以及ID
                    this.setState({rowId: record.stkReqID}, () => {
                        this.handleOk();
                    })
                }
            }
        };

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

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

        onSwitchState=()=>{
            if(this.props.form.getFieldValue('approve2')){
                this.props.form.setFieldsValue({approve2: false})
            }
        };
        onSwitchAllState=()=>{
            if(this.props.form.getFieldValue('approve')){
                this.props.form.setFieldsValue({approve: false})
            }
        };

        render() {
            let {ChineseEnglishSize,language} = this.state;
            const formItemInput  = {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 },
            };
            const formItemLayout = {    // label 和input宽度
                labelCol: { span:10 },
                wrapperCol: { span: 14 },
            };
            const { getFieldDecorator } = this.props.form;
            return (
                <Modal
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText={ChineseEnglishSize.MaterialInventoryTransferFormdetermine ? ChineseEnglishSize.MaterialInventoryTransferFormdetermine.descripts:'确定'}
                    cancelText={ChineseEnglishSize.MaterialInventoryTransferFormcancel ? ChineseEnglishSize.MaterialInventoryTransferFormcancel.descripts:'取消'}
                    width='75%'
                    className="selectRequisition"
                >
                    <div>
                        <Row>
                            <Card
                                size='small'
                                title={ChineseEnglishSize.MaterialInventoryTransferFormselectRequestForm ? ChineseEnglishSize.MaterialInventoryTransferFormselectRequestForm.descripts:'选取请求单'}
                                className="condition"
                            >
                                <Form >
                                    <Row>
                                        <Col span={18} className="top-form">
                                                <Row>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.MaterialInventoryTransferFormtoLoc ? ChineseEnglishSize.MaterialInventoryTransferFormtoLoc.descripts:'请求科室：'} {...formItemInput}>
                                                            {getFieldDecorator('ReLoc', {
                                                                initialValue: undefined,
                                                                rules:[{ required : false, message: ChineseEnglishSize.MaterialInventoryTransferFormtoLoc ? ChineseEnglishSize.MaterialInventoryTransferFormtoLoc.message:'请求科室不能为空'}]
                                                            })(
                                                                <Select showSearch allowClear placeholder={ChineseEnglishSize.MaterialInventoryTransferFormtoLocTips ? ChineseEnglishSize.MaterialInventoryTransferFormtoLocTips.descripts:'请选择请求科室'} >
                                                                    {this.props.SelectData.loc && this.props.SelectData.loc.map((item, i) => {
                                                                        return <Option key={i} value={item.id}>{item.descripts}</Option>
                                                                    })}
                                                                </Select>
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.MaterialInventoryTransferFormstartDate ? ChineseEnglishSize.MaterialInventoryTransferFormstartDate.descripts:'起始日期：'} {...formItemInput}>
                                                            {getFieldDecorator('StartDate', {
                                                                initialValue: this.props.SelectData.params ? Moment(this.props.SelectData.params.startDate) : undefined,
                                                            })(
                                                                <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" />
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryTransferFormshowThetransferIsCompleteMedic ? ChineseEnglishSize.MaterialInventoryTransferFormshowThetransferIsCompleteMedic.descripts:'显示转移完成药品'}>
                                                            {getFieldDecorator('approve',{
                                                                valuePropName: 'checked',
                                                                initialValue: false,
                                                                rules:[{required: false}]
                                                            })(
                                                                language.language == 'EN' ?  <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                                            ) }
                                                        </Form.Item>
                                                    </Col>
                                                </Row>
                                                <Row>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.MaterialInventoryTransferFormfrLoc ? ChineseEnglishSize.MaterialInventoryTransferFormfrLoc.descripts:'供给科室：'} {...formItemInput}>
                                                            {getFieldDecorator('geLoc', {
                                                                initialValue: undefined,
                                                                rules:[{ required :  false, message: ChineseEnglishSize.MaterialInventoryTransferFormfrLoc ? ChineseEnglishSize.MaterialInventoryTransferFormfrLoc.message:'供给科室不能为空'}]
                                                            })(
                                                                <Select showSearch allowClear placeholder={ChineseEnglishSize.MaterialInventoryTransferFormfrLocTips ? ChineseEnglishSize.MaterialInventoryTransferFormfrLocTips.descripts:'请选择供给科室'} >
                                                                    {this.props.SelectData.loc && this.props.SelectData.loc.map((item, i) => {
                                                                        return <Option key={i} value={item.id}>{item.descripts}</Option>
                                                                    })}
                                                                </Select>
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.MaterialInventoryTransferFormendDate ? ChineseEnglishSize.MaterialInventoryTransferFormendDate.descripts:'截止日期：'} {...formItemInput}>
                                                            {getFieldDecorator('EndDate', {
                                                                initialValue:  this.props.SelectData.params ? Moment(this.props.SelectData.params.endDate) : undefined,
                                                            })(
                                                                <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" />
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryTransferFormincludePartialTransfer ? ChineseEnglishSize.MaterialInventoryTransferFormincludePartialTransfer.descripts:'包含部分转移'}>
                                                            {getFieldDecorator('approve2',{
                                                                valuePropName: 'checked',
                                                                initialValue: false,
                                                                rules:[{required: false}]
                                                            })(
                                                                language.language == 'EN' ?  <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                                            ) }
                                                        </Form.Item>
                                                    </Col>
                                                </Row>
                                        </Col>
                                        <Col span={5} style={{marginLeft: '33px'}}>
                                            <Row style={{marginBottom: '20px',marginTop: '5px'}}>
                                                <Button  type="primary" style={{marginRight: '30px'}} onClick={()=> {this.props.handleThis.show();this.getTableData()}} ref={this.myRef14}>{ChineseEnglishSize.MaterialInventoryTransferFormsearch ? ChineseEnglishSize.MaterialInventoryTransferFormsearch.descripts:'查询'}</Button>
                                                <Button style={{marginRight: '30px'}} onClick={this.resetFields}>{ChineseEnglishSize.MaterialInventoryTransferFormclean ? ChineseEnglishSize.MaterialInventoryTransferFormclean.descripts:'清屏'}</Button>
                                            </Row>
                                        </Col>
                                    </Row>
                                </Form>
                            </Card>
                        </Row>
                        <Row>
                            <Col  span={10}>
                                <Card
                                    size='small'
                                    title={ChineseEnglishSize.MaterialInventoryTransferFormrequestForm ? ChineseEnglishSize.MaterialInventoryTransferFormrequestForm.descripts:'请求单'}
                                >
                                    <div style={{height: store.getState().tableHeight.y - 86 + 'px'}}>
                                        <Table
                                            columns={this.columns}
                                            dataSource={this.state.data}
                                            pagination={false}
                                            bordered
                                            scroll={{ x: 1000, y: store.getState().tableHeight.y - 120 }}
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                                        <Pagination
                                            showTotal={() => this.showTotal(this.state.total)}
                                            size="small"
                                            showQuickJumper
                                            showSizeChanger
                                            defaultCurrent={1}
                                            current={this.state.page}
                                            total={this.state.total}
                                            onChange={this.onChange}
                                            onShowSizeChange={this.onShowSizeChange}
                                            style={{textAlign: "right", marginTop: '13px'}}
                                        />
                                    </div>
                                </Card>
                            </Col>
                            <Col  span={14}>
                                <Card
                                    size='small'
                                    title={ChineseEnglishSize.MaterialInventoryTransferFormrequestFormDetails ? ChineseEnglishSize.MaterialInventoryTransferFormrequestFormDetails.descripts:'请求单明细'}
                                >
                                    <div style={{height: store.getState().tableHeight.y - 86 + 'px'}}>
                                        <Table
                                            columns={this.columnsDetail}
                                            dataSource={this.state.getBatchDetail}
                                            pagination={false}
                                            bordered
                                            scroll={{ x: 2050, y: store.getState().tableHeight.y - 120 }}
                                        />
                                        <Pagination
                                            showTotal={() => this.showTotal(this.state.total2)}
                                            size="small"
                                            showQuickJumper
                                            showSizeChanger
                                            defaultCurrent={1}
                                            current={this.state.page2}
                                            total={this.state.total2}
                                            style={{textAlign: "right", marginTop: '13px'}}
                                            onChange={this.onChange2}
                                            onShowSizeChange={this.onShowSizeChange2}
                                        />
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </div>

                </Modal>

            )
        }


    }
);
export default SelectRequisition