// 主收费项维护界面 --- 基本信息
import React from 'react';
import { Form, Row, Col, Input, Button, Select, message, DatePicker } from 'antd';
import { $http } from 'containers/config/https';
import { Util, dayFormat } from 'tools';
import FormDataDifferenceComparison from 'pages/common/FormDataDifferenceComparison'; // 表单数据差异比对公共弹窗
import Moment from 'moment';

const { TextArea } = Input;
const { Option } = Select;
let timer = null;

class MTMBasicInformation extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userInfo: {}, // 选中的行数据
            subclassSelectData: {}, // 子类下拉框数据集
            otherSelectData: {}, // 费别,等级,单位,地区下拉框数据
            rowId: '', // 行数据
            selectSearchData: [], //搜索下拉数据
            formData: [], // 表单数据
        }
    }

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

    componentWillReceiveProps(props) {
        if (props.subclassSelectData !== this.state.subclassSelectData) {
            this.setState({ subclassSelectData: props.subclassSelectData }, () => {
                this.getFormData();
            })
        }
        if (props.otherSelectData !== this.state.otherSelectData) {
            this.setState({ otherSelectData: props.otherSelectData }, () => {
                this.getFormData();
            })
        }
        if (props.rowId !== this.state.rowId) {
            this.setState({ rowId: props.rowId })
        }
        if (props.rowData !== this.state.userInfo) {
            this.setState({
                userInfo: {
                    ...props.rowData,
                    acsubID: 'itemACsubID' in props.rowData && props.rowData.itemACsubID ? props.rowData.itemACsubID : '',
                    approvalNo: 'itemApprovalNo' in props.rowData && props.rowData.itemApprovalNo ? props.rowData.itemApprovalNo : '',
                    ecsubID: 'itemECsubID' in props.rowData && props.rowData.itemECsubID ? props.rowData.itemECsubID : '',
                    excluded: 'itemExCluded' in props.rowData && props.rowData.itemExCluded ? props.rowData.itemExCluded : '',
                    explain: 'itemExplain' in props.rowData && props.rowData.itemExplain ? props.rowData.itemExplain : '',
                    icsubID: 'itemICsubID' in props.rowData && props.rowData.itemICsubID ? props.rowData.itemICsubID : '',
                    inclusion: 'itemInClusion' in props.rowData && props.rowData.itemInClusion ? props.rowData.itemInClusion : '',
                    manfDesc: 'itemManfDesc' in props.rowData && props.rowData.itemManfDesc ? props.rowData.itemManfDesc : '',
                    mcsubID: 'itemMCsubID' in props.rowData && props.rowData.itemMCsubID ? props.rowData.itemMCsubID : '',
                    ocsubID: 'itemOCsubID' in props.rowData && props.rowData.itemOCsubID ? props.rowData.itemOCsubID : '',
                    pcsubID: 'itemPCsubID' in props.rowData && props.rowData.itemPCsubID ? props.rowData.itemPCsubID : '',
                    regionTypeID: 'itemRegionTypeID' in props.rowData && String(props.rowData.itemRegionTypeID) ? props.rowData.itemRegionTypeID : '',
                    remarks: 'itemRemarks' in props.rowData && props.rowData.itemRemarks ? props.rowData.itemRemarks : '',
                    spec: 'itemSpec' in props.rowData && props.rowData.itemSpec ? props.rowData.itemSpec : '',
                    tcsubID: 'itemTCsubID' in props.rowData && props.rowData.itemTCsubID ? props.rowData.itemTCsubID : '',
                    unitID: 'itemUnitID' in props.rowData && props.rowData.itemUnitID ? props.rowData.itemUnitID : ''
                }
            })
        }
    }

    getFormData = () => {
        let { subclassSelectData, otherSelectData } = this.state;
        let formData = [{
            dataIndex: 'itemCode',
            title: '收费项代码',
            typeCode: 'Input',
        }, {
            dataIndex: 'itemDesc',
            title: '收费项描述',
            typeCode: 'Input',
        }, {
            dataIndex: 'unitID',
            title: '单位',
            typeCode: 'Select',
            detailItem: otherSelectData && 'UNIData' in otherSelectData && otherSelectData.UNIData ? otherSelectData.UNIData : []
        }, {
            dataIndex: 'pcsubID',
            title: '物价子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'PCSUBData' in subclassSelectData && subclassSelectData.PCSUBData ? subclassSelectData.PCSUBData : []
        }, {
            dataIndex: 'mcsubID',
            title: '病案子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'MCSUBData' in subclassSelectData && subclassSelectData.MCSUBData ? subclassSelectData.MCSUBData : []
        }, {
            dataIndex: 'tcsubID',
            title: '收费子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'TCSUBData' in subclassSelectData && subclassSelectData.TCSUBData ? subclassSelectData.TCSUBData : []
        }, {
            dataIndex: 'icsubID',
            title: '住院子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'ICSUBData' in subclassSelectData && subclassSelectData.ICSUBData ? subclassSelectData.ICSUBData : []
        }, {
            dataIndex: 'ocsubID',
            title: '门诊子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'OCSUBData' in subclassSelectData && subclassSelectData.OCSUBData ? subclassSelectData.OCSUBData : []
        }, {
            dataIndex: 'ecsubID',
            title: '核算子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'ECSUBData' in subclassSelectData && subclassSelectData.ECSUBData ? subclassSelectData.ECSUBData : []
        }, {
            dataIndex: 'acsubID',
            title: '会计子类',
            typeCode: 'Select',
            detailItem: subclassSelectData && 'ACSUBData' in subclassSelectData && subclassSelectData.ACSUBData ? subclassSelectData.ACSUBData : []
        }, {
            dataIndex: 'regionTypeID',
            title: '地区',
            typeCode: 'Select',
            detailItem: otherSelectData && 'RegionTypeData' in otherSelectData && otherSelectData.RegionTypeData ? otherSelectData.RegionTypeData : []
        }, {
            dataIndex: 'manfDesc',
            title: '厂家',
            typeCode: 'Input'
        }, {
            dataIndex: 'approvalNo',
            title: '批准文号',
            typeCode: 'Input'
        }, {
            dataIndex: 'spec',
            title: '规格',
            typeCode: 'Input',
            detailItem: subclassSelectData && 'ManfData' in subclassSelectData && subclassSelectData.ManfData ? subclassSelectData.ManfData : []
        }, {
            dataIndex: 'remarks',
            title: '备注',
            typeCode: 'Input'
        }, {
            dataIndex: 'excluded',
            title: '除外内容',
            typeCode: 'Input'
        }, {
            dataIndex: 'inclusion',
            title: '项目内含',
            typeCode: 'Input'
        }, {
            dataIndex: 'explain',
            title: '收费说明',
            typeCode: 'Input'
        }]
        this.setState({ formData })
    }

    // 清空所有
    resetFieldsInfo = () => {
        this.setState({ userInfo: {}, rowId: '' }, () => {
            this.props.resetFieldsUserInfo();
        })
        this.resetFields(); //重置表单
    }

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

    /**
    * @ByShizi: 收费项医嘱项修改保存时须展示原信息
    * 需求 #521
    * Create 2022-04-19
    */
    handleDifferenceComparison = () => {
        const { form: { validateFields } } = this.props;
        const { userInfo, formData } = this.state;
        let diffData = [];
        validateFields((errors, values) => {
            values.itemEndDate = values.itemEndDate ? Moment(values.itemEndDate).format(dayFormat) : '';
            // 验证成功
            if (errors === null) {
                for (var keys in values) {
                    for (var rowKeys in userInfo) {
                        if (keys === rowKeys && values[keys] !== undefined && userInfo[rowKeys] !== undefined && values[keys] !== userInfo[rowKeys]) {
                            let formItemData = Util.returnDataCccordingToAttributes(formData, keys, 'dataIndex');
                            let detailItem = formItemData?.detailItem;
                            let typeCode = formItemData?.typeCode;
                            diffData.push({
                                dataIndex: keys,
                                title: formItemData?.title,
                                new: typeCode === 'Select' && values[keys] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, values[keys], 'ID').Descripts : values[keys],
                                old: typeCode === 'Select' && userInfo[rowKeys] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, userInfo[rowKeys], 'ID').Descripts : userInfo[rowKeys]
                            })
                        }
                    }
                }
                console.log("diffData", diffData)
                if (diffData && diffData.length > 0) {
                    this.diffChild.modifyVisible && this.diffChild.modifyVisible(true, diffData);
                } else {
                    message.error("没有修改的数据需要保存。")
                }
            }
        })
    }

    // 保存
    handleSave = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            // 验证成功
            if (errors === null) {
                values.logonGroupID = user && user.groupID ? user.groupID : '';
                values.logonHospID = user && user.hospID ? user.hospID : '';
                values.userID = user && user.userID ? user.userID : '';
                values.itemID = this.state.rowId ? this.state.rowId : '';
                let data = {
                    params: []
                }
                values.EndDate = values.itemEndDate ? Moment(values.itemEndDate).format(dayFormat) : '';
                data.params.push(values)
                $http.post('urlADS', this, {
                    code: '05100013',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            // 成功提示
                            if (values.itemID) {
                                message.success('编辑成功');
                                this.diffChild.modifyVisible && this.diffChild.modifyVisible(false);
                            } else {
                                message.success('新增成功');
                                this.setState({ rowId: res.itemID }, () => {
                                    this.props.compileActiveKey(this.state.rowId);
                                })
                            }
                            var { getTableData } = this.props;
                            getTableData && getTableData()
                        }
                    }
                })
            }
        })
    }

    // 根据输入域中的值获取厂家信息
    getSelectSearchData = (value) => {
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(() => {
            if (value) {
                let data = {
                    params: [{
                        desc: value
                    }]
                }
                $http.post('urlS', this, {
                    code: "02020352",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({ selectSearchData: res.manf })
                        }
                    }
                })
            }
        }, 300)
    };

    render() {
        let { userInfo, subclassSelectData, otherSelectData, rowId } = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput = {
            labelCol: {
                xs: { span: 12 },
                sm: { span: 12 },
                md: { span: 12 },
                lg: { span: 12 },
                xl: { span: 10 },
                xxl: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 12 },
                sm: { span: 12 },
                md: { span: 12 },
                lg: { span: 12 },
                xl: { span: 14 },
                xxl: { span: 16 },
            },
        };
        const formItemTextArea = {
            labelCol: {
                xs: { span: 6 },
                sm: { span: 6 },
                md: { span: 6 },
                lg: { span: 6 },
                xl: { span: 5 },
                xxl: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 18 },
                sm: { span: 18 },
                md: { span: 18 },
                lg: { span: 18 },
                xl: { span: 19 },
                xxl: { span: 20 },
            },
        }

        // 物价子类
        let priceSubclassOption = subclassSelectData.PCSUBData && subclassSelectData.PCSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 病案子类
        let caseSubclassOption = subclassSelectData.MCSUBData && subclassSelectData.MCSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 收费子类
        let chargeSubclassOption = subclassSelectData.TCSUBData && subclassSelectData.TCSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 住院子类
        let hospitalizedSubclassOption = subclassSelectData.ICSUBData && subclassSelectData.ICSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 门诊子类
        let outpatientServiceSubclassOption = subclassSelectData.OCSUBData && subclassSelectData.OCSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 核算子类
        let businessAccountingSubclassOption = subclassSelectData.ECSUBData && subclassSelectData.ECSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 会计子类
        let accountantSubclassOption = subclassSelectData.ACSUBData && subclassSelectData.ACSUBData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 地区子类
        let regionSubclassOption = otherSelectData.RegionTypeData && otherSelectData.RegionTypeData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })
        // 单位
        let unitSubclassOption = otherSelectData.UNIData && otherSelectData.UNIData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })

        // 厂家
        let manfDataOption = subclassSelectData.ManfData && subclassSelectData.ManfData.map((item, index) => {
            return (<Option key={index} value={item.ID} title={item.Descripts + '^' + item.descriptsSPCode}>{item.Descripts}</Option>)
        })

        return (
            <div style={{ marginTop: '12px' }}>
                {/* hideRequiredMark--隐藏所有表单项的必选标记 initialValue--初始值 */}
                <Form>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="收费项代码：" {...formItemInput}>
                                {getFieldDecorator('itemCode', {
                                    initialValue: userInfo.itemCode ? userInfo.itemCode : undefined,
                                    rules: [{ required: true, message: '请输入收费项代码' }]
                                })(
                                    <Input placeholder="请输入" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="收费项描述：" {...formItemInput}>
                                {getFieldDecorator('itemDesc', {
                                    initialValue: userInfo.itemDesc ? userInfo.itemDesc : undefined,
                                    rules: [{ required: true, message: '请输入收费项描述' }]
                                })(
                                    <Input placeholder="请输入" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="单位：" {...formItemInput}>
                                {getFieldDecorator('unitID', {
                                    initialValue: userInfo.itemUnitID ? userInfo.itemUnitID : undefined,
                                    rules: [{ required: true, message: '请选择所属医院' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {unitSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="物价子类：" {...formItemInput}>
                                {getFieldDecorator('pcsubID', {
                                    initialValue: userInfo.itemPCsubID ? userInfo.itemPCsubID : undefined,
                                    rules: [{ required: true, message: '请选择物价子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {priceSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>

                        <Col span={8}>
                            <Form.Item label="病案子类：" {...formItemInput}>
                                {getFieldDecorator('mcsubID', {
                                    initialValue: userInfo.itemMCsubID ? userInfo.itemMCsubID : undefined,
                                    rules: [{ required: true, message: '请选择病案子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {caseSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="收费子类：" {...formItemInput}>
                                {getFieldDecorator('tcsubID', {
                                    initialValue: userInfo.itemTCsubID ? userInfo.itemTCsubID : undefined,
                                    rules: [{ required: true, message: '请选择收费子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {chargeSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="住院子类：" {...formItemInput}>
                                {getFieldDecorator('icsubID', {
                                    initialValue: userInfo.itemICsubID ? userInfo.itemICsubID : undefined,
                                    rules: [{ required: true, message: '请选择住院子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {hospitalizedSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="门诊子类：" {...formItemInput}>
                                {getFieldDecorator('ocsubID', {
                                    initialValue: userInfo.itemOCsubID ? userInfo.itemOCsubID : undefined,
                                    rules: [{ required: true, message: '请选择门诊子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {outpatientServiceSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>

                        <Col span={8}>
                            <Form.Item label="核算子类：" {...formItemInput}>
                                {getFieldDecorator('ecsubID', {
                                    initialValue: userInfo.itemECsubID ? userInfo.itemECsubID : undefined,
                                    rules: [{ required: true, message: '请选择核算子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {businessAccountingSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="会计子类：" {...formItemInput}>
                                {getFieldDecorator('acsubID', {
                                    initialValue: userInfo.itemACsubID ? userInfo.itemACsubID : undefined,
                                    rules: [{ required: true, message: '请选择会计子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {accountantSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="地区：" {...formItemInput}>
                                {getFieldDecorator('regionTypeID', {
                                    initialValue: userInfo.itemRegionTypeID ? String(userInfo.itemRegionTypeID) : undefined,
                                    rules: [{ required: true, message: '请选择地区子类' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                        {regionSubclassOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="厂家：" {...formItemInput}>
                                {getFieldDecorator('manfDesc', {
                                    initialValue: userInfo.itemManfDesc ? userInfo.itemManfDesc : undefined
                                })(
                                    // <Select showSearch allowClear placeholder="请选择" optionFilterProp="title">
                                    //     {manfDataOption}
                                    // </Select>
                                    // <Select
                                    //     allowClear
                                    //     showSearch
                                    //     defaultActiveFirstOption={false}
                                    //     showArrow={false}
                                    //     filterOption={false}
                                    //     notFoundContent={null}
                                    //     placeholder="输入关键字自动检索"
                                    //     onSearch={this.getSelectSearchData}
                                    // >
                                    //     {
                                    //         this.state.selectSearchData && this.state.selectSearchData.map((item, index) => {
                                    //             return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
                                    //         })
                                    //     }
                                    // </Select>
                                    <Input placeholder="请输入" />

                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="批准文号：" {...formItemInput}>
                                {getFieldDecorator('approvalNo', {
                                    initialValue: userInfo.itemApprovalNo ? userInfo.itemApprovalNo : undefined
                                })(
                                    <Input placeholder="请输入" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="规格：" {...formItemInput}>
                                {getFieldDecorator('spec', {
                                    initialValue: userInfo.itemSpec ? userInfo.itemSpec : undefined
                                })(
                                    <Input placeholder="请输入" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="失效日期" {...formItemInput}>
                                {getFieldDecorator('itemEndDate', {
                                    initialValue: userInfo.itemEndDate ? Moment(userInfo.itemEndDate, 'YYYY-MM-DD') : undefined,
                                })(
                                    <DatePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        // disabled={userInfo.itemStDate ? true : false}
                                        disabledDate={this.itemEndDate}
                                    />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="备注：" {...formItemTextArea}>
                                {getFieldDecorator('remarks', {
                                    initialValue: userInfo.itemRemarks ? userInfo.itemRemarks : undefined,
                                })(
                                    <TextArea rows={1} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="除外内容：" {...formItemTextArea}>
                                {getFieldDecorator('excluded', {
                                    initialValue: userInfo.itemExCluded ? userInfo.itemExCluded : undefined,
                                })(
                                    <TextArea rows={1} />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="项目内含：" {...formItemTextArea}>
                                {getFieldDecorator('inclusion', {
                                    initialValue: userInfo.itemInClusion ? userInfo.itemInClusion : undefined,
                                })(
                                    <TextArea rows={1} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="收费说明：" {...formItemTextArea}>
                                {getFieldDecorator('explain', {
                                    initialValue: userInfo.itemExplain ? userInfo.itemExplain : undefined,
                                })(
                                    <TextArea rows={1} />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row style={{ marginTop: '24px', textAlign: 'center' }}>
                        <Button type="primary" style={{ marginRight: '12px' }} onClick={rowId ? this.handleDifferenceComparison : this.handleSave}>{rowId ? '编辑' : '新增'}</Button>
                        <Button onClick={this.resetFieldsInfo}>重置</Button>
                    </Row>
                </Form>

                {/*修改时差异提醒*/}
                <FormDataDifferenceComparison onRef={ref => this.diffChild = ref} onOk={this.handleSave} />
            </div>
        )
    }
};
const MTMBasicInformationForm = Form.create()(MTMBasicInformation);
export default MTMBasicInformationForm;