/**
 * 生命体征填写(单人)
 */

import React from 'react';
import PatientList from '../Patient/PatientList';
import PatientInfo from '../Patient/PatientInfo';
import {
    Row, Col, Divider, Button, DatePicker, message, Table, Input, Select, Switch, Tag, Icon
} from 'antd';
import { Util } from 'tools/index';
import { temperature } from 'tools/index';
import { $http } from '../../../containers/config/https';
import store from '../../../store';
import Moment from 'moment';
// import fetchJsonp from 'fetch-jsonp';
import './CSS/VitalSigns.less';
import ShowComponentModal from 'pages/workstation/component/ShowComponentModal';

// 组件const
const { Option } = Select;
class VitalSignsSingle extends React.Component {
    constructor(props) {
        super(props);
        var patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
        this.state = {
            patient: patientData.admID,
            date: "",
            column: [],
            dataSource: [],
            clickCol: "",
            saveData: {},
            errorList: [],
            toDay: "",
            needFlag: false,
            patientData: patientData,
            iconType: "double-left",
            leftspan: 5,
            rightspan: 19,
            isShowComponentModal: false,
            componentModalData: {},
        }

    }
    componentDidMount() {
        let leftList = document.querySelectorAll('.vitalHeight  .ant-table-body');
        if (leftList.length > 0) {
            leftList[0].style.height = store.getState().tableHeight.y + 75 + 'px';
        }
        message.config({ top: 400, duration: 3 });
        this.handleSearch();
    }

    updateState = (patientObj) => {
        if (patientObj && 'selectPatient' in patientObj) {
            const selectPatient = patientObj?.selectPatient || {};
            let patientData = {
                patID: selectPatient?.patID || '',
                admID: selectPatient?.admID || '',
            };
            React.$setSessionData('patientData', patientData);
        }
        if (patientObj.iconType) {
            this.setState(patientObj);
        }
        if (patientObj.patient) {
            let admId = patientObj.patient;
            if (admId.length === 0) return
            this.setState({
                patient: admId[0],
            }, () => {
                this.handleSearch();
            });
        }
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    // 获取患者生命体征数据
    handleSearch = () => {
        if ((this.state.patient == "") || (this.state.patient === undefined)) {
            return;
        }
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            "params": [{
                hospID: user.hospID,    //医院ID
                admID: this.state.patient,
                date: this.state.date,
                status: "Y",
                flag: this.state.needFlag ? "Y" : "N",
            }]
        };
        $http.post('urlADS', this, {
            code: "04040008",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let toDay = this.state.toDay;
                    if (toDay === "") {
                        toDay = res.result.date
                    }
                    this.setState({
                        column: res.result.column,
                        date: res.result.date,
                        dataSource: res.result.dataSource,
                        toDay: toDay,
                        clickCol: "",
                        saveData: {},
                        errorList: res.result.errorList
                    })
                }
            }
        });
    }

    ///保存数据
    handleSave = () => {
        let saveData = this.state.saveData;
        if (saveData.length === 0) {
            message.warn("无需要保存的数据!");
            return;
        }
        if (this.state.patient === '') {
            message.error('请选择患者');
            return;
        };
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            "params": [{
                dataList: this.state.saveData,
                hospID: user.hospID,    //医院ID
                userID: user.userID,    //用户ID
                date: this.state.date,
                admID: this.state.patient,
            }]
        };
        $http.post('urlADS', this, {
            code: "04040009",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    if (res.errorList.length !== 0) {
                        message.error(res.errorList.join(";"));
                    } else {
                        message.success("保存成功！");
                    }
                }
                this.handleSearch();
            }
        });
    }

    /// 修改日期
    handleDateChange = (date, datetimeString) => {
        this.setState({
            date: datetimeString
        }, () => {
            this.handleSearch()
        })
    }

    ///单元格样式修改
    renderColItem = (col, colIndex, text, record, index) => {
        let obj = {
            children: text,
            props: {
                style: {}
            },
        };
        if (record.need[col.dataIndex] == '1') {
            obj.props.className = "colors NeedTest"
        }
        if (record.need[col.dataIndex] == '2') {
            obj.props.className = "colors TestedAndMeasured";
        }
        //一天录入次数少于6次的合并单元格
        if (col.dataIndex !== "itemCode") {
            if (record[col.dataIndex] !== undefined) {
                obj.props.colSpan = record.colSpan;
            } else {
                obj.props.colSpan = 0;
            }
        }
        if (((index + "." + colIndex) === this.state.clickCol) && ((col.dataIndex !== "itemCode") || (record.editable === "Y"))) {
            if ((record.itemCode === "") && (col.dataIndex !== "itemCode")) {
                message.warn("请先录入空白栏标题!");
                text = (
                    <Input
                        autoFocus="autoFocus"
                        key={'null'}
                        defaultValue=''
                        value=''
                        disabled
                    />
                )
                obj.children = text;
                return obj;
            }
            if (col.dataIndex === "itemCode") {
                text = (
                    <Select
                        autoFocus={true}
                        allowClear={true}
                        key={index + "." + col.dataIndex}
                        style={{ width: '100%' }}
                        defaultValue={text}
                        onChange={this.onBlankItemChange.bind(this, col, record, index, colIndex)}
                    >
                        {
                            record.blankItem.map((item) => {
                                return (
                                    <Option key={item}>
                                        {item}
                                    </Option>
                                )
                            })
                        }
                    </Select>
                )
            } else {
                text = (
                    <Input
                        autoFocus="autoFocus"
                        key={index + "." + col.dataIndex}
                        style={{
                            backgroundColor: this.state.errorList[index + "." + col.dataIndex] === undefined ? "#ffffff" :
                                this.state.errorList[index + "." + col.dataIndex] === 0 ? "#ffffff" :
                                    this.state.errorList[index + "." + col.dataIndex] === 2 ? "#FAAD14" :
                                        this.state.errorList[index + "." + col.dataIndex] === 3 ? "#FAAD14" :
                                            "#f50"
                        }}
                        defaultValue={text}
                        onChange={this.onChange.bind(this, col, record, index)}
                        onBlur={this.onBlur.bind(this, col, record, index)}
                        onPressEnter={this.onPressEnter.bind(this, colIndex, index)}
                        onKeyDown={this.onKeyDownEnter.bind(this, colIndex, index)}
                    />
                )
            }
            obj.children = text;
        } else {

            obj.props.style.backgroundColor = this.state.errorList[index + "." + col.dataIndex] === undefined ? "#ffffff" :
                this.state.errorList[index + "." + col.dataIndex] === 0 ? "#ffffff" : (this.state.errorList[index + "." + col.dataIndex] === 2 ? "#faad14" : "#f50")
        }
        return obj;
    }

    //空白栏选择
    onBlankItemChange = (col, record, index, colIndex, value) => {
        // let errorList = this.state.errorList;
        if (!value) { value = ""; }
        record[col.dataIndex] = value;
        let saveData = this.state.saveData;
        let saveRecord = saveData[record.key];
        if (!saveRecord) {
            saveData[record.key] = { [col.dataIndex]: value }
        } else {
            saveData[record.key][col.dataIndex] = value;
        }
        this.forceUpdate();
    }

    //需测体征查询
    onSwitchChange = (flag) => {
        this.setState({ needFlag: flag }, () => {
            this.handleSearch();
        })
    }

    //编辑框文本变化事件
    onChange = (col, record, index, e) => {
        e.stopPropagation();
        let errorList = this.state.errorList;
        errorList[index + "." + col.dataIndex] = 0;
        let value = e.target.value;
        record[col.dataIndex] = e.target.value;
        let saveData = this.state.saveData;
        let saveRecord = saveData[record.key];
        if (!saveRecord) {
            saveData[record.key] = { [col.dataIndex]: value }
        } else {
            saveData[record.key][col.dataIndex] = value;
        }

        if (((record.normalRangeFrom !== "") || (record.normalRangeTo !== "")) && (value !== "")) {
            //非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$ 
            // var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
            let regex = /^\d+(\.\d+)?$/
            errorList[index + "." + col.dataIndex] = 0
            if (!regex.test(parseFloat(value))) {
                //message.warn("请注意：" + col.title + "数据格式不正确");
                errorList[index + "." + col.dataIndex] = 1
            } else {
                if ((record.normalRangeFrom !== "") && (parseFloat(value) < parseFloat(record.normalRangeFrom))) {
                    //message.warn("请注意：" + col.title + "值小于正常低值");
                    errorList[index + "." + col.dataIndex] = 2
                }
                if ((record.normalRangeTo !== "") && (parseFloat(value) > parseFloat(record.normalRangeTo))) {
                    // message.warn("请注意：" + col.title + "值大于正常高值");
                    errorList[index + "." + col.dataIndex] = 3
                }
            }
        }
        if (((record.errorRangeFrom !== "") || (record.errorRangeTo !== "")) && (value !== "")) {
            //非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$ 
            // var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
            let regex = /^\d+(\.\d+)?$/
            if (!regex.test(parseFloat(value))) {
                errorList[index + "." + col.dataIndex] = 1
            } else {
                if ((record.errorRangeFrom !== "") && (parseFloat(value) < parseFloat(record.errorRangeFrom))) {
                    errorList[index + "." + col.dataIndex] = 4
                }
                if ((record.errorRangeTo !== "") && (parseFloat(value) > parseFloat(record.errorRangeTo))) {
                    errorList[index + "." + col.dataIndex] = 5
                }
            }
        }
        this.forceUpdate();
    }

    ///失去焦点触发的事件
    onBlur = (col, record, index, e) => {
        e.stopPropagation();
        let value = e.target.value;
        if (((record.normalRangeFrom !== "") || (record.normalRangeTo !== "")) && (value !== "")) {
            //非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$ 
            // var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
            let regex = /^\d+(\.\d+)?$/
            if (!regex.test(parseFloat(value))) {
                message.warn("请注意：" + record.title + "数据格式不正确");
            } else {
                if ((record.normalRangeFrom !== "") && (parseFloat(value) < parseFloat(record.normalRangeFrom))) {
                    // message.warn("请注意：" + record.title + "值小于正常低值");
                }
                if ((record.normalRangeTo !== "") && (parseFloat(value) > parseFloat(record.normalRangeTo))) {
                    // message.warn("请注意：" + record.title + "值大于正常高值");
                }
            }
        }
        if (((record.errorRangeFrom !== "") || (record.errorRangeTo !== "")) && (value !== "")) {
            //非负浮点数（正浮点数 + 0）：^\d+(\.\d+)?$ 
            // var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; //正浮点数
            let regex = /^\d+(\.\d+)?$/
            if (!regex.test(parseFloat(value))) {
                // message.warn("请注意：" + record.title + "数据格式不正确");
            } else {
                if ((record.errorRangeFrom !== "") && (parseFloat(value) < parseFloat(record.errorRangeFrom))) {
                    message.warn("请注意：" + record.title + "值小于错误低值");
                }
                if ((record.errorRangeTo !== "") && (parseFloat(value) > parseFloat(record.errorRangeTo))) {
                    message.warn("请注意：" + record.title + "值大于错误高值");
                }
            }
        }
        this.setState({ clickCol: "" })
    }

    //支持上下左右回车切换
    onKeyDownEnter = (col, row, e) => {
        if (e !== "") { e.stopPropagation(); }
        // col 列
        // row 行
        if (e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40 && e.keyCode !== 13) {
            return false;
        }
        let column = this.state.column;
        let flag = true;
        let first = 1, end = column.length - 1; //第一个和最后一个可编辑的列
        for (var i = 0; i < column.length; i++) {
            if ((column[i].editable === "Y") && (first === '')) {
                first = i;
            }
            if (column[i].editable === "Y") {
                end = i;
            }
        }
        if (col === end && row === this.state.dataSource.length - 1) {
            this.setState({ clickCol: 0 + '.' + first });
            return;
        }
        switch (e.keyCode) {
            case 37://左 
                col--;
                break;
            case 38://上
                row--;
                break;
            case 39://右
                col++;
                break;
            case 40://下
                row++;
                // flag = false;
                // this.onPressEnter(col, row, e);
                break;
            case 13:
                flag = false;
                this.onPressEnter(col, row, e);
                break;
        }
        if (row > this.state.dataSource.length - 1) {
            return false;
        }
        if (col > end) {
            col = first;
            row = row + 1;
        }
        if (col < first) {
            col = end;
            row = row - 1;
        }
        let record = this.state.dataSource[row];
        if (record[column[col].dataIndex] === undefined) {
            let j = col;
            col = '';
            if ((e.keyCode == "39") || (e.keyCode == "40")) {
                for (; j < column.length; j++) {
                    if (record[column[j].dataIndex] !== undefined) {
                        col = j;
                    }
                    if (col !== '') break;
                }
            }
            if ((e.keyCode == "37") || (e.keyCode == "38")) {
                for (; j > 0; j--) {
                    if (record[column[j].dataIndex] !== undefined) {
                        col = j;
                    }
                    if (col !== '') break;
                }
            }
        }
        //本行未找到有效編輯行時，遍历下一行数据，当下一行超过当前table时，下一行为起始行
        let j = 1;
        if (col == '') {

            if ((e.keyCode == "39") || (e.keyCode == "40")) {
                row = row + 1;
                if (row > this.state.dataSource.length) {
                    row = 0;
                }
                record = this.state.dataSource[row];
                col = '';
                for (; j < column.length; j++) {
                    if (record[column[j].dataIndex] !== undefined) {
                        col = j;
                    }
                    if (col !== '') break;
                }
            }
            if ((e.keyCode == "37") || (e.keyCode == "38")) {
                row = row - 1;
                if (row < 0) {
                    row = this.state.dataSource.length;
                }
                record = this.state.dataSource[row];
                col = '';
                j = end;
                for (; j > 0; j--) {
                    if (record[column[j].dataIndex] !== undefined) {
                        col = j;
                    }
                    if (col !== '') break;
                }
            }
        }
        if (flag) {
            this.setState({ clickCol: row + '.' + col });
        }
    }

    ///编辑框回车事件
    onPressEnter = (colIndex, index, e) => {
        if (e !== "") { e.stopPropagation(); }
        let column = this.state.column;
        let clickCol = this.state.clickCol;
        let record = this.state.dataSource[index];
        let first = 1;
        let next = '';
        let i = colIndex + 1;
        for (; i < column.length; i++) {
            if (record[column[i].dataIndex] !== undefined) {
                next = i;
            }
            if (next !== '') break;
        }

        if ((next === column.length) || (next === '')) {
            next = first;
            index = index + 1;
        }
        if (index >= this.state.dataSource.length) {
            index = 0;
        }
        record = this.state.dataSource[index];
        if (record[column[next].dataIndex] === undefined) {
            next = '';
            let j = first + 1;
            for (; j < column.length; j++) {
                if (record[column[j].dataIndex] !== undefined) {
                    next = j;
                }
                if (next !== '') break;
            }
        }

        if (index < this.state.dataSource.length) {
            clickCol = index + "." + next;
        } else {
            clickCol = "0." + first;
        }
        this.setState({ clickCol: clickCol })
    }

    ///点击单元格
    onCell = (colIndex, record, index) => {
        return {
            onClick: (event) => {
                this.setState({
                    clickCol: index + "." + colIndex,
                })
            },
        }
    }

    ///前一天点击事件
    onPreDay = (e) => {
        let lateDay = Moment(this.state.date).add(-1, 'day').format('YYYY-MM-DD');
        this.setState({ date: lateDay }, () => {
            this.handleSearch();
        })
    }

    ///后一天点击事件
    onNextDay = () => {
        // let today = Moment(this.state.toDay)
        let lateDay = Moment(this.state.date).add(+1, 'day').format('YYYY-MM-DD');
        /*
        if (Moment(lateDay).valueOf() > today.valueOf()) {
            message.warn("日期不能超过当天!");
            return;
        }
        */
        this.setState({ date: lateDay }, () => {
            this.handleSearch();
        })
    }

    disabledDate = dateValue => {
        if (this.state.toDay === "") {
            return false;
        }
        let today = Moment(this.state.toDay)
        return dateValue.valueOf() > today.valueOf();
    };

    //预览体温单
    previewTemperature = () => {
        temperature.previewTemperature(this.state.patient);
        return;
        /*
        if (this.state.clickRow == '') {
            message.warn("请先选择患者");
            return;
        }
        let dllInput = {};
        dllInput.exeName = "XYSTemperature.exe";
        dllInput.path = "C:\\ProgramData\\XYS\\XYSService\\plugins\\Temperature\\";
        let parameter = "";
        let sessionObj = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        Object.keys(sessionObj).forEach(function (key) {
            parameter = parameter + key + ":" + sessionObj[key] + ",";

        });
        parameter = parameter + "wardID:" + sessionObj.locID;
        parameter = parameter + "," + "admID:" + this.state.patient;
        dllInput.parameter = parameter;

        let data = 'input={"inputDir":"Temperature/OpenExe.dll","clsName":"OpenExe.ExeObj","funcName":"CreateProcess","dllInput":' + JSON.stringify(dllInput) + '}'
        let that = this
        fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
            jsonpCallback: 'JsonCallback',
            timeout: 30000,
        })
            .then(function (response) {
                return response.json()
            }).then(function (json) {
            }).catch(function (ex) {
            })
        */
    }

    // 历史查询
    handleHistoricalQuery = () => {
        this.setState({
            isShowComponentModal: true,
            componentModalData: {
                ENDesc: '',
                title: '历史查询',
                component: 'pages/workstation/component/ConsultationHistory.jsx',
            }
        })
    }

    //隐藏弹出框
    hideModal = (name) => {
        this.setState({
            [name]: false
        });
    }

    render() {
        const { patient, isShowComponentModal } = this.state;
        const columns = this.state.column.map((col, colIndex) => {
            return {
                ...col,
                render: this.renderColItem.bind(this, col, colIndex),
                onCell: this.onCell.bind(this, colIndex),
            };
        });
        return (
            <div style={{ width: '100%', height: '100%' }} className="VitalSignsSingle colors">
                <Col className={this.state.iconType == "double-left" ? "" : "visibleIcon"} span={this.state.leftspan}
                    style={{ border: this.state.iconType == "double-left" ? "1px solid #cccccc" : "0px", height: "100%", overflowY: 'hidden', background: '#ffffff', boxSizing: 'border-box' }}>
                    <PatientList updateState={this.updateState} iconType={this.state.iconType} type="radio" />
                </Col>
                <Col span={this.state.rightspan} style={{ height: '100%' }} >
                    <Row style={{ width: '100%', height: '36px', textAlign: 'left', lineHeight: '36px', textAlign: 'left' }}>
                        <PatientInfo admID={!Util.isEmpty(this.state.patient) ? this.state.patient : ''} />
                    </Row>
                    <Divider />
                    <Row style={{ paddingBottom: '3px', margin: '5px 24px 0', height: '40px', lineHeight: '40px', background: '#F5F4F4', border: '1px solid rgba(225,225,225)', borderBottom: 0 }}>
                        <Icon type="left" disabled={this.state.date === "" ? true : false} onClick={this.onPreDay} style={{ marginLeft: '24px', color: '#1890FF' }} /><span onClick={this.onPreDay} style={{ color: '#1890FF', marginLeft: '10px', marginTop: '3px' }}>前一天</span>
                        {/* <Button disabled={this.state.date === "" ? true : false} style={{ margin: '0 15px 0 0' }} type="primary" onClick={this.onPreDay}>前一天</Button> */}
                        <DatePicker disabledDate={this.disabledDate} onChange={this.handleDateChange} style={{ marginLeft: '15px' }} value={this.state.date === "" ? null : Moment(this.state.date, 'YYYY-MM-DD')} />
                        <span style={{ color: '#1890FF', marginLeft: '10px', marginTop: '3px' }} onClick={this.onNextDay}>后一天</span>
                        <Icon type="right" disabled={this.state.date === "" ? true : false} onClick={this.onNextDay} style={{ marginLeft: '10px', color: '#1890FF' }} />
                        {/* <Button disabled={this.state.date === "" ? true : false} style={{ margin: '0 15px 0 0' }} type="primary" onClick={this.onNextDay}>后一天</Button> */}
                        &nbsp;&nbsp;&nbsp; 需测体征:  <Switch style={{ marginLeft: '15px' }} checked={this.state.needFlag} onChange={this.onSwitchChange} />
                        <Button type="primary" style={{ marginLeft: '15px' }} onClick={this.handleSave}>保存</Button>
                        <Button onClick={this.previewTemperature} type="primary" style={{ color: '#fff', margin: '0px 15px' }}>预览</Button>
                        <Button ghost type="primary" disabled={!patient} onClick={this.handleHistoricalQuery}>历史查询</Button>
                        <div className="navtext" style={{ float: 'Right', marginRight: '12px' }}>
                            <span className="nav-text"></span>&nbsp;&nbsp;错误数据
                            <span className="navtep"></span>&nbsp;&nbsp;非正常数据
                            <span className="navtemp"></span>&nbsp;&nbsp;需测未测
                            <span className="navbar"></span>&nbsp;&nbsp;需测已测

                        </div>

                    </Row>
                    <Row style={{ padding: '0 24px' }} className="vitalSingTable">
                        <Col>
                            <Table
                                columns={columns}
                                scroll={{ x: 900, y: store.getState().tableHeight.y + 90 + 'px' }}
                                style={{ height: (store.getState().tableHeight.y + 136) }}
                                className='vitalHeight'
                                dataSource={this.state.dataSource}
                                pagination={false}
                                bordered
                            >
                            </Table>
                        </Col>
                    </Row>
                </Col>
                <ShowComponentModal
                    isShow={isShowComponentModal}
                    dataSource={this.state.componentModalData}
                    onHide={() => this.hideModal('isShowComponentModal')}
                />
            </div>
        )
    }
}

export default VitalSignsSingle;