/**
 * 添加体征需测规则
 */

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

// 组件const
const { Option } = Select;
let user;
let timeout;
class AddRule extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            ruleType: [],
            times: [],
            tempItem: [],
            locList: [],
            blankItem: [],
            conditionItem: [],
            selectIndex: "",
            blankItemAdd: "",
            conditionFilter: true,
            type: "",
        }
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    }
    componentDidMount() {
        this.props.onRef(this);
    }
    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    // 保存配置信息
    handleSubmit = (type, e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {  //!err

                let data = {
                    "params": [{
                        userID: user.userID,    //用户ID
                        hospID: this.props.hospID,    //医院ID
                        code: values.code || '',  //规则代码                   
                        descripts: values.descripts || '',     //规则描述
                        items: values.items ? values.items.join(",") : "",    //需测体征项目
                        type: values.type || '',  //  规则类型      
                        conditionItem: values.conditionItem || '', // 规则项目
                        condition: values.condition || '',    // 生效条件                   
                        todayTimes: values.todayTimes ? values.todayTimes.join(",") : "",      //  当日需测时间点                      
                        otherTimes: values.otherTimes ? values.otherTimes.join(",") : "", //非当日需测时间点 
                        days: values.days || '',    //测量天数
                        locs: values.locs ? values.locs.join(",") : "",   // 生效科室
                        shieldLoc: values.shieldLoc ? values.shieldLoc.join(",") : "",     //无效科室
                        saveType: type,  //保存类型
                    }]
                };
                $http.post('urlADS', this, {
                    code: "04040017",
                    data: data,
                    success: function (res) {
                        let errorCode = res.errorCode;
                        if (errorCode === '0') {
                            message.success("保存成功!");
                            this.onClose();
                            this.props.handelThis.handleQuery(this.props.hospID);
                        }
                    }
                });
            }

        });
    }

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

        });
    };
    // 打开抽屉
    showDrawer = () => {
        let data = {
            params: [{
                hospID: this.props.hospID,    //医院ID
                status: "Y",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04040016",
            data: data,
            success: (res) => {
                this.setState({
                    ruleType: res.result.ruleType,
                    times: res.result.times,
                    tempItem: res.result.tempItem,
                    locList: res.result.locList,
                    visible: true,
                })
            }
        });
    };

    // 重置表单
    resetFields() {
        this.props.form.resetFields();
    }
    /** 快捷筛选 */
    filterOption = (input, option) => {
        return ((option.props.descripts.toLowerCase().indexOf(input.toLowerCase()) >= 0)
            || (option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0)
            || (option.props.descriptsspcode.toLowerCase().indexOf(input.toLowerCase()) >= 0))
    }
    onFocusCondition = () => {
        let type = this.props.form.getFieldValue("type");
        if ((!type) || (type === "")) {
            type = this.props.ruleInfo.ruleType;
        }
        if (!type) {
            message.warn("请先选择规则类型!")
            return;
        }
        if (type === "E") {
            let data = { params: [{}] };
            $http.post('urlDeault', this, {
                code: "04040010",
                data: data,
                success: (res) => {
                    this.setState({ conditionItem: res.data, conditionFilter: true });
                }
            });
        } else if (type === "O") {
            this.setState({ conditionItem: [], conditionFilter: false });
        } else {
            this.setState({ conditionItem: this.state.tempItem, conditionFilter: true });
        }
    }
    ///校验编号
    checkSeqNo = (rule, value, callback) => {
        //与表单数据进行关联
        var regex = /^[1-9]\d*$/;
        if (!value) {
            // 当value值不存在的话
            callback('顺序号不能为空');
        } else {
            if (!regex.test(value)) {
                callback("顺序号只能为正整数");
            }
        }
        callback();
    }

    //可变项目下拉选择
    onChange = (e) => {

        this.setState({ selectIndex: e });
        setTimeout(() => {
            this.props.form.setFieldsValue({ blankItemAdd: this.state.blankItem[e] })
        }, 100)
    }

    ///可变项目维护框
    onAddPressEnter = (e) => {
        let blankItem = this.state.blankItem;
        let selectIndex = this.state.selectIndex;
        if ((selectIndex === "") || (selectIndex === undefined)) {
            if (e.target.value === "") {
                message.warn("请输入内容")
                return;
            }
            if (blankItem.length === 0) {
                blankItem = this.props.ruleInfo.blankItem || [];
            }
            blankItem.push(e.target.value);

        } else {
            if (blankItem.length === 0) {
                blankItem = this.props.ruleInfo.blankItem || [];
            }
            if (e.target.value === "") {
                blankItem.splice(selectIndex, 1);
            } else {
                blankItem[selectIndex] = e.target.value;
            }
        }
        blankItem = this.unique5(blankItem);

        this.setState({
            blankItem: blankItem,
            selectIndex: ""
        })
        setTimeout(() => {
            this.props.form.setFieldsValue({ blankItemAdd: "" })
        }, 100)

    }
    //选择规则类型触发的事件
    onTypeChange = (value) => {
        this.props.form.setFieldsValue({ conditionItem: "" })
        if (value === "E") {

            let data = { params: [{}] };
            $http.post('urlDeault', this, {
                code: "04040010",
                data: data,
                success: (res) => {
                    this.setState({ type: value, conditionItem: res.data, conditionFilter: true });
                }
            });
        } else if (value === "O") {
            this.setState({ type: value, conditionFilter: false });
        } else {
            this.setState({ type: value, conditionItem: this.state.tempItem, conditionFilter: true });
        }
    }

    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);
    }
    // 条件类型为医嘱是查询数据
    handleSerach = (e) => {
        if (e.keyCode == '32') {
            let value = e.target.value;
            value = value.replace(/\s*/g, "");
            if (this.props.form.getFieldValue("type") === "O") {
                var reg = /\s/g;
                if (reg.test(value)) {
                    message.error('不能输入空字符')
                    return
                }
                this.GetMedItem(value, data => this.setState({ conditionItem: data }))
            }
        }
    }

    /** 去重*/
    unique5(arr) {
        var x = new Set(arr);
        return [...x];
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        let ruleInfo = this.props.ruleInfo ? this.props.ruleInfo : {};
        let types = [], items = [], conditionItems = [], times = [], locs = [];
        this.state.ruleType.map((item) => {
            types.push(
                <Option key={item.id}>{item.descripts}
                </Option>
            )
        })
        this.state.tempItem.map((item) => {
            items.push(
                <Option key={item.key}>{item.descripts}
                </Option>
            )
        })
        if (this.state.type !== "") {
            this.state.conditionItem.map((item) => {
                if ((item.id !== undefined) && (item.id !== "")) {
                    conditionItems.push(
                        <Option key={item.id}>{item.descripts}
                        </Option>
                    )
                }
            })
        } else {
            if (ruleInfo.itemBaseData) {
                ruleInfo.itemBaseData.map((item) => {
                    if ((item.id !== undefined) && (item.id !== "")) {
                        conditionItems.push(
                            <Option key={item.id}>{item.descripts}
                            </Option>
                        )
                    }
                })
            }
        }

        this.state.times.map((item) => {
            times.push(
                <Option key={item}>{item}
                </Option>
            )
        })
        this.state.locList.map((item) => {
            locs.push(
                <Option key={item.id}>{item.descripts}
                </Option>
            )
        })

        return (
            <Drawer
                title={this.props.title + "需测生命体征规则"}
                width={720}
                onClose={this.onClose}
                visible={this.state.visible}
                style={{
                    overflow: 'auto',
                    height: 'calc(100% - 108px)',
                    paddingBottom: '108px',
                }}
            >
                <Form layout="vertical" onSubmit={this.handleSubmit}  >
                    {/* 第一行 */}
                    <Row>
                        <Col span={7}>
                            <Form.Item label="规则代码">
                                {getFieldDecorator('code', {
                                    initialValue: ruleInfo.ruleCode,
                                    rules: [{ required: true, message: '请输入规则代码' }]
                                })(
                                    <Input placeholder="请输入规则代码" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="规则描述">
                                {getFieldDecorator('descripts', {
                                    initialValue: ruleInfo.ruleDesc,
                                    rules: [{ required: true, message: '请输入规则描述' }],
                                })(
                                    <Input placeholder="请输入规则描述" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="需测体征项目">
                                {getFieldDecorator('items', {
                                    initialValue: ruleInfo.ruleItemID,
                                    rules: [{ required: true, message: '请选择需测体征项目' }],
                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        placeholder="请选择需测体征项目" >
                                        {items}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第二行 */}
                    <Row>
                        <Col span={7} >
                            <Form.Item label="规则类型">
                                {getFieldDecorator('type', {
                                    initialValue: ruleInfo.ruleType,
                                    rules: [{ required: true, message: '请选择规则类型' }],
                                })(
                                    <Select
                                        allowClear={true}
                                        onChange={this.onTypeChange}
                                        placeholder="请选择规则类型" >
                                        {types}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label='条件项目(医嘱空格键查询)'>
                                {getFieldDecorator('conditionItem', {
                                    initialValue: ruleInfo.conditionItemID,
                                    rules: [{ required: true, message: '请选择条件项目' }]
                                })(
                                    <Select
                                        allowClear={true}
                                        showSearch
                                        filterOption={this.state.conditionFilter}
                                        onInputKeyDown={this.handleSerach}
                                        placeholder="请选择条件项目"
                                        onFocus={this.onFocusCondition}
                                    >
                                        {conditionItems}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label='生效条件'>
                                {getFieldDecorator('condition', {
                                    initialValue: ruleInfo.condition,
                                    rules: [{ message: '生效条件' }],
                                })(
                                    <Input placeholder="生效条件" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第三行 */}
                    <Row>
                        <Col span={7}>
                            <Form.Item label="当日需测时间点">
                                {getFieldDecorator('todayTimes', {
                                    initialValue: ruleInfo.todayTimes,
                                })(
                                    <Select
                                        mode="multiple"
                                        allowClear={true}
                                        showSearch={true}
                                        placeholder="当日需测时间点"
                                    >
                                        {times}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="非当天需测时间点">
                                {getFieldDecorator('otherTimes', {
                                    initialValue: ruleInfo.otherTimes,
                                })(
                                    <Select
                                        allowClear={true}
                                        showSearch={true}
                                        mode="multiple"
                                        placeholder="非当天需测时间点"
                                    >
                                        {times}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="测量天数">
                                {getFieldDecorator('days', {
                                    initialValue: ruleInfo.ruleDays,
                                    rules: [{ message: '请输入测量天数' }],
                                })(
                                    <Input placeholder="请输入测量天数" className='input' />
                                )}
                            </Form.Item>
                        </Col>

                    </Row>
                    {/* 第四行 */}
                    <Row>
                        <Col span={7}  >
                            <Form.Item label="生效科室">
                                {getFieldDecorator('locs', {
                                    initialValue: ruleInfo.locs,
                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        placeholder="请选择生效科室" >
                                        {locs}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="无效科室">
                                {getFieldDecorator('shieldLoc', {
                                    initialValue: ruleInfo.shieldLocs,
                                })(
                                    <Select
                                        allowClear={true}
                                        mode="multiple"
                                        placeholder="请选择无效科室" >
                                        {locs}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row style={{ width: '100%', textAlign: 'center', marginTop: "30px" }}>
                        {((ruleInfo.hospID === "") || (ruleInfo.hospID === undefined)) ? <Button onClick={this.handleSubmit.bind(this, "C")} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存(公共)</Button> : ""}
                        {ruleInfo.ruleCode !== undefined ? <Button onClick={this.handleSubmit.bind(this, "H")} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存(本院)</Button> : ""}
                    </Row>
                </Form>
            </Drawer>
        )

    }
}
const AddRuleFrom = Form.create()(AddRule);

export default AddRuleFrom;
