// 物资采购订单录入
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Switch, Input, Button, message, Popconfirm, Upload, Tooltip, Icon } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools'
import Moment from 'moment';
import DetailEntryList from './component/DetailEntryList.jsx';
import InquireEntry from './component/InquireEntry.jsx';
import './style/index.less';

const { Option } = Select;
const { TextArea } = Input;

function isObjEqual(o1,o2){
    var props1 = Object.getOwnPropertyNames(o1);
    var props2 = Object.getOwnPropertyNames(o2);
    if (props1.length != props2.length) {
        return false;
    }
    for (var i = 0,max = props1.length; i < max; i++) {
        var propName = props1[i];
        if (o1[propName] !== o2[propName]) {
            return false;
        }
    }
    return true;
}
const PurchaseOrderEntry = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {},
                SelectData: {}, // 下拉框数据
                detailInfo: [], // 明细列表数据
                rowId: '', // 入库单Id
                pageSize: 10,
                page: 1,
                User: JSON.parse(window.sessionStorage.userData),
                statusCode: '',
                statusId: '',
                inOpLocDr: '',
                ChineseEnglishSize: {}, //中英翻译

            };
            this.myRef1 = React.createRef();
            this.myRef2 = React.createRef();
            this.myRef3 = React.createRef();
            this.myRef4 = React.createRef();
            this.myRef5 = React.createRef();
            this.myRef6 = React.createRef();
            this.myRef7 = React.createRef();
            this.myRef8 = React.createRef();
            this.myRef9 = React.createRef();
        }

        componentDidMount() {
            // 初始化数据
            this.getSelectData();
            this.getInOpLocDr();
        }

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

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

        detailOnRef = (ref) => {
            this.childDetail = ref;
        };

        // 获取下拉框的数据
        getSelectData() {
            let data = {
                params: []
            };
            $http.post('urlS', this, {
                code: "02060069",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({ SelectData: res })
                    } else {
                        this.setState({ SelectData: {} })
                    }
                }
            })
        }

        // 保存
        saveHandle = () => {
            let {ChineseEnglishSize} = this.state
            if(this.childDetail.state.data.length < 1) {
                message.error(ChineseEnglishSize.materialPurchaseOEListdetailUnitTips ? ChineseEnglishSize.materialPurchaseOEListdetailUnitTips.descripts:"明细列表不能为空")
            } else {
                // if(this.childDetail.state.stockID){
                //     let newObj =  this.childDetail.checkFormData();
                //     let beforeObj = this.childDetail.initialDataObj();
                //     if (!isObjEqual(newObj,beforeObj)){
                //         message.error('有未保存的数据，请先保存');
                //         return
                //     }
                // }
                this.props.form.validateFields((errors, values) => {
                    let obj = JSON.parse(JSON.stringify(values));
                    if(errors == null){
                        let userList = this.state.userInfo ? this.state.userInfo : undefined;
                        // let stkCat = this.props.form.getFieldValue('stkCat');
                        // let locDr = this.props.form.getFieldValue('inOpLocDr');
                        // let operType = this.props.form.getFieldValue('operType');
                        let remark = this.props.form.getFieldValue('remark2');
                        let listId = this.childModal.state.rowId;
                        let data = {
                            params: [{
                                POID: listId ? listId : this.state.statusId ? this.state.statusId : '',
                                locID: obj.inOpLocDr ? obj.inOpLocDr : userList.locID,
                                vendorID: obj.vendor ? obj.vendor : '',
                                remark: remark ? remark : '',
                                detail: this.childDetail.state.data
                            }]
                        };
                        $http.post('urlS', this, {
                            code: "02060070",
                            data: data,
                            success: function (res) {

                                if (+res.errorCode === 0) {
                                    // 成功提示
                                    message.success(res.errorMessage);
                                    this.setState({statusCode: res.result.main.stateCode , statusId: res.result.main.POID });
                                    this.childModal.setState({tableData: [], total: 0});
                                    this.getEchoData(res.result.main.POID);
                                }
                            },
                            error: function (err) {
                                console.log(err)
                            }
                        })
                    }
                })

            }

        };

        // 保存成功后根据返回回来的inOperateID重新查找数据
        getEchoData(id) {
            // 重置表单
            this.props.form.resetFields(); //清空所有
            this.setState({rowId: id}); // 将行id保存起来
            let data = {
                params: [
                    {
                        POID: id
                    }
                ],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02060072",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        for (let i = 0; i < res.detail.rows.length; i++) {
                            res.detail.rows[i].key = i + "main";
                        }
                        this.setState({userInfo: res.main, detailInfo: res.detail.rows});
                        // this.props.form.setFieldsValue(res.result[0].mainInfo[0]); // 将查询出来的数据回显
                    } else {
                        this.setState({userInfo: {}, detailInfo: []});
                    }
                }
            })
        }

        // 获取到部门的值
        getInOpLocDr = () => {
            let inOpLocDr = this.props.form.getFieldValue('inOpLocDr');
            this.setState({inOpLocDr: inOpLocDr});
            return inOpLocDr
        }

        // 点击查询显示弹框
        inquireHandle = () => {
            this.getInOpLocDr();
            this.childModal.showModal();
        };

        // 重置所有内容
        resetFieldsAll() {
            this.props.form.resetFields(); //清空所有
            this.setState({userInfo: {}, detailInfo: [], rowId: "", statusCode: '', statusId: ''});
            this.childDetail.resetFields();
            this.childDetail.deleteData();
            this.childModal.handleUncheck();
            this.childModal.setState({tableData: []});
        }

        // 重置表单
        resetFields = () => {
            this.resetFieldsAll()
        };

        // 删除
        handleDelete = () => {
            let data2 = {
                params: {
                    detail: [{
                        PODetailID:this.childDetail.state.userInfo&&this.childDetail.state.userInfo.PODetailID ? this.childDetail.state.userInfo.PODetailID: undefined,
                    }]

                }
            };
            let data3 = {
                params: {
                    main: [
                        {
                            POID: this.childModal.state.rowId ? this.childModal.state.rowId : undefined,
                        }
                    ]

                }
            };
            $http.post('urlS', this, {
                code: "02060074",
                data: this.childDetail.state.userInfo&&this.childDetail.state.userInfo.PODetailID ? data2 : data3,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.resetFieldsAll();
                        this.childModal.setState({tableData : [],total: 0, userInfo: {}})
                    }
                }
            })
        };

        //完成
        accomplish = () => {
            let userPOID =  this.state.userInfo.POID ?  this.state.userInfo.POID : undefined;
            let data = {
                params: [{
                    POID: this.state.statusId ? this.state.statusId : userPOID
                }]
            };
            $http.post('urlS', this, {
                code: "02060075",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.setState({statusCode: ''});
                        this.getEchoData(res.result.main.POID);
                        this.childModal.setState({tableData : [],total: 0})
                    }
                }
            })
        };
        //取消完成
        offAccomplish = () => {
            let userPOID =  this.state.userInfo.POID ?  this.state.userInfo.POID : undefined;
            let data = {
                params: [{
                    POID: this.state.statusId ? this.state.statusId : userPOID
                }]
            };
            $http.post('urlS', this, {
                code: "02060076",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.getEchoData(res.result.main.POID);
                        this.childModal.setState({tableData : [],total: 0})
                    }
                }
            })
        }
        changesDesc=(v)=>{
            this.setState({ inOpLocDr: v})
        };
        //获取中英版
        getChineseEnglishSize=(v)=>{
            this.setState({ChineseEnglishSize: v})
        }
        render() {
            const formItemInput  = {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 },
            };
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo: {};
            let user = this.state.User.locID ? this.state.User.locID: undefined;
            let {ChineseEnglishSize} = this.state;
            let userStatusCode = this.state.userInfo.stateCode ? this.state.userInfo.stateCode : '';
            return (
                <div className="inPurPlan">
                    <Card
                        size="small"
                        title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.materialPurchaseOEListpurchaseOrderEntry ? ChineseEnglishSize.materialPurchaseOEListpurchaseOrderEntry.descripts:'采购计划制单'}</div>}
                    >
                        <Row>
                            <Col span={18} className="top-form">
                                <Form>
                                    <Row>
                                        <Col span={8} style={{paddingRight: '10px'}}>
                                            <Form.Item label={ChineseEnglishSize.materialPurchaseOEListloc ? ChineseEnglishSize.materialPurchaseOEListloc.descripts:'科室'} {...formItemInput}>
                                                {getFieldDecorator('inOpLocDr', {
                                                    initialValue: userInfo.locID ? userInfo.locID+'' : user,
                                                    rules:[{ required : ChineseEnglishSize.materialPurchaseOEListloc ? ChineseEnglishSize.materialPurchaseOEListloc.required =='Y'? true:false: false, message: ChineseEnglishSize.materialPurchaseOEListloc ? ChineseEnglishSize.materialPurchaseOEListloc.message:'科室不能为空'}]
                                                })(
                                                    <Select showSearch allowClear placeholder="请选择科室" onChange={this.changesDesc}>
                                                        {this.state.SelectData.loc && this.state.SelectData.loc.map(item => {
                                                            return <Option key={item.id} value={item.id} >{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8} style={{paddingRight: '10px'}}>
                                            <Form.Item label={ChineseEnglishSize.materialPurchaseOEListnum ? ChineseEnglishSize.materialPurchaseOEListnum.descripts:'计划单号'} {...formItemInput}>
                                                {getFieldDecorator('NO', {
                                                    initialValue: userInfo.PONO ? userInfo.PONO : undefined,
                                                })(
                                                    <Input disabled />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8} style={{paddingRight: '30px'}}>
                                            <Form.Item label={ChineseEnglishSize.materialPurchaseOEListvendor ? ChineseEnglishSize.materialPurchaseOEListvendor.descripts:'供应商'} {...formItemInput}>
                                                {getFieldDecorator('vendor', {
                                                    initialValue: userInfo.vendorID ? userInfo.vendorID : undefined,
                                                    rules:[{ required : ChineseEnglishSize.materialPurchaseOEListvendor ? ChineseEnglishSize.materialPurchaseOEListvendor.required =='Y'? true:false: false, message: ChineseEnglishSize.materialPurchaseOEListvendor ? ChineseEnglishSize.materialPurchaseOEListvendor.message:'供应商不能为空'}]
                                                })(
                                                    <Select showSearch allowClear placeholder={ChineseEnglishSize.materialPurchaseOEListvendor && ChineseEnglishSize.materialPurchaseOEListpleaseSelect ? ChineseEnglishSize.materialPurchaseOEListpleaseSelect.descripts+ChineseEnglishSize.materialPurchaseOEListvendor.descripts:'请选择供应商'} >
                                                        {this.state.SelectData.vendor && this.state.SelectData.vendor.map(item => {
                                                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={8} style={{paddingRight: '10px'}}>
                                            <Form.Item label={ChineseEnglishSize.materialPurchaseOEListentryStartDate ? ChineseEnglishSize.materialPurchaseOEListentryStartDate.descripts:'录入日期'} {...formItemInput}>
                                                {getFieldDecorator('StartDate', {
                                                    initialValue: Moment(),
                                                })(
                                                    <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" disabled />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8} style={{paddingRight: '10px'}}>
                                            <Form.Item label={ChineseEnglishSize.materialPurchaseOEListremark2 ? ChineseEnglishSize.materialPurchaseOEListremark2.descripts:'备注'} {...formItemInput}>
                                                {getFieldDecorator('remark2', {
                                                    initialValue: userInfo.remark ? userInfo.remark : undefined,
                                                })(
                                                    <TextArea rows={1} style={{width: '100%'}} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={6}>
                                <Row style={{marginBottom: '20px',marginTop: '5px'}}>
                                    <Button style={{marginRight: '30px'}} onClick={this.inquireHandle}>{ChineseEnglishSize.materialPurchaseOEListsearch ? ChineseEnglishSize.materialPurchaseOEListsearch.descripts:'查询'}</Button>
                                    <Button type="primary" style={{marginRight: '30px'}} onClick={this.saveHandle}>{ChineseEnglishSize.materialPurchaseOEListsave ? ChineseEnglishSize.materialPurchaseOEListsave.descripts:'保存'}</Button>
                                    <Button disabled={this.state.statusCode == 10 ? false : userStatusCode == 10 ? false : true} onClick={this.accomplish}>{ChineseEnglishSize.materialPurchaseOEListaccomplish ? ChineseEnglishSize.materialPurchaseOEListaccomplish.descripts:'完成'}</Button>
                                </Row>
                                <Row>
                                    <Popconfirm title={ChineseEnglishSize.materialPurchaseOEListresetTips ? ChineseEnglishSize.materialPurchaseOEListresetTips.descripts:"重置后将初始化数据，你确定要重置吗?"} onConfirm={this.resetFields} >
                                        <Button style={{marginRight: '30px'}} >{ChineseEnglishSize.materialPurchaseOEListReset ? ChineseEnglishSize.materialPurchaseOEListReset.descripts:'重置'}</Button>
                                    </Popconfirm>
                                    <Popconfirm title={ChineseEnglishSize.materialPurchaseOEListdeleteTips ? ChineseEnglishSize.materialPurchaseOEListdeleteTips.descripts:'删除不可恢复，你确定要删除吗?'} onConfirm={this.handleDelete} >
                                        <Button type="danger" style={{marginRight: '30px'}}>{ChineseEnglishSize.materialPurchaseOEListdelete ? ChineseEnglishSize.materialPurchaseOEListdelete.descripts:'删除'}</Button>
                                    </Popconfirm>
                                    <Button disabled={this.state.statusCode == 20 ? false : userStatusCode == 20 ? false : true} onClick={this.offAccomplish}>{ChineseEnglishSize.materialPurchaseOEListcancelComplete ? ChineseEnglishSize.materialPurchaseOEListcancelComplete.descripts:'取消完成'}</Button>
                                </Row>
                            </Col>
                        </Row>
                    </Card>
                    <DetailEntryList SelectData={this.state.SelectData} onRef={this.detailOnRef} detailInfo={this.state.detailInfo} handleThis={this} inOpLocDr={this.state.inOpLocDr} />
                    <InquireEntry ChineseEnglishSize={this.state.ChineseEnglishSize} SelectData={this.state.SelectData} onRef={this.onRef} inOpLocDr={this.state.inOpLocDr ? this.state.inOpLocDr : ''} handleThis={this} />
                </div>
            )
        }
    }
);
export default PurchaseOrderEntry;