/**
 * 添加生命体征配置
 */

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

// 组件const
const { Option } = Select;
class AddConfig extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            unitArr: [],
            timesArr: [],
            typeArr: [],
            config: [],
            blankItem: [],
            selectIndex: "",
            blankItemAdd: "",
        }
    }
    componentDidMount() {
        this.props.onRef(this);
    }
    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }
    getConfigData = () => {
        let data = {
            params: [{
                hospID: this.props.hospID,    //医院ID
                code: "",
                descripts: "",
                status: "Y",
                addPatCol: "0",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04040001",
            data: data,
            success: (res) => {
                this.setState({
                    unitArr: res.result.unit,
                    timesArr: res.result.times,
                    typeArr: res.result.type,
                    config: res.result.config,
                })
            }
        });


    }
    // 保存配置信息
    handleSubmit = (type, e) => {
        e.preventDefault();
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        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 || '',     //描述
                        ENDesc: values.ENDesc || '',     //英文描述
                        type: values.type || '',    //数据类型
                        times: values.times || '',  //  填写次数
                        linkItem: values.linkItem || '',
                        normalRangeFrom: values.normalRangeFrom || '',    // 正常低值
                        normalRangeTo: values.normalRangeTo || '',      //  正常高值
                        errorRangeFrom: values.errorRangeFrom || '', //错误低值
                        errorRangeTo: values.errorRangeTo || '',    //错误高值
                        unit: values.unit || '',   // 填写单位
                        color: values.color || '',     //颜色
                        graph: values.graph || '',   //图案
                        babyFlag: values.babyFlag === true ? "Y" : "N",   //婴儿标记
                        saveType: type,  //保存类型
                        status: values.status === true ? "Y" : "N",   //状态
                        seqNo: values.seqNo || '',         //序号
                        blankItem: this.state.blankItem.length === 0 ? "" : this.state.blankItem.join("^"),  //可变项目
                        blankItemFlag: values.blankItemFlag === true ? "Y" : "N",   //是否可变项目标记
                        drawLine: values.drawLine === true ? "Y" : "N",   //是否画线
                        baseVal: values.baseVal || '0',  //最小刻度
                        stroke: values.stroke || '',   //线条宽度
                        unitVal: values.unitVal || '',  //每小格的值
                    }]
                };
                $http.post('urlADS', this, {
                    code: "04040002",
                    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,
        }, () => {
            // 如果为编辑，则关闭后清除表单

            this.props.handelThis.resetConfigInfo();
            this.resetFields()

        });
    };
    // 打开抽屉
    showDrawer = () => {
        this.setState({
            visible: true,
        });
        this.getConfigData();
    };

    // 重置表单
    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))
    }

    ///校验编号
    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.configInfo.blankItem || [];
            }
            blankItem.push(e.target.value);

        } else {
            if (blankItem.length === 0) {
                blankItem = this.props.configInfo.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)

    }

    /** 去重*/
    unique5(arr) {
        var x = new Set(arr);
        return [...x];
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        let configInfo = this.props.configInfo ? this.props.configInfo : {};
        let linkItem = [];
        this.state.config.map((item) => {
            linkItem.push(
                <Option key={item.key}>{item.descripts}
                </Option>
            )
        })
        let blankItem = [];
        const blankItems = (this.state.blankItem.length === 0) && (configInfo.blankItem) ? configInfo.blankItem : this.state.blankItem;
        blankItems.map((item, index) => {
            blankItem.push(
                <Option key={index}>{item}
                </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('seqNo', {
                                    initialValue: configInfo.seqNo,
                                    rules: [{ required: true, validator: this.checkSeqNo }]
                                })(
                                    <Input placeholder="请输入填写序号" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="项目代码">
                                {getFieldDecorator('code', {
                                    initialValue: configInfo.code,
                                    rules: [{ required: true, message: '请输入体征代码' }]
                                })(
                                    <Input placeholder="请输入体征代码" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="项目描述">
                                {getFieldDecorator('descripts', {
                                    initialValue: configInfo.descripts,
                                    rules: [{ required: true, message: '请输入体征项目描述' }],
                                })(
                                    <Input placeholder="请输入体征项目描述" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第二行 */}
                    <Row>
                        <Col span={7} >
                            <Form.Item label="英文描述">
                                {getFieldDecorator('ENDesc', {
                                    initialValue: configInfo.ENDesc,
                                })(
                                    <Input placeholder="请输入体征项目英文描述" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="数据类型">
                                {getFieldDecorator('type', {
                                    initialValue: configInfo.type,
                                    rules: [{ required: true, message: '请选择数据类型' }],
                                })(
                                    <Select
                                        allowClear={true}
                                        placeholder="请选择数据类型" >
                                        {this.state.typeArr.map(item => <Option key={item.value}>{item.value}</Option>)}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="录入次数">
                                {getFieldDecorator('times', {
                                    initialValue: configInfo.times,
                                    rules: [{ required: true, message: '请输入录入次数' }],
                                })(
                                    <Select
                                        allowClear={true}
                                        placeholder="请选择录入次数" >
                                        {
                                            this.state.timesArr.map(
                                                item => <Option key={item.value}>{item.value}</Option>
                                            )
                                        }
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第三行 */}
                    <Row>
                        <Col span={7}  >
                            <Form.Item label="测量单位">
                                {getFieldDecorator('unit', {
                                    initialValue: configInfo.unitDr,
                                    rules: [{ message: '请选择测量单位' }],
                                })(
                                    <Select
                                        allowClear={true}
                                        showSearch={true}
                                        placeholder="请选择测量单位"
                                        filterOption={this.filterOption}
                                    >
                                        {this.state.unitArr.map(item =>
                                            <Option
                                                key={item.id}
                                                descriptsspcode={item.descriptsSPCode}
                                                descripts={item.descripts}
                                                code={item.code}
                                            >
                                                {item.code}
                                            </Option>)
                                        }
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="关联项目">
                                {getFieldDecorator('linkItem', {
                                    initialValue: configInfo.linkItem,
                                    rules: [{ message: '关联项目' }],
                                })(
                                    <Select
                                        allowClear={true}
                                        showSearch={true}
                                        placeholder="关联项目"
                                    >
                                        {linkItem}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="婴儿标记">
                                {getFieldDecorator('babyFlag', {
                                    valuePropName: 'checked',
                                    initialValue: configInfo.babyFlag === "Y" ? true : false,
                                })(

                                    <Switch checkedChildren="是" unCheckedChildren="否" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第四行 */}
                    <Row>
                        <Col span={7}  >
                            <Form.Item label="正常低值">
                                {getFieldDecorator('normalRangeFrom', {
                                    initialValue: configInfo.normalRangeFrom,
                                    rules: [{ message: '请输入正常低值' }],
                                })(
                                    <Input placeholder="请输入正常低值" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="正常高值">
                                {getFieldDecorator('normalRangeTo', {
                                    initialValue: configInfo.normalRangeTo,
                                    rules: [{ message: '请输入正常高值' }],
                                })(
                                    <Input placeholder="请输入正常高值" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="错误低值">
                                {getFieldDecorator('errorRangeFrom', {
                                    initialValue: configInfo.errorRangeFrom,
                                    rules: [{ message: '请输入错误低值' }],
                                })(
                                    <Input placeholder="请输入错误低值" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第五行 */}
                    <Row>
                        <Col span={7} >
                            <Form.Item label="错误高值">
                                {getFieldDecorator('errorRangeTo', {
                                    initialValue: configInfo.errorRangeTo,
                                    rules: [{ message: '请输入错误高值' }],
                                })(
                                    <Input placeholder="请输入错误高值" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="可变内容">
                                {getFieldDecorator('blankItem', {
                                    initialValue: "",
                                })(
                                    <Select
                                        allowClear={true}
                                        showSearch={true}
                                        placeholder="可变内容"
                                        onChange={this.onChange}
                                    >
                                        {blankItem}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="可变项目维护:">
                                {getFieldDecorator('blankItemAdd', {
                                    initialValue: "",
                                })(
                                    <Input placeholder="输入后回车(Enter)" onPressEnter={this.onAddPressEnter} className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第六行 */}
                    <Row>
                        <Col span={7} >
                            <Form.Item label="可变项目">
                                {getFieldDecorator('blankItemFlag', {
                                    valuePropName: 'checked',
                                    initialValue: (configInfo.blankItemFlag === "Y") ? true : false,
                                })(
                                    <Switch
                                        checkedChildren="是"
                                        unCheckedChildren="否"
                                        className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="画线项目">
                                {getFieldDecorator('drawLine', {
                                    valuePropName: 'checked',
                                    initialValue: (configInfo.drawLine === "Y") ? true : false,
                                })(
                                    <Switch
                                        checkedChildren="是"
                                        unCheckedChildren="否"
                                        className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="划线颜色">
                                {getFieldDecorator('color', {
                                    initialValue: configInfo.color,
                                    rules: [{ message: '划线颜色' }],
                                })(
                                    <Input placeholder="划线颜色(RGB)" className='input' />
                                )}
                            </Form.Item>
                        </Col>

                    </Row>
                    {/* 第七行 */}
                    <Row>
                        <Col span={7}>
                            <Form.Item label="图案">
                                {getFieldDecorator('graph', {
                                    initialValue: configInfo.graph,
                                    rules: [{ message: '图案' }],
                                })(
                                    <Input placeholder="图案" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="线条宽度:">
                                {getFieldDecorator('stroke', {
                                    initialValue: configInfo.stroke,
                                })(
                                    <Input placeholder="线条宽度" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="最小刻度:">
                                {getFieldDecorator('baseVal', {
                                    initialValue: configInfo.baseVal,
                                    /**
                                     * @ByYQY: 生命体征最小刻度输入限制
                                     * Create 2022-1-29
                                     */
                                    rules: [{ required: true, message: '请输入最小刻度' }],
                                })(
                                    <Input placeholder="最小刻度" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {/* 第八行 */}
                    <Row>
                        <Col span={7} >
                            <Form.Item label="每小格值:">
                                {getFieldDecorator('unitVal', {
                                    initialValue: configInfo.unitVal,
                                })(
                                    <Input placeholder="每小格值" className='input' />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={7} offset={1}>
                            <Form.Item label="是否显示">
                                {getFieldDecorator('status', {
                                    valuePropName: 'checked',
                                    initialValue: (configInfo.status === "Y") || (configInfo.status === undefined) || (configInfo.hospID === "") ? true : false,
                                })(
                                    <Switch
                                        disabled={(configInfo.status === undefined) || (configInfo.hospID === "") ? true : false}
                                        checkedChildren="是"
                                        unCheckedChildren="否"
                                        className='input' />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row style={{ width: '100%', textAlign: 'center', marginTop: "30px" }}>
                        {((configInfo.hospID === "") || (configInfo.hospID === undefined)) ? <Button onClick={this.handleSubmit.bind(this, "C")} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存(公共)</Button> : ""}
                        <Button onClick={this.handleSubmit.bind(this, "H")} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存(本院)</Button>
                    </Row>
                </Form>
            </Drawer>
        )

    }
}
const ConfigAddFrom = Form.create()(AddConfig);

export default ConfigAddFrom;
