import React, { Component } from 'react';
import { $http } from '../../containers/config/https';
import { Drawer, Form, Select, Row, Col, Switch, Input, InputNumber , Button , message } from 'antd';

let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
const { Option } = Select;
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};
let timeout;


class ConcernModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            conditionItem: [],
            transUserType: '',
            transSituation: '',
            transStatusDesc: '',
            transSeqNo: '',
            transEmergencyFlag: '',
            locList: [],
            ordCatList: [],
            ordSubCatList: [],
            medList: [],
            conditionFilter: true,
            transID: ""
        }
    }

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

    showDrawer = () => {
        let data = {
            params: [{
                hospID: this.props.hospID,
            }]
        }
        $http.post('urlS', this, {
            code: '04050009',
            data: data,
            success: (res) => {
                if (res.errorCode === "0") {
                    this.setState({
                        locList: res.result.locList,
                        ordCatList: res.result.ordCatList,
                        ordSubCatList: res.result.ordSubCatList,
                        visible: true,
                    })
                }
            }
        })
    }

    GetMedItem = (value, callback) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        function getMedItemData() {
            if (value.length < 2) {
                callback([]);
                return
            }
            let data = {
                params: [{
                    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);
    }


    // 条件类型为医嘱是查询数据
    handleSerach = (e) => {
        if (e.keyCode == '32') {
            let value = e.target.value;
            value = value.replace(/\s*/g, "");
            var reg = /\s/g;
            if (reg.test(value)) {
                message.error('不能输入空字符')
                return
            }
            this.GetMedItem(value, data => this.setState({ medList: data }))
        }
    }
    //医嘱项下拉框获得焦点时回调
    onFocusCondition = () => {
        this.setState({
            medList: [],
            conditionFilter: false
        });
    }

    // 关闭抽屉
    onClose = () => {
        this.setState({
            visible: false,
            medList: [],
        }, () => {
            // 如果为编辑，则关闭后清除表单
            this.props.handelThis.resetRuleInfo();
            this.resetFields()

        });
    };

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

        // 保存配置信息
        handleSubmit = (type, e) => {
            e.preventDefault();
            this.props.form.validateFields((err, values) => {
                if (!err) {  //!err
                    let transID = "";
                    if (this.props.concernInfo){
                        transID = this.props.concernInfo.transID;
                    }
                    let data = {
                        "params": [{
                            userID: user.userID,
                            saveType: type,
                            transID: transID,    //用户ID
                            hospID: type === 'C' ? '' : this.props.hospID,    //医院ID              
                            transType: values.transType ? "D" : "T",     //需关注类型
                            transUserType: values.transUserType ? "N" : "D",    //人员类型
                            transSituation: values.transSituation || '',  // 需处理情况描述       
                            transSituationCode: values.transSituationCode || '', // 需处理情况Code
                            transStatusDesc: values.transStatusDesc ? "Y" : "N",    // 启用                   
                            transSeqNo: values.transSeqNo || "",      //顺序                      
                            transEmergencyFlag: values.transEmergencyFlag ? "Y" : "N", //急诊留观 
                            transShieldLoc: values.transShieldLoc ? values.transShieldLoc.join(",") : "",    //科室
                            transShieldCat: values.transShieldCat ? values.transShieldCat.join(",") : "",   // 医嘱大类
                            transShieldOrdCat: values.transShieldOrdCat ? values.transShieldOrdCat.join(",") : "",     //医嘱子类
                            transShieldMed: values.transShieldMed ? values.transShieldMed.join(",") : "",  //医嘱项
                            transControlFlag: values.transControlFlag ? "Y" : "N", //是否控制
                            linkMethod: values.linkMethod,
                            parameter: values.parameter,
                            jumpPage: values.jumpPage,
                        }]
                    };
                    $http.post('urlADS', this, {
                        code: "04050010",
                        data: data,
                        success: function (res) {
                            let errorCode = res.errorCode;
                            if (errorCode === "0") {
                                this.onClose();
                                message.success("保存成功!");
                                this.props.handelThis.handleQuery(this.props.hospID);
                            }
                        }
                    });
                }
    
            });
        }

    render() {
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
        let concernInfo = this.props.concernInfo ? this.props.concernInfo : {};

        let locItem = [], ordCatItem = [], ordSubCatItem = [], transShieldMedItem = [];
        this.state.locList.map((item) => {
            locItem.push(
                <Option key={item.id}>{item.descripts}</Option>
            )
        })
        this.state.ordCatList.map((item) => {
            ordCatItem.push(
                <Option key={item.id}>{item.descripts}</Option>
            )
        })
        this.state.ordSubCatList.map((item) => {
            ordSubCatItem.push(
                <Option key={item.id}>{item.descripts}</Option>
            )
        })
        this.state.medList.map((item) => {
            transShieldMedItem.push(
                <Option key={item.id}>{item.descripts}</Option>
            )
        })

        let transTypeValue = concernInfo.transType === "出院" ? true : false;
        let userTypeValue = concernInfo.transUserType === "护士" ? true : false;
        let statusValue = concernInfo.transStatusDesc === "启用" ? true : false;
        let emergencyValue = concernInfo.transEmergencyFlag === "显示" ? true : false;
        let transControl = concernInfo.transControlFlag === "控制" ? true : false;
        let situationValue = concernInfo.transSituation;
        let situationCodeValue = concernInfo.transSituationCode;
        let seqNoValue = concernInfo.transSeqNo;
        // let transShieldMed = concernInfo.transShieldMed;
        // if ((transShieldMed)&&(this.state.medList.length===0)) {
        //     transShieldMed.map((item) => {
        //         transShieldMedItem.push(
        //             <Option key={item.id}>{item.descripts}</Option>
        //         )
        //     })
        // }

        return (

            <Drawer
                title={this.props.title + "需关注配置"}
                width={720}
                onClose={this.onClose}
                visible={this.state.visible}
            >
                <Form layout="vertical" onSubmit={this.handleSubmit}>
                    <Row gutter={16}>
                        <Col span={6} >
                            <Form.Item label="需关注类型" >
                                {getFieldDecorator('transType', {
                                    valuePropName: 'checked',
                                    initialValue: transTypeValue,
                                    rules: [{ required: true, message: '请选择需关注类型!' }],
                                })(
                                    <Switch checkedChildren="出院" unCheckedChildren="转科"  />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6} >
                            <Form.Item label="人员类型" >
                                {getFieldDecorator('transUserType', {
                                    valuePropName: 'checked',
                                    initialValue: userTypeValue,
                                    rules: [{ required: true, message: '请选择需人员类型!' }],
                                })(
                                    <Switch checkedChildren="护士" unCheckedChildren="医生" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6} >
                            <Form.Item label="是否启用" >
                                {getFieldDecorator('transStatusDesc', {
                                    valuePropName: 'checked',
                                    initialValue: statusValue,
                                    rules: [{ required: true, message: '请选择需关注类型!' }],
                                })(
                                    <Switch checkedChildren="启用" unCheckedChildren="不启用" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6} >
                            <Form.Item label="提示顺序" >
                                {getFieldDecorator('transSeqNo', {
                                    initialValue: seqNoValue,
                                    rules: [{ required: true, message: '请选择提示顺序!' }],
                                })(
                                    <InputNumber min={1} />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={6} >
                            <Form.Item label="急诊留观是否显示" >
                                {getFieldDecorator('transEmergencyFlag', {
                                    valuePropName: 'checked',
                                    initialValue: emergencyValue,
                                    rules: [{ required: true }],
                                })(
                                    <Switch checkedChildren="显示" unCheckedChildren="不显示" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6} >
                            <Form.Item label="是否控制" >
                                {getFieldDecorator('transControlFlag', {
                                    valuePropName: 'checked',
                                    initialValue: transControl,
                                    rules: [{ required: true }],
                                })(
                                    <Switch checkedChildren="控制" unCheckedChildren="不控制" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6} >
                            <Form.Item label="需处理情况描述" >
                                {getFieldDecorator('transSituation', {
                                    initialValue: situationValue,
                                    rules: [{ required: true, message: '请输入需处理情况描述!' }],
                                })(
                                    <Input placeholder="请输入需处理情况描述" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6} >
                            <Form.Item label="需处理情况描述代码" >
                                {getFieldDecorator('transSituationCode', {
                                    initialValue: situationCodeValue,
                                    rules: [{ required: true, message: '请输入需处理情况描述代码!' }],
                                })(
                                    <Input placeholder="请输入需处理情况描述代码" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                       
                    </Row>
                    <Row gutter={16}>
                        <Col span={11}>
                            <Form.Item label="屏蔽科室">
                                {getFieldDecorator('transShieldLoc', {
                                    initialValue: concernInfo.transShieldLocID,

                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        placeholder="请选择屏蔽科室">
                                        {locItem}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={11}>
                            <Form.Item label="屏蔽医嘱大类项目">
                                {getFieldDecorator('transShieldCat', {
                                    initialValue: concernInfo.transShieldCatID,

                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        placeholder="请选择屏蔽医嘱大类项目">
                                        {ordCatItem}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={11}>
                            <Form.Item label="屏蔽医嘱子类项目">
                                {getFieldDecorator('transShieldOrdCat', {
                                    initialValue: concernInfo.transShieldOrdCatID,
                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        placeholder="请选择屏蔽医嘱子类项目">
                                        {ordSubCatItem}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={11}>
                            <Form.Item label="屏蔽医嘱项(按下医嘱空格键查询)">
                                {getFieldDecorator('transShieldMed', {
                                    initialValue: concernInfo.transShieldMedID,
                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        showSearch
                                        onInputKeyDown={this.handleSerach}
                                        filterOption={false}
                                        placeholder="请选择条件项目"
                                        onFocus={this.onFocusCondition}
                                    >
                                        {transShieldMedItem}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={11} >
                            <Form.Item label="关联后台方法(与现有code相同,勿改)" style={{color:'red'}}>
                                {getFieldDecorator('linkMethod', {
                                    initialValue: concernInfo.linkMethod,
                                })(
                                    <Input />
                                )}
                            </Form.Item>
                        </Col>  
                        <Col span={11} >
                            <Form.Item label="参数">
                                {getFieldDecorator('parameter', {
                                    initialValue: concernInfo.parameter,
                                })(
                                    <Input />
                                )}
                            </Form.Item>
                        </Col>                                    
                    </Row>
                    <Row>
                        <Col span={22} >
                            <Form.Item label="跳转页面">
                                {getFieldDecorator('jumpPage', {
                                    initialValue: concernInfo.jumpPage,
                                })(
                                    <Input />
                                )}
                            </Form.Item>
                        </Col>                                    
                    </Row>
                </Form>
                <div
                    style={{
                    position: 'absolute',
                    left: 0,
                    bottom: 0,
                    width: '100%',
                    borderTop: '1px solid #e9e9e9',
                    padding: '10px 16px',
                    background: '#fff',
                    textAlign: 'right',
                    }}
                >
                    <Row style={{ width: '100%', textAlign: 'center', marginTop: "30px" }}>
                        {((concernInfo.hospID === "") || (concernInfo.hospID === undefined)) ? 
                            <Button onClick={this.handleSubmit.bind(this, "C")} style={{ marginRight: 8, background: 'rgba(66,185,131,1)', color: '#fff' }}>保存(公共)</Button> 
                            : ""}
                        <Button onClick={this.handleSubmit.bind(this, "H")} style={{ marginRight: 8, background: 'rgba(66,185,131,1)', color: '#fff' }}>保存(本院)</Button>
                        <Button onClick={this.onClose} style={{ marginRight: 8 }}>返回</Button>
                    </Row>
                    
				</div>
            </Drawer>
        )
    }
}

const ConcernFrom = Form.create()(ConcernModal);

export default ConcernFrom;