/**
 * 添加过敏记录
 * 2019-06-28
 * JYW
 */
import React from 'react'
import {
    Form, Row, Col, Input, Select, Drawer, Button, message, Switch, DatePicker
} from 'antd';
import moment from 'moment';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import '../style/index.less';

// 组件const
const { Option } = Select;
const { TextArea } = Input;
let timeout;
var user;
var recordData;
class AddAllergyRecords extends React.Component {

    constructor(props) {
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        var patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
        recordData = JSON.parse(sessionStorage.getItem('patientData'));
        if (!recordData) {
            recordData = JSON.parse(sessionStorage.getItem('recordData'));
        }
        super(props);
        this.state = {
            medData: [],
            allergyType: [],
            allergens: [],
            ENObj: {},
            CNObj: {},
        }
    }
    componentDidMount() {
        this.getDetailTableColumns()
        message.config({ top: 400, duration: 3 });
        this.loadBaseData();
    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }
    loadBaseData = () => {
        var params = {
            params: [{
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050039",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        allergyType: res.result.allergyType, //过敏源类型
                        allergens: res.result.allergens,//过敏源
                    })
                }
            }
        });
    }

    // 获取明系列表头数据
    getDetailTableColumns = () => {
        var that = this
        let data = {
            params: [{
                reactCode: ['AllergyRecords'],
                compontName: 'AllergyRecords',
                type: 'C',
            }]
        }
        $http.post('urlS', that, {
            code: '01040073',
            data: data,
            success: function (res) {
                console.log(res)
                if (+res.errorCode == 0) {
                    that.setState({
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN
                    })
                }
            }
        })
    };
    //医嘱项目查询
    handleSearch = (value) => {
        if (value.length >= 2) {
            this.GetMedItem(value, data => this.setState({ medData: data }))
        }
    }
    GetMedItem = (value, callback) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        function getMedItemData() {
            if (value.length < 2) {
                callback([]);
                return
            }
            let data = {
                params: [{
                    hospID: user.hospID,
                    findCode: value,
                    detailFlag: ""
                }]
            }
            $http.post(' ', this, {
                code: "01010002",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        callback(res.result.Data)

                    }
                }
            })
        }
        timeout = setTimeout(getMedItemData, 1000);
    }
    //保存过敏记录信息
    onSubmit = (e) => {
        e.preventDefault();
        if (Util.isEmpty(recordData.patID)) {
            message.warn(user.language == "EN" ? this.state.ENObj.AllergyRecordsNotPatinet.descripts : this.state.CNObj.AllergyRecordsNotPatinet.descripts);
            return;
        }
        this.props.form.validateFields((err, values) => {
            if (!err) {  //!err

                let data = {
                    "params": [{
                        userID: user.userID,                       //用户ID
                        hospID: user.hospID,                       //医院ID
                        patID: recordData.patID,                  //医院ID
                        onsetDate: moment(values.onsetDate).format(dayFormat) || '',         //过敏日期                   
                        allergyTypeID: values.typeID || '',               //过敏分类
                        allergensID: values.allergensID || '',     //过敏源
                        medItemID: values.medID || '',                 //过敏项目      
                        note: values.notes || '',                 //备注
                        checkConflict: values.checkConflict ? "Y" : 'N', //过敏冲突检测
                        status: "Y",
                        id: this.props.allergy ? this.props.allergy.id : '',        //过敏记录ID
                    }]
                };
                $http.post('urlADS', this, {
                    code: "03050041",
                    data: data,
                    success: function (res) {
                        let errorCode = res.errorCode;
                        if (errorCode === '0') {
                            message.success(user.language == "EN" ? this.state.ENObj.AllergyRecordsSaveSuccess.descripts : this.state.CNObj.AllergyRecordsSaveSuccess.descripts);
                            this.cleanData();
                            this.props.hanlderThis.setState({
                                reload: true,
                            })
                            this.setState({ medData: [] })
                        }
                    }
                });
            }

        });

    }
    //清除数据
    cleanData = () => {
        this.props.form.resetFields();
        this.props.hanlderThis.setState({
            editAllergy: {},
        })
    }
    //过敏分类选择触发
    onTypeChange = (value) => {
        var that = this
        this.props.form.setFieldsValue({
            allergensID: "",
        }, () => {
            var typeID = that.props.form.getFieldValue("typeID")
            if (that.state.allergyType[typeID - 1] != null) {
                if (that.state.allergyType[typeID - 1].code == "Drug") {

                    that.props.form.setFieldsValue({
                        checkConflict: true,
                    })
                } else {
                    that.props.form.setFieldsValue({
                        checkConflict: false,
                    })
                }
            }
        });

    }
    //根据选中的过敏源查询医嘱项
    onAllergensChange(e) {
        this.props.form.setFieldsValue({
            medID: "",
        });
        //获取选中的过敏分类的ID
        var typeID = this.props.form.getFieldValue("typeID")
        //根据获取分类的ID 判断是否是 药物：“Durg”
        if (this.state.allergyType[typeID - 1].code == "Drug") {
            let data = {
                "params": [{
                    AllergenID: e
                }]
            };
            $http.post('urlADS', this, {
                code: "03050092",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            medData: res.result,
                        })
                    }
                }
            });
        }
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        let allergyObj = this.props.allergy || {};
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 7 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        let medItem = [];
        let medFlag = true;
        this.state.medData.map((item) => {
            if ((item.id + "") === allergyObj.medID) {
                medFlag = false;
            }
            medItem.push(
                <Option key={item.id}>{item.descripts}
                </Option>
            )
        })
        if (!Util.isEmpty(allergyObj.medID)) {
            if (medFlag) {
                medItem.push(
                    <Option key={allergyObj.medID}>{allergyObj.medDesc}
                    </Option>
                )
            }
        }
        let allergyType = [], allergens = [];
        const typeID = this.props.form.getFieldValue("typeID");
        this.state.allergyType.map((item) => {
            allergyType.push(<Option key={item.id}>{item.descripts}</Option>)
        })
        this.state.allergens.map((type) => {
            if ((typeID !== "") && ((typeID + "") === (type.id + ""))) {
                type.allergens.map((item) => {
                    allergens.push(<Option key={item.id}>{item.descripts}</Option>)
                })
            }
            if ((typeID === "") && ((type.id + "") === (allergyObj.allergyTypeID + ""))) {
                type.allergens.map((item) => {
                    allergens.push(<Option key={item.id}>{item.descripts}</Option>)
                })

            }
        })

        var language = user.language
        var languageObj = {}
        if (language == "EN") {
            languageObj = this.state.ENObj
        } else {
            languageObj = this.state.CNObj
        }
        return (
            <div className='doctor-allergy' style={{ paddingLeft: '14px', height: store.getState().tableHeight.y - 94 + "px" }}>
                <Form {...formItemLayout} layout="horizontal" onSubmit={this.handleSubmit} >
                    {/* 第一行 */}

                    <Form.Item label={languageObj.AllergyRecordsAllergyDate != null ? languageObj.AllergyRecordsAllergyDate.descripts : ""}>
                        {getFieldDecorator('onsetDate', {
                            initialValue: allergyObj.onsetDate ? moment(allergyObj.onsetDate, 'YYYY-MM-DD') : moment(new Date(), 'YYYY-MM-DD'),
                            rules: [{ required: true, message: languageObj.AllergyRecordsSelectAlectAllergy != null ? languageObj.AllergyRecordsSelectAlectAllergy.descripts : "" }]

                        })(
                            <DatePicker disabledDate={(curDate) => {
                                return curDate && curDate > moment().endOf('day');
                            }} />
                        )}
                    </Form.Item>

                    {/* 第二行 */}

                    <Form.Item label={languageObj.AllergyRecordsAllergyType != null ? languageObj.AllergyRecordsAllergyType.descripts : ""}>
                        {getFieldDecorator('typeID', {
                            initialValue: allergyObj.allergyTypeID || "",
                            rules: [{ required: true, message: languageObj.AllergyRecordsSelectAllergyType != null ? languageObj.AllergyRecordsSelectAllergyType.descripts : "" }]
                        })(
                            <Select allowClear={true} placeholder={languageObj.AllergyRecordsSelectAllergyType != null ? languageObj.AllergyRecordsSelectAllergyType.descripts : ""}
                                onChange={this.onTypeChange}
                            >
                                {allergyType}
                            </Select>
                        )}
                    </Form.Item>

                    {/* 第三行 */}

                    <Form.Item label={languageObj.AllergyRecordsAllergy != null ? languageObj.AllergyRecordsAllergy.descripts : ""}>
                        {getFieldDecorator('allergensID', {
                            initialValue: allergyObj.allergensID || "",
                            rules: [{ required: true, message: languageObj.AllergyRecordsSelectAllergy != null ? languageObj.AllergyRecordsSelectAllergy.descripts : "" }]
                        })(
                            <Select
                                allowClear={true}
                                showSearch={true}
                                placeholder={languageObj.AllergyRecordsAllergy != null ? languageObj.AllergyRecordsAllergy.descripts : ""}
                                onChange={this.onAllergensChange.bind(this)}
                            >
                                {allergens}
                            </Select>
                        )}
                    </Form.Item>

                    {/* 第四行 */}

                    <Form.Item label={languageObj.AllergyRecordsAllergyProject != null ? languageObj.AllergyRecordsAllergyProject.descripts : ""}>
                        {getFieldDecorator('medID', {
                            initialValue: allergyObj.medID || "",
                        })(
                            <Select
                                allowClear={true}
                                showSearch={true}
                                autoClearSearchValue={false}
                                defaultActiveFirstOption={false}
                                showArrow={false}
                                filterOption={false}
                                onSearch={this.handleSearch}
                                placeholder={languageObj.AllergyRecordsAllergyProject != null ? languageObj.AllergyRecordsAllergyProject.descripts : ""}
                            >
                                {medItem}
                            </Select>
                        )}
                    </Form.Item>
                    {/* 第五行 */}
                    <Form.Item label={languageObj.AllergyRecordsNote != null ? languageObj.AllergyRecordsNote.descripts : ""}>
                        {getFieldDecorator('notes', {
                            initialValue: allergyObj.note || "",
                        })(
                            <TextArea
                                maxLength={50}
                                placeholder={languageObj.AllergyRecordsNotes != null ? languageObj.AllergyRecordsNotes.descripts : ""}
                                autosize={{ minRows: 4, maxRows: 6 }}
                                style={{
                                    height: '150',
                                }} />
                        )}
                    </Form.Item>

                    {/* 第六行 */}

                    <Form.Item label={languageObj.AllergyRecordsAllergyConflictCheck != null ? languageObj.AllergyRecordsAllergyConflictCheck.descripts : ""}>
                        {getFieldDecorator('checkConflict', {
                            initialValue: allergyObj.checkConflict == "Y" ? true : false,
                            valuePropName: 'checked',
                        })(
                            <Switch checkedChildren={languageObj.AllergyRecordsYES != null ? languageObj.AllergyRecordsYES.descripts : ""} unCheckedChildren={languageObj.AllergyRecordsNO != null ? languageObj.AllergyRecordsNO.descripts : ""} className='input' />
                        )}
                    </Form.Item>

                    <Row style={{ width: '100%', textAlign: 'center', marginTop: "30px" }}>
                        <Button onClick={this.cleanData} >{this.props.allergy.id ? languageObj.AllergyRecordsCancel != null ? languageObj.AllergyRecordsCancel.descripts : "" : languageObj.AllergyRecordsClean != null ? languageObj.AllergyRecordsClean.descripts : ""}</Button>
                        <Button onClick={this.onSubmit} type='primary' style={{ marginLeft: '20px', background: '#1890FF' }}  >{languageObj.AllergyRecordsSave != null ? languageObj.AllergyRecordsSave.descripts : ""}</Button>
                    </Row>
                </Form>
            </div>
        )
    }
}
const AddAllergyRecordsFrom = Form.create()(AddAllergyRecords);

export default AddAllergyRecordsFrom;