/*
 * Creator:     ML
 * CreatDate:   2020-04-08
 * descripts：  心理评估
 * */
import React from 'react';
import moment from 'moment';
import { dayFormat } from 'tools/index';
import { Form, Col, Select, Icon, Tooltip, Button, Row, TimePicker, DatePicker, Radio, message, Popconfirm } 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 formItemLayoutPeo = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}
const formItemLayoutDataForm = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
}
const formItemLayoutCenter = {
    labelCol: { span: 2 },
    wrapperCol: { span: 24 },
}
const formItemLayouts = {
    labelCol: { span: 3 },
    wrapperCol: { span: 24 }
}
const AssessmentPsychological = Form.create()(
    class AssessmentPsychological 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);
            var date = new Date();
            this.state = {
                userData,
                assessData,
                diseaseArr: [],
                diseaseSubArr: [],
                typeArr: [],
                StartDate: undefined,  // //开始日期
                EndDate: moment(date).format(dayFormat),  // //结束日期
                advicelogMessage: "",
                advicelogVisible: false,
                requid: this.props.requireds,
                requireds: true,
                isTransitionStart: true,
                doctor: "",
                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.onConsPsy(this)
            const { userData } = this.state
            // this.handleGetData()
            let data = {}
            data = {
                params: [{
                    hospID: userData && userData.hospID || "",
                }],
            }
            $http.post('urlS', this, {
                code: '03070033',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            diseaseArr: res.result.data
                        })
                    }
                }
            })
        }
        //日期
        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 })
            }
        }
        findData = () => {

        }
        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,
                        // [name + "Score"]: e.target.score,
                    });
                }
            }
        };
        del = () => {
            const { userData } = this.state
            let data = {}
            data = {
                params: [{
                    userID: userData && userData.userID || "",
                    healthRecordID: this.state.doctorID,
                    assessCatCode: "a21"
                }],
            }
            $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.props.getPress()
                        this.setState({
                            delStatus: true
                        })
                    }
                }
            })
        }
        clear = (d) => {
            this.props.form.resetFields();
            this.setState({
                oneValue: "",
                oneScore: 0,
                twoValue: "",
                twoScore: 0,
                threeValue: "",
                threeScore: 0,
                fourValue: "",
                fourScore: 0,
                collectTime: ""
                // doctorID:""
            })
            this.props.form.resetFields();
            if (d) {
                this.setState({
                    delStatus: true,
                    doctorID: ""
                })
            }
        }
        //获取
        handleGetData = (id) => {
            const { assessData } = this.state
            let data = {}
            data = {
                params: [
                    {
                        healthRecordID: id,
                        assessmentCatCode: "a21"
                    }
                ],
            }
            $http.post('urlS', this, {
                code: '03070037',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.props.form.resetFields();
                        if (res.result.doctorID) {
                            this.setState({
                                healthDoctorID: res.result.doctorID
                            })
                        }
                        if (res.result.doctorID && res.result.father) {
                            this.setState({
                                collectTime: res.result.father[0].collectTime,
                            })
                            this.props.form.setFieldsValue({ diseaseID: res.result.father[0].collectUserID, collectDate: moment(res.result.father[0].collectDate), });
                        } else {
                            //清空
                            this.clear()
                            this.setState({
                                delStatus: true
                            })
                        }
                        if (res.result.father[0].ID) {
                            this.setState({
                                delStatus: false
                            })
                        }
                        if (res.result.father[0].children) {
                            let data = res.result.father[0].children
                            this.setState({
                                oneValue: data.a2101,
                                oneScore: Number(data.a2101note),
                                twoValue: data.a2102,
                                twoScore: Number(data.a2102note),
                                threeValue: data.a2103,
                                threeScore: Number(data.a2103note),
                                fourValue: data.a2104,
                                fourScore: Number(data.a2104note),
                            })
                        }
                    } else {

                    }
                }
            })
        }
        setValue = (id) => {
            // console.log("id---------",id)
            this.setState({
                doctorID: id
            }, () => {
                this.handleGetData(id)
            })
        }
        //保存
        handleSave = () => {
            const { userData, assessData } = this.state
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    let data = {}
                    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: "a21",
                                        collectDate: values.collectDate ? moment(values.collectDate).format('YYYY-MM-DD') : moment(moment()).format('YYYY-MM-DD'),
                                        collectTime: this.state.collectTime || moment(moment()).format('HH:mm:ss'),
                                        collectUserID: values.diseaseID || "",
                                        assessItem: [
                                            {
                                                assessItemCode: "a2101",
                                                assessItemValue: this.state.oneValue,
                                                assessNote: this.state.oneScore,
                                            },
                                            {
                                                assessItemCode: "a2102",
                                                assessItemValue: this.state.twoValue,
                                                assessNote: this.state.twoScore,
                                            }, {
                                                assessItemCode: "a2103",
                                                assessItemValue: this.state.threeValue,
                                                assessNote: this.state.threeScore,
                                            }, {
                                                assessItemCode: "a2104",
                                                assessItemValue: this.state.fourValue,
                                                assessNote: this.state.fourScore,
                                            },
                                        ]
                                    }
                                ]
                            }
                        ],
                    }
                    $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.updateList()
                                this.props.getPress()
                                message.success("保存成功")
                                this.handleGetData(res.result.healthRecordID)
                            } else {

                            }
                        }
                    })
                }
            })

        }
        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()
                    });
                }
            }

        }
        render() {
            const { getFieldDecorator } = this.props.form;
            const { collArr, diseaseArr, diseaseSubArr, assessData, typeArr, statusArr, columns, widthTotal } = this.state;
            var date = new Date();
            let searchColConfig = {
                xs: { span: 24 },
                sm: { span: 12 },
                md: { span: 10 },
                lg: { span: this.props && this.props.modal ? 8 : 6 }
            }
            const mesIcon = <Icon type="exclamation-circle" />
            //疾病
            let diseaseOp = []
            diseaseArr && diseaseArr.map(item => {
                diseaseOp.push(<Option key={item.id} title={item.descripts} onClick={() => window.sessionStorage.setItem("noSave", true)} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.id)}>{item.descripts}</Option>)
            })
            //疾病症状
            let diseaseSubOp = []
            diseaseSubArr && diseaseSubArr.map(item => {
                diseaseSubOp.push(<Option className="DoctorAdviceFind-optionLeft" key={item.admID} role={item.admStr + '^' + item.admStr} title={item.admStr} value={String(item.admID)}>{item.thisTime == "Y" ? <span style={{ color: "#1999db", marginRight: "4px" }}>本次</span> : ""}{item.admStr}</Option>)
            })
            // console.log("this.props.required",this.props.requireds,"this.state.requid",this.state.requid)
            return (
                <div className="assess-dom psychological-dom">
                    <Row style={{ textAlign: "center" }}>
                        <h2>心理评估</h2>
                    </Row>
                    <Row style={{ color: "#bfbfbf", marginBottom: "12px" }}>
                        请根据您当前的心理状况回答以下问题
                    </Row>
                    <Row style={{ position: "relative" }}>
                        <Form>
                            <Col span={4} 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={{ marginLeft: "16px" }}
                            >
                                <FormItem {...formItemLayoutPeo} 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"
                                            allowClear
                                        >
                                            {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 onClick={this.handleSave} type="primary">{this.state.doctorID && this.state.doctorID ? "更新" : "保存"}</Button> */}
                                            <Button style={{ margin: "0 18px 0 18px" }} onClick={this.handleSave} type="primary">保存</Button>
                                        </div>
                                    )}
                                </FormItem>
                            </Col>
                        </Form>
                    </Row>
                    <p style={{ background: "#f5f4f4", height: "8px", margin: "0" }}>
                    </p>
                    <div className="conent" onClick={(e) => this.handleRadio(e)}>
                        <Row style={{ display: "flex", paddingBottom: "0" }}>
                            <Col span={8}>
                                <p>
                                    1、您是否对生活基本满意？
                                </p>
                            </Col>
                            <Col span={12}>
                                <Radio.Group onChange={(e) => this.handleChange(e, "one")} value={this.state.oneValue}>
                                    <Radio value={"a210101"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a19001"}>是</Radio>
                                    <Radio value={"a210102"} id={this.state.oneValue + "^" + "oneValue" + "^" + "oneScore" + "^" + "a10101"}>不是</Radio>
                                </Radio.Group>
                            </Col>

                        </Row>
                        <Row style={{ display: "flex", paddingBottom: "0" }}>
                            <Col span={8}>
                                <p>
                                    2、您是否觉得自己生活是空虚的？
                                </p></Col>
                            <Col span={12}>
                                <Radio.Group onChange={(e) => this.handleChange(e, "two")} value={this.state.twoValue}>
                                    <Radio value={"a210201"} id={this.state.twoValue + "^" + "twoValue" + "^" + "twoScore" + "^" + "a19201"}>是</Radio>
                                    <Radio value={"a210202"} id={this.state.twoValue + "^" + "twoValue" + "^" + "twoScore" + "^" + "a1201"}>不是</Radio>
                                </Radio.Group></Col>
                        </Row>
                        <Row style={{ display: "flex", paddingBottom: "0" }}>
                            <Col span={8}>
                                <p>
                                    3、您是否担心自己会发生不幸？
                                </p>
                            </Col>
                            <Col span={12}>
                                <Radio.Group onChange={(e) => this.handleChange(e, "three")} value={this.state.threeValue}>
                                    <Radio value={"a210301"} id={this.state.threeValue + "^" + "threeValue" + "^" + "threeScore" + "^" + "a19001"}>是</Radio>
                                    <Radio value={"a210302"} id={this.state.threeValue + "^" + "threeValue" + "^" + "threeScore" + "^" + "a190201"}>不是</Radio>
                                </Radio.Group>
                            </Col>

                        </Row>
                        <Row style={{ display: "flex", paddingBottom: "0" }}>
                            <Col span={8}>
                                <p>
                                    4、您是否大多数时候都感到幸福？
                                </p>
                            </Col>
                            <Col span={12}>
                                <Radio.Group onChange={(e) => this.handleChange(e, "four")} value={this.state.fourValue}>
                                    <Radio value={"a210401"} id={this.state.fourValue + "^" + "fourValue" + "^" + "fourScore" + "^" + "a0201"}>是</Radio>
                                    <Radio value={"a210402"} id={this.state.fourValue + "^" + "fourValue" + "^" + "fourScore" + "^" + "a190201"}>不是</Radio>
                                </Radio.Group>
                            </Col>
                        </Row>
                    </div>
                </div>
            );
        }
    })
export default AssessmentPsychological
