/**
 * 出院
 */

import React, { Component } from 'react';
import { Form, Select, Modal, Input, Table, Card, Col, Row, TimePicker, DatePicker, message } from 'antd';
import { Util, dateFormat, timeFormat, dayFormat, List } from 'tools/index';
import { $http } from 'containers/config/https';
import PatientInfo from 'pages/nurse/Patient/PatientInfo';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
var patientData = {}
class ShowDischargeModal extends Component {

    constructor(props) {
        super(props);
        var showFlag = true
        patientData = JSON.parse(sessionStorage.getItem('patientData'));
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            total: 0,
            page: 1,
            pageSize: 10,
            okText: "医疗结算",
            disType: "1", // disType 1 医疗结算 2 撤销医疗结算 3 护士办理出院 4 护士撤销出院
            dataSource: [],
            patientData: patientData,
            userData: userData,
            visible: showFlag ? this.props.isShow : false,
            formatDateType: true,
            formatTimeType: true,
            openadmDocChargeDate: false,
            openadmDocChargeTime: false,
            openpatDeceasedDate: false,
            openpatDeceasedTime: false,
            openadmNurChargeDate: false,
            openadmNurChargeTime: false,
        }
    }

    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {

            this.showFlag = true

        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }



    componentDidMount() {
        this.getPatientInfo()
        this.getDisCondition()
    }

    getDisCondition() {
        let data = {
            params: [{
                typeCode: "recall"
            }]
        }
        $http.post('urlDeault', this, {
            code: "04050012",
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    this.setState({
                        disCondition: res.result.disCondition,
                        recallReason: res.result.recallReason,
                    }, () => {
                        this.getNeedCareCondition();
                    });
                }
            }
        })
    }

    /**  
    *  获取患者基本信息
    */
    getPatientInfo(admID) {
        let data = {
            params: [{
                admID:patientData.admID,
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04020007",
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    let okText = "确定", disType = "1";
                    let patientInfo = res.result;
                    let admDocChargeDate = patientInfo.admInfo.admDocChargeDate, admDocChargeTime = patientInfo.admInfo.admDocChargeTime;
                    let admNurChargeDate = patientInfo.admInfo.admNurChargeDate, admNurChargeTime = patientInfo.admInfo.admNurChargeTime;
                    okText = "医疗结算"
                    if (patientInfo.admInfo.admDocChargeDate !== "") {
                        okText = "撤销医疗结算", disType = "2"
                    }
                    if (patientInfo.admInfo.admNurChargeDate !== "") {
                        okText = "出院召回", disType = "4"
                    }
                    let patDeceased = patientInfo.basicInfo.patDeceased;
                    this.setState({
                        patientInfo: patientInfo,
                        selCondition: patientInfo.admInfo.admDisConditionID,
                        dieFlag: patDeceased,
                        admDocChargeDate: admDocChargeDate,
                        admDocChargeTime: admDocChargeTime,
                        admNurChargeDate: admNurChargeDate,
                        admNurChargeTime: admNurChargeTime,
                        okText: okText,
                        disType: disType,
                        patDeceasedDate: patientInfo.basicInfo.patDeceasedDate,
                        patDeceasedTime: patientInfo.basicInfo.patDeceasedTime,
                        admDocChargeDesc: patientInfo.admInfo.admDocChargeDesc,
                        admNurChargeDesc: patientInfo.admInfo.admNurChargeDesc,
                    });
                }
            }
        })

    }

    getNeedCareCondition() {
        let data = {
            params: [{
                power: "discharge",
                admID: patientData.admID,
                deptType: "N",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04050005",
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    this.setState({
                        needCareCondition: res.result.needCareAry,
                    });
                }
            }
        })
    }

    closeModal() {
        let { onHide } = this.props;
        //onHide && onHide();
        this.showFlag = false
        this.setState({
            visible: false
        })
        this.cleanInput();
    }

    //清空输入框
    cleanInput() {
        this.setState({
            disCondition: [],
            recallReason: [],
            needCareCondition: [],
            selCondition: "",
            dieFlag: "N",
            admDocChargeDate: "",
            admDocChargeTime: "",
            admNurChargeDate: "",
            admNurChargeTime: "",
            patDeceasedDate: "",
            patDeceasedTime: "",
            patientInfo: "",
            admDocChargeDesc: "",
            admNurChargeDesc: "",
        })
    }
    //日期面板打开/关闭
    handleOnOpenChangeDate = (code, status) => {
        if (status) {
            this.setState({
                formatDateType: false,
                ['open' + code]: true,
            })
        } else {
            this.setState({
                formatDateType: true,
                ['open' + code]: false,
            })
        }
    }
    handleOnOpenChangeTime = (code, status) => {
        if (status) {
            this.setState({
                formatTimeType: false,
                ['open' + code]: true,
            })
        } else {
            this.setState({
                formatTimeType: true,
                ['open' + code]: false,
            })
        }
    }
    //时间框回车
    timeBlur = (e, code) => {
        var e = window.event || e;
        if (e.keyCode == 13) {
            this.setState({
                ['open' + code]: false,
                formatTimeType: true,
            })
        }
    }
    //提交
    onSubmit() {
        let code = "04050002";
        let paramObj = {};
        if (this.state.dieFlag === "Y") {
            paramObj.patDeceasedDate = moment(this.state.patDeceasedDate).format("YYYY-MM-DD");
            paramObj.patDeceasedTime = moment(this.state.patDeceasedTime).isValid() ? moment(this.state.patDeceasedTime).format("HH:mm:ss") : this.state.patDeceasedTime;
        }
        if (this.state.dieFlag === "Y") {
            paramObj.patDeceasedDate = moment(this.state.patDeceasedDate).format("YYYY-MM-DD");
            paramObj.patDeceasedTime = moment(this.state.patDeceasedTime).isValid() ? moment(this.state.patDeceasedTime).format("HH:mm:ss") : this.state.patDeceasedTime;
        }
        if (this.state.disType !== "2") {

            paramObj.admDocChargeDate = moment(this.state.admDocChargeDate).format("YYYY-MM-DD");
            paramObj.admDocChargeTime = (moment(this.state.admDocChargeTime)).isValid() ? moment(this.state.admDocChargeTime).format("HH:mm:ss") : this.state.admDocChargeTime;
            paramObj.disConditionID = this.state.selCondition;
        }
        else {
            paramObj.admDocChargeDate = "";
            paramObj.admDocChargeTime = "";
            paramObj.disConditionID = "";
        }

        paramObj.admID = this.state.patientData.admID;
        paramObj.userID = this.state.userData.userID;
        if ((this.state.disType === "2") || (this.state.disType === "4")) {
            paramObj.cancelDis = this.state.disType;
        }
        else {
            if (this.state.selCondition === "") {
                message.error('请选择出院原因!');
                return;
            }
        }
        if (Util.isEmpty(this.state.selCondition)) {
            message.error('请选择出院原因!');
            return;
        }

        let data = { params: [] };
        data.params.push(paramObj);

        $http.post('urlDeault', this, {
            code: code,
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    message.success(res.errorMessage);
                    this.closeModal()
                    var { handleEndOperation } = this.props;
                    handleEndOperation && handleEndOperation()
                }
            }
        })
    }

    onDateTimeChange(name, data, e) {
        this.setState({
            [name]: e
        })
    }

    onConditionChange(name, e, options) {
        this.setState({
            [name]: e,
            dieFlag: options.props.dieFlag
        })
    }

    render() {
        var needCareConditionOption = []
        this.state.needCareCondition && this.state.needCareCondition.map((item, index) => {
            needCareConditionOption.push(<div key={index} value={item.abnorDesc} style={{ fontSize: '16px' }}>
                {item.abnorDesc}医嘱<span style={{ color: '#1999db' }}>{item.number}</span>条</div>)
        })

        var disConditionOption = []
        this.state.disCondition && this.state.disCondition.map((item, index) => {
            disConditionOption.push(<Option key={index} value={item.id} dieFlag={item.dieFlag}>{item.descripts}</Option>)
        })

        var recallOption = []
        this.state.recallReason && this.state.recallReason.map((item, index) => {
            recallOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        return <div>
            <Modal className='discharge-modal'
                title={'出院'}
                okText={this.state.okText}
                maskClosable={false}
                visible={this.state.visible}
                onCancel={this.closeModal.bind(this)}
                onOk={this.onSubmit.bind(this)}>
                <div style={{ background: '#efefef' }}>
                    <Card>
                        <PatientInfo admID={this.state.patientData && this.state.patientData.admID} ref="PatientInfo" />
                    </Card>
                    <Card style={{ width: '30%', height: '33vh', float: 'left', overflow: 'auto' }}>
                        {needCareConditionOption}
                    </Card>
                    <Card style={{ width: '69.8%', height: '33vh', float: 'right', textAlign: 'right' }}>
                        <Row style={{ marginRight: 10 }}>
                            <Col span={12}>
                                预出院日期：<DatePicker style={{ width: '65%' }} placeholder='预出院日期'
                                    onChange={this.onDateTimeChange.bind(this, "admDocChargeDate")}
                                    value={Util.isEmpty(this.state.admDocChargeDate) ? '' : moment(this.state.admDocChargeDate, dayFormat)}
                                    format={this.state.formatDateType ? 'YYYY-MM-DD' : 'YYYYMMDD'}
                                    onOpenChange={(status) => this.handleOnOpenChangeDate('admDocChargeDate', status)}
                                    open={this.state.openadmDocChargeDate}
                                />
                            </Col>
                            <Col span={12}>
                                预出院时间：<TimePicker style={{ width: '65%' }} placeholder='预出院时间'
                                    onChange={this.onDateTimeChange.bind(this, "admDocChargeTime")}
                                    value={Util.isEmpty(this.state.admDocChargeTime) ? '' : moment(this.state.admDocChargeTime, 'HH:mm')}
                                    format={this.state.formatTimeType ? 'HH:mm' : 'HHmm'}
                                    onOpenChange={(status) => this.handleOnOpenChangeTime('admDocChargeTime', status)}
                                    onKeyDown={(e) => this.timeBlur(e, 'admDocChargeTime')}
                                    open={this.state.openadmDocChargeTime}
                                />
                            </Col>
                        </Row>
                        <Row style={{ marginTop: 10, marginRight: 10 }}>
                            <Col span={12}>
                                操作医生：<Input style={{ width: '65%' }} placeholder='操作医生'
                                    value={Util.isEmpty(this.state.admDocChargeDesc) ? this.state.userData.userName : this.state.admDocChargeDesc}
                                    disabled={true} />
                            </Col>
                            <Col span={12}>
                                出院条件：<Select style={{ width: '65%' }} placeholder='出院条件'
                                    onChange={this.onConditionChange.bind(this, 'selCondition')}
                                    value={Util.isEmpty(this.state.selCondition) ? undefined : this.state.selCondition}>
                                    {disConditionOption}
                                </Select>
                            </Col>
                        </Row>

                        {this.state.dieFlag === "Y" ? <Row style={{ marginTop: 10, marginRight: 10 }}>
                            <Col span={12}>
                                死亡日期：<DatePicker style={{ width: '65%' }} placeholder='死亡日期'
                                    onChange={this.onDateTimeChange.bind(this, "patDeceasedDate")}
                                    value={Util.isEmpty(this.state.patDeceasedDate) ? '' : moment(this.state.patDeceasedDate, dayFormat)}
                                    format={this.state.formatDateType ? 'YYYY-MM-DD' : 'YYYYMMDD'}
                                    onOpenChange={(status) => this.handleOnOpenChangeDate('patDeceasedDate', status)}
                                    open={this.state.openpatDeceasedDate}
                                />
                            </Col>
                            <Col span={12}>
                                死亡时间：<TimePicker style={{ width: '65%' }} placeholder='死亡时间'
                                    onChange={this.onDateTimeChange.bind(this, "patDeceasedTime")}
                                    value={Util.isEmpty(this.state.patDeceasedTime) ? null : moment(this.state.patDeceasedTime, 'HH:mm')}
                                    format={this.state.formatTimeType ? 'HH:mm' : 'HHmm'}
                                    onOpenChange={(status) => this.handleOnOpenChangeTime('patDeceasedTime', status)}
                                    onKeyDown={(e) => this.timeBlur(e, 'patDeceasedTime')}
                                    open={this.state.openpatDeceasedTime}
                                />
                            </Col>
                        </Row> : null}

                        <Row style={{ marginTop: 10, marginRight: 10 }}>
                            <Col span={12}>
                                出院日期：<DatePicker style={{ width: '65%' }} placeholder='出院日期'
                                    onChange={this.onDateTimeChange.bind(this, "admNurChargeDate")}
                                    value={Util.isEmpty(this.state.admNurChargeDate) ? '' : moment(this.state.admNurChargeDate, dayFormat)}
                                    format={this.state.formatDateType ? 'YYYY-MM-DD' : 'YYYYMMDD'}
                                    onOpenChange={(status) => this.handleOnOpenChangeDate('admNurChargeDate', status)}
                                    open={this.state.openadmNurChargeDate} 
                                />
                            </Col>
                            <Col span={12}>
                                出院时间：<TimePicker style={{ width: '65%' }} placeholder='出院时间'
                                    onChange={this.onDateTimeChange.bind(this, "admNurChargeTime")}
                                    value={Util.isEmpty(this.state.admNurChargeTime) ? null : moment(this.state.admNurChargeTime, 'HH:mm')}
                                    format={this.state.formatTimeType ? 'HH:mm' : 'HHmm'}
                                    onOpenChange={(status) => this.handleOnOpenChangeTime('patDeceasedTime', status)}
                                    onKeyDown={(e) => this.timeBlur(e, 'patDeceasedTime')}
                                    open={this.state.openpatDeceasedTime}
                                />
                            </Col>
                        </Row>
                        <Row style={{ marginTop: 10, marginRight: 10 }}>
                            <Col span={12}>
                                操作护士：<Input style={{ width: '65%' }} placeholder='操作护士'
                                    value={(!Util.isEmpty(this.state.admNurChargeDesc) && Util.isEmpty(this.state.admNurChargeDesc)) ?
                                        this.state.userData.userName : this.state.admNurChargeDesc}
                                    disabled={true} />
                            </Col>
                            <Col span={12}>
                                召回原因：<Select style={{ width: '65%' }} placeholder='召回原因'
                                    onChange={Util.handleSelectChange.bind(this, 'recallID')}
                                    disabled={this.state.disType != "4"}
                                    value={this.state.recallID}>{recallOption}</Select>
                            </Col>
                        </Row>
                    </Card>
                </div>
            </Modal></div >
    }
}

export default Form.create()(ShowDischargeModal);