/*
 * Creator:     ML
 * CreatDate:   2020-05-08
 * descripts：  中医体质辨识 / 中医体质辨识健康指导
 * */
import React from 'react';
import moment from 'moment';
import { Util, } from 'tools/index';
import store from 'store';
import E from 'wangeditor';
import { Form, Col, Select, Icon, Tooltip, Button, Row, TimePicker, DatePicker, Radio, Input, message, Popconfirm, Checkbox } from 'antd';
import { $http } from 'containers/config/https';
//组件const
const Option = Select.Option;
const FormItem = Form.Item;
const padding = {
    padding: "0px"
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 3 },
    wrapperCol: { span: 20 }
}
const formItemLayoutDataForm = {
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
}
const formItemLayouts = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 }
}
let activedID = ""
const AssessmentConsGuidance = Form.create()(
    class AssessmentConsGuidance extends React.Component {
        constructor(props) {
            let userData = sessionStorage.getItem("userData") ? JSON.parse(sessionStorage.getItem("userData")) : {};
            let assessData = sessionStorage.getItem("assessData") ? JSON.parse(sessionStorage.getItem("assessData")) : {};
            super(props);
            this.state = {
                editorContent: "<div></div>",
                checkboxOne: [""],
                checkboxTwo: [""],
                disCheckArr: true,
                userData,
                assessData,
                diseaseArr: [],
                typeArr: [],
                requid: this.props.requireds,
                requireds: true,
                doctor: "",
                isTransitionStart: true,
                delStatus: true,
            };
        }

        componentWillReceiveProps(nextProps) {
            if (nextProps.doctorID != this.state.doctor) {
                if (nextProps.doctorID) {
                    this.handleGetData(nextProps.doctorID)
                    this.setState({
                        doctorID: nextProps.doctorID,
                        doctor: nextProps.doctorID
                    })
                }
            }
        }

        componentDidMount = () => {
            this.props.onRef(this)
            activedID = this.props.id

            //设置富文本
            const elem = this.refs.editorElem
            const editor = new E(elem)
            editor.customConfig.onchange = html => {
                this.setState({
                    editorContent: html
                }, () => {
                })
            }
            editor.customConfig.menus = [
                'head',  // 标题
                'bold',  // 粗体
                'fontSize',  // 字号
                'fontName',  // 字体
                'italic',  // 斜体
                'underline',  // 下划线
                'foreColor',  // 文字颜色
                'list',  // 列表
                'justify',  // 对齐方式
                'quote',  // 引用
                'emoticon',  // 表情
                'undo',  // 撤销
                'redo'  // 重复
            ]
            editor.create()
            this.editor = editor
            this.setCont()
            const { userData } = this.state
            let datas = {}
            datas = {
                params: [{
                    hospID: userData && userData.hospID || "",
                }],
            }
            $http.post('urlS', this, {
                code: '03070033',
                data: datas,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            diseaseArr: res.result.data
                        })
                    }
                }
            })
        }
        //设置富文本内容
        setCont = () => {
            // console.log("this.state.editorContent",this.state.editorContent)
            this.editor.txt.html(this.state.editorContent)
            if (document.querySelector('.w-e-text-container')) {
                document.querySelector('.w-e-text-container').style.height = store.getState().tableHeight.y - 260 + 'px'
                document.querySelector('.w-e-text-container').style.zIndex = 998
            }
            if (document.querySelector('.w-e-menu')) {
                let a = document.querySelectorAll('.w-e-menu')
                for (var i = 0; i < a.length; i++) {
                    a[i].style.zIndex = 999
                }
            }
        }
        del = () => {
            const { userData } = this.state
            let data = {}
            data = {
                params: [{
                    userID: userData && userData.userID || "",
                    healthRecordID: this.state.doctorID,
                    assessCatCode: "a30"
                }],
            }
            $http.post('urlS', this, {
                code: '03070081',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("删除成功")
                        window.sessionStorage.setItem("noSave", false);
                        this.clear()
                        this.setState({
                            delStatus: true
                        })
                    }
                }
            })
        }
        //清空
        clear = (d) => {
            this.props.form.resetFields();
            this.setState({
                collectTime: "",
                editorContent: this.state.editorContent || "<div></div>",
                checkboxOne: [""],
                checkboxTwo: [""],
                disCheckArr: true,
                physiqueClassID: this.state.physiqueClassID || "",
                oneValue: this.state.oneValue || ""
            }, () => {
                this.setCont()
            })
            if (d) {
                this.setState({
                    delStatus: true,
                    doctorID: ""
                })
            }
        }
        setValue = (id, flag) => {
            this.setState({
                doctorID: id,
                activeFlag: flag
            }, () => {
                this.handleGetData(id, flag)
            })
            // if(activedID!=id){
            //     // debugger
            //     this.setState({
            //         doctorID: id,
            //         obj: {}
            //     }, () => {
            //         this.handleGetData(id)
            //     })
            // }else{
            //     console.log("this.props.objs",this.props.objs)
            //     this.setState({
            //         doctorID: id,
            //     }, () => {
            //         this.handleGetData(id)
            //     })
            // }

        }
        //日期
        onPanelChange = (n, v) => {
            if (!v) {
                if (n == 1) {
                    window.sessionStorage.setItem("noSave", true);
                    this.setState({
                        dateF: "",
                    })
                } else {
                    this.setState({
                        dateT: ""
                    })
                }
            } else {
                if (n == 1) {
                    window.sessionStorage.setItem("noSave", true);
                    this.setState({
                        dateF: moment(v).format("YYYY-MM-DD"),
                    })
                } else {
                    this.setState({
                        dateT: moment(v).format("YYYY-MM-DD"),
                    })
                }
            }

        }
        //展开/关闭起始时间
        handleOnOpenChangeStart = (status) => {
            if (!status) {
                this.setState({ isTransitionStart: true })
            } else {
                this.setState({ isTransitionStart: false })
            }
        }

        handleChange = (e, name) => {
            if (e.target) {
                if (name) {
                    if (this.state[name + "Value"] !== e.target.value) {
                        window.sessionStorage.setItem("noSave", true);
                    } else {
                        window.sessionStorage.setItem("noSave", false);
                    }
                    this.setState({
                        [name + 'Value']: e.target.value,
                    });
                }
            }
        };
        //获取
        handleGetData = (id, flag) => {
            const { assessData, obj } = this.state
            // debugger
            let data = {}
            data = {
                params: [
                    {
                        healthRecordID: id || "",
                        assessmentCatCode: "a30"
                    }
                ],
            }
            $http.post('urlS', this, {
                code: '03070037',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if (res.result.doctorID) {
                            this.setState({
                                healthDoctorID: res.result.doctorID
                            })
                        }
                        //体质分类下拉框数据
                        if (res.result.pullDown) {
                            this.setState({
                                physiqueClassData: res.result.pullDown.result,
                                oneValue: res.result.pullDown.ageGroup,
                                physiqueClassID: res.result.pullDown.defaultDown,
                            })
                        }
                        //回显分为默认显示和保存过后显示 默认显示取pullDown 内容  保存过后回显children里面数据
                        if (res.result.doctorID && res.result.father) {
                            this.setState({
                                collectTime: res.result.father[0].collectTime
                            })
                            this.props.form.setFieldsValue({ collectDate: moment(res.result.father[0].collectDate), diseaseID: res.result.father[0].collectUserID, });
                            //操作数据回显 
                            if (res.result.father[0].children) {
                                this.setState({
                                    delStatus: false,
                                })
                                let data = {}
                                data = res.result.father[0].children
                                let a = data.a3003 || " & "
                                let b = a.split("&")
                                let c = data.a3004 || " & "
                                let d = c.split("&")
                                this.setState({
                                    oneValue: data.a3001 || res.result.pullDown.ageGroup,
                                    physiqueClassID: data.a3002 || res.result.pullDown.defaultDown,
                                    checkboxOne: b,
                                    checkboxTwo: d,
                                    editorContent: data.a3005note || content,
                                }, () => {
                                    if (this.state.checkboxOne.includes("a300304")) {
                                        this.setState({
                                            disCheckArr: false,
                                        })
                                    } else {
                                        this.setState({
                                            disCheckArr: true,
                                            checkboxTwo: [""]
                                        })
                                    }
                                    this.setCont()
                                })
                            }
                        } else {
                            //清空  设置默认
                            this.setState({
                                delStatus: true
                            })
                            let content = "<div></div>"
                            if (res.result.pullDown.result) {
                                res.result.pullDown.result && res.result.pullDown.result.map((item, i) => {
                                    if (res.result.pullDown.defaultDown == item.code) {
                                        content = item.textContent
                                    }
                                })
                            }
                            // console.log("content0000",content)
                            this.setState({
                                oneValue: res.result.pullDown.ageGroup,
                                physiqueClassID: res.result.pullDown.defaultDown,
                                editorContent: content,
                            }, () => {
                                this.clear()
                                // console.log("content",content)
                            })
                        }
                    } else {
                        //接口返回错误
                    }
                }
            })
        }
        //设置note
        handleTonote = (code, obj) => {
            let toObj = {
                'a280201': () => obj['assessNote'] = this.state.a280201note,
                'a280202': () => obj['assessNote'] = this.state.a280202note,
                'a280203': () => obj['assessNote'] = this.state.a280203note,
                'a280204': () => obj['assessNote'] = this.state.a280204note,
                'a280205': () => obj['assessNote'] = this.state.a280205note,
                'a280206': () => obj['assessNote'] = this.state.a280206note,
                'a2301': () => obj['assessNote'] = this.state.a2301note,
            }
            if (toObj[code]) {
                toObj[code]();
            }
        }
        //保存
        handleSave = () => {
            const { ufserData, checkboxOne, checkboxTwo } = this.state
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    let data = {}
                    let a = checkboxOne
                    let b = a.join("&")
                    let c = checkboxTwo
                    let d = c.join("&")
                    data = {
                        params: [
                            {
                                doctorID: this.state.healthDoctorID || "",//体检记录责任医生 
                                locID: userData && userData.locID || "",
                                hospID: userData && userData.hospID || "",
                                patID: sessionStorage.getItem("patID") ? JSON.parse(sessionStorage.getItem("patID")) : "",
                                healthRecordID: this.state.doctorID && this.state.doctorID || "",
                                assessCat: [
                                    {
                                        assessCatCode: "a30",
                                        collectDate: values.collectDate ? moment(values.collectDate).format('YYYY-MM-DD') : moment(moment()).format('YYYY-MM-DD'),
                                        collectUserID: values.diseaseID || "",
                                        assessItem: [
                                            {
                                                assessItemCode: "a3001",
                                                assessItemValue: this.state.oneValue,
                                                // assessNote: this.state.oneScore,
                                            },
                                            {
                                                assessItemCode: "a3002",
                                                assessItemValue: this.state.physiqueClassID,
                                                // assessNote: this.state.twoScore,
                                            }, {
                                                assessItemCode: "a3003",
                                                assessItemValue: b,
                                                // assessNote: this.state.threeScore,
                                            }, {
                                                assessItemCode: "a3004",
                                                assessItemValue: d,
                                                // assessNote: this.state.fourScore,
                                            }, {
                                                assessItemCode: "a3005",
                                                // assessItemValue: this.state.editorContent,
                                                assessNote: this.state.editorContent,
                                            },

                                        ]
                                    }
                                ]
                            }
                        ],
                    }
                    $http.post('urlS', this, {
                        code: '03070035',
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                // if (this.state.doctorID && this.state.doctorID) {
                                //     message.success("更新成功")
                                // } else {
                                //     message.success("保存成功")
                                // }
                                this.setState({
                                    delStatus: false
                                })
                                window.sessionStorage.setItem("healthRecordID", res.result.healthRecordID);
                                window.sessionStorage.setItem("noSave", false);
                                if (!this.state.doctorID) {

                                } this.props.updateHeathList()
                                message.success("保存成功")
                                this.handleGetData(res.result.healthRecordID)
                            } else {

                            }
                        }
                    })
                }
            })

        }
        handleChangeInput = (e, name) => {
            if (e.target) {
                if (this.state[name] !== e.target.value) {
                    window.sessionStorage.setItem("noSave", true);
                } else {
                    window.sessionStorage.setItem("noSave", false);
                }
                this.setState({
                    [name]: e.target.value,
                }, () => {
                })
            }
        }
        handleRadio = (e,) => {
            let tag = e.target;
            let arr = tag.id.split("^")
            if (tag.value) {
                if (tag.type === 'radio' && arr[0].toString() === tag.value.toString()) {
                    this.setState({
                        [arr[1]]: '',
                        [arr[2]]: 0,
                    }, () => {
                        // this.handleTotal()
                    });
                }
            }
        }
        handleChangeTwo = (e) => {
            this.setState({
                checkboxTwo: e
            })
        }
        handleChangeOne = (e) => {
            if (e[e.length - 1] != "a23120505") {
                let newArr = []
                e && e.map((i, s) => {
                    if (i == "a23120505") {
                        newArr = e.splice(s + 1)
                        this.setState({
                            checkboxOne: newArr,
                        })
                    } else {
                        this.setState({
                            checkboxOne: e
                        })
                    }
                })
            } else if (e.includes("a23120505")) {
                let arr = []
                arr.push(e[e.length - 1])
                this.setState({
                    checkboxOne: arr,
                    disCheckArr: true,
                })
            } else {
                this.setState({
                    checkboxOne: e
                })
            }
            //点击肿瘤选项
            if (e.includes("a300304")) {
                this.setState({
                    disCheckArr: false,
                })
            } else {
                this.setState({
                    disCheckArr: true,
                    checkboxTwo: [""]
                })
            }
        }
        handleCont = (textContent) => {
            window.sessionStorage.setItem("noSave", true)
            this.setState({
                editorContent: textContent
            }, () => {
                this.setCont()
            })
        }
        render() {
            const { getFieldDecorator } = this.props.form;
            const { diseaseArr, physiqueClassData } = this.state;

            //疾病
            let diseaseOp = []
            diseaseArr && diseaseArr.map(item => {
                diseaseOp.push(<Option key={item.id} name={item.descriptsSPCode} title={item.descripts} onClick={() => window.sessionStorage.setItem("noSave", true)} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.id)}>{item.descripts}</Option>)
            })
            //体质分类physiqueClassOp
            let physiqueClassOp = []
            physiqueClassData && physiqueClassData.map(item => {
                physiqueClassOp.push(<Option key={item.code} name={item.descriptsSPCode} title={item.descripts} onClick={() => this.handleCont(item.textContent)} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.code)}>{item.descripts}</Option>)
            })
            return (
                <div id="guidance-Dom" style={{ height: store.getState().tableHeight.y + 20 + 'px' }}>
                    <Row style={{ textAlign: "center" }}>
                        <h2>中医体质辨识健康指导</h2>
                    </Row>
                    <Row style={{ position: "relative" }}>
                        <Form>
                            <Col span={5} className="starDataDom" style={{ padding: "0" }}>
                                <FormItem label='辨识时间' {...formItemLayoutDataForm}>
                                    {getFieldDecorator('collectDate', {
                                        initialValue: moment(),
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <DatePicker onChange={(v) => this.onPanelChange(1, v)} style={{ width: '100%' }} placeholder={'调查日期'} disabledDate={(curDate) => {
                                            return curDate && curDate > moment().endOf('day');
                                        }} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col
                                span={6}
                                // style={padding}
                                className="select-item"
                                style={{ margin: "0 24px" }}
                            >
                                <FormItem {...formItemLayouts} label={this.props.locale && this.props.locale == 'EN' ? 'disease' : '指导医生'} >
                                    {getFieldDecorator('diseaseID', {
                                        initialValue: this.state.userData && this.state.userData.userID || undefined,
                                        rules: [{ required: true, message: '请选择指导医生' }]
                                    })(
                                        <Select
                                            style={{ width: "100%", textAlign: "left", }}
                                            showSearch={true}
                                            optionFilterProp="role"
                                        >
                                            {diseaseOp}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{ paddingLeft: "0", position: "absolute", right: "96px" }}>
                                <FormItem  {...formItemLayout}>
                                    {getFieldDecorator('findData', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <div style={{ display: "flex", marginTop: "4px" }}>
                                            <Popconfirm disabled={this.state.delStatus} title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.del()} >
                                                <Button type="danger" style={{ color: this.state.delStatus ? "#bfbfbf" : "#ffff", cursor: this.state.delStatus ? "not-allowed" : "pointer", background: this.state.delStatus ? "#fff" : "#ff7875", border: this.state.delStatus ? "1px solid #bfbfbf" : "1px solid #ff7875" }}  >删除指导</Button>
                                            </Popconfirm>
                                            {/* <Button style={{ background: "#fff", color: "#1890ff", margin: "0 18px 0 18px" }} type="primary">打印</Button> */}
                                            <Button style={{ margin: "0 18px 0 18px" }} onClick={this.handleSave} type="primary">{"保存"}</Button>
                                        </div>
                                    )}
                                </FormItem>
                            </Col>
                        </Form>
                    </Row>
                    <div>
                        <div className="conent" onClick={(e) => this.handleRadio(e)}>
                            <Row style={{ display: "flex", paddingBottom: "0" }}>
                                <Col span={2}>
                                    <p>
                                        年龄段分类
                                    </p>
                                </Col>
                                <Col span={20}>
                                    <Radio.Group onChange={(e) => this.handleChange(e, "one")} value={this.state.oneValue}>
                                        <Radio value={"a300101"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a19001"}>儿童（0-6岁）</Radio>
                                        <Radio value={"a300102"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a1001"}>少年（7-17岁）</Radio>
                                        <Radio value={"a300103"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a101"}>青年（18-40岁）</Radio>
                                        <Radio value={"a300104"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a1011"}>中年（41-65岁）</Radio>
                                        <Radio value={"a300105"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a1900"}>老年（66岁以后）</Radio>
                                    </Radio.Group>
                                </Col>

                            </Row>
                            <Row style={{ display: "flex", paddingBottom: "0" }}>
                                <Col span={2}>
                                    <p>
                                        体质分类
                                    </p></Col>
                                <Col span={10}>
                                    <Select getPopupContainer={triggerNode => triggerNode.parentNode}
                                        showSearch
                                        onChange={Util.handleSelectChange.bind(this, "physiqueClassID")}
                                        value={this.state.physiqueClassID} style={{ width: "100%" }}
                                        filterOption={(input, option) =>
                                            option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }>
                                        {physiqueClassOp}
                                    </Select>
                                </Col>
                            </Row>
                            <Row style={{ display: "flex", paddingBottom: "0" }}>
                                <Col span={2}>
                                    <p>
                                        适应人群
                                    </p>
                                </Col>
                                <Col span={20}>
                                    <Checkbox.Group onChange={(e) => this.handleChangeOne(e)} value={this.state.checkboxOne}>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea01"} value={"a300301"}>高血压</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea02"} value={"a300302"}>糖尿病</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea03"} value={"a300303"}>孕产妇</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea04"} value={"a300304"}>肿瘤</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea04"} value={"a300305"}>重点人群</Checkbox>
                                    </Checkbox.Group>
                                </Col>
                            </Row>
                            <Row style={{ display: "flex", paddingBottom: "0" }}>
                                <Col span={2}>
                                    <p>
                                        肿瘤类别
                                    </p>
                                </Col>
                                <Col span={20}>
                                    <Checkbox.Group disabled={this.state.disCheckArr} onChange={(e) => this.handleChangeTwo(e)} value={this.state.checkboxTwo}>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea01"} value={"a300401"}>大肠</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea02"} value={"a300402"}>胃</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea04"} value={"a300403"}>肝</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea04"} value={"a300404"}>肺</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea04"} value={"a300405"}>乳腺</Checkbox>
                                        <Checkbox id={this.state.threeaValue + "^" + "threeaValue" + "^" + "oneScore" + "^" + "threea04"} value={"a300406"}>宫颈肺</Checkbox>
                                    </Checkbox.Group>
                                </Col>
                            </Row>
                            <Row style={{ display: "flex", paddingBottom: "0" }}>
                                <Col span={2}>
                                    <p>
                                        指导内容
                                    </p>
                                </Col>
                                <Col span={20}>
                                    {/* 生成编辑器 */}
                                    <div ref="editorElem" style={{ textAlign: 'left', margin: '12px 0px 0px 0px' }}>
                                    </div>
                                </Col>
                            </Row>
                        </div>
                    </div>
                </div >
            );
        }
    })
export default AssessmentConsGuidance
