/**
 * 生命体征明细
 */
import React from 'react'
import PatientList from '../Patient/PatientList';
import PatientInfo from '../Patient/PatientInfo';
import {
    Row, Col, Divider, Button, DatePicker, message, Table, Input, Select, Tag, Switch
} from 'antd';
import { $http } from '../../../containers/config/https';
import store from '../../../store';
import Moment from 'moment';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import fetchJsonp from 'fetch-jsonp';
import { temperature } from 'tools/index';

import './CSS/VitalSigns.less';
class VitalSignsDetailComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            patient: [],
            stDate: "",
            endDate: "",
            column: [],
            dataSource: [],
            clickCol: "",
            saveData: {},
            errorList: [],
            toDay: "",
            total: 0,
            page: 1,
            pageSize: 20,
            needFlag: false,
            iconType: "double-left",
            leftspan: 5,
            rightspan: 19,
            header0ffHeight: 0,
        }
    }
    componentDidMount() {
        message.config({ top: 400, duration: 3 });
        let patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
        var {patient}=this.state;
        var {admID}=this.props;
        if (admID){
            patientData.admID=admID;
        }
        if(((patientData.admID))&&(patient.length==0)){
            patient.push(patientData.admID);
            this.setState({
                patient:patient
            },()=>{
                this.getConfigData();
            })
        }else{
            this.getConfigData();
        } 
        if(this.props.onRef){
            this.props.onRef(this);
        }
        
    }
    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }
    //更新组件状态,提供给子组件
    updateState = (state) => {
        if (state.iconType) {
            this.setState(state);
        } else {
            this.setState(state, () => {
                this.handleSearch();
            });
        }
    }
    // 获取配置数据
    getConfigData = () => {

        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            "params": [{
                hospID: user.hospID,    //医院ID
                wardID: user.locID,
                status: "Y",
                addPatCol: "3"
            }]
        };
        $http.post('urlADS', this, {
            code: "04040006",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let column = [];
                    let obj = {};
                    obj.key = "date";
                    obj.title = "日期";
                    obj.dataIndex = "date";
                    obj.width = '120px';
                    obj.align = "center";
                    column.push(obj);

                    obj = {};
                    obj.key = "time";
                    obj.title = "时间";
                    obj.dataIndex = "time";
                    obj.width = '120px';
                    obj.align = "center";
                    column.push(obj);

                    column = column.concat(res.result.config);
                    let lateDay = Moment(res.result.date).add(-2, 'day').format('YYYY-MM-DD');
                    this.setState({
                        column: column,
                        stDate: lateDay,
                        endDate: res.result.date,
                    }, () => {
                        this.handleSearch();
                    })
                }
            }
        });

    }
    // 获取患者生命体征数据
    handleSearch = () => { 
        if (this.state.patient.length === 0) {
            this.commonChild.handleLoading()
            return;
        }
        this.commonChild.setState({ loading: true });
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let { page, pageSize } = this.state;
        let data = {
            params: [{
                hospID: user.hospID,
                admID: this.state.patient[0],
                stDate: this.state.stDate,
                endDate: this.state.endDate,
                flag: this.state.needFlag ? "Y" : "N",
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        };
        $http.post('urlADS', this, {
            code: "04040011",
            data: data,
            success: function (res) {
                this.commonChild.handleLoading()
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        dataSource: res.result,
                        total: res.total,
                        saveData: {},
                    })
                }
            },
        });

    }
    ///保存数据
    handleSave = () => {
        let saveData = this.state.saveData;
        if (saveData.length === 0) {
            message.warn("无需要保存的数据!");
            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
                admID: this.state.patient[0],
            }]
        };
        $http.post('urlADS', this, {
            code: "04040012",
            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();
                }
            }
        });
    }
    ///点击单元格
    onCell = (colIndex, record, index) => {
        return {
            onClick: (event) => {
                this.setState({
                    clickCol: index + "." + colIndex,
                })
            },
        }
    }
    //编辑框文本变化事件
    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.date + "^" + record.time];
        if (!saveRecord) {
            saveData[record.date + "^" + record.time] = { [col.dataIndex]: value }
        } else {
            saveData[record.date + "^" + record.time][col.dataIndex] = value;
        }

        if (((col.normalRangeFrom !== "") || (col.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 ((col.normalRangeFrom !== "") && (parseFloat(value) < parseFloat(col.normalRangeFrom))) {
                    //message.warn("请注意：" + col.title + "值小于正常低值");
                    errorList[index + "." + col.dataIndex] = 2
                }
                if ((col.normalRangeTo !== "") && (parseFloat(value) > parseFloat(col.normalRangeTo))) {
                    // message.warn("请注意：" + col.title + "值大于正常高值");
                    errorList[index + "." + col.dataIndex] = 3
                }
            }
        }
        if (((col.errorRangeFrom !== "") || (col.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 ((col.errorRangeFrom !== "") && (parseFloat(value) < parseFloat(col.errorRangeFrom))) {
                    errorList[index + "." + col.dataIndex] = 4
                }
                if ((col.errorRangeTo !== "") && (parseFloat(value) > parseFloat(col.errorRangeTo))) {
                    errorList[index + "." + col.dataIndex] = 5
                }
            }
        }
        this.forceUpdate();
    }

    ///编辑框回车事件
    onPressEnter = (colIndex, index, e) => {
        if (e !== "") { e.stopPropagation(); }
        let column = this.state.column;
        let clickCol = this.state.clickCol;
        let first = '';
        let next = '';
        let i = 0;
        for (; i < column.length; i++) {
            if (column[i].blankItemFlag === "Y") continue;
            if ((column[i].editable === "Y") && (first === '')) {
                first = i;
            }
            if ((i > colIndex) && (column[i].editable === "Y")) {
                next = i;
            }
            if (next !== '') break;
        }

        if (next === '') {
            next = first;
            index = index + 1;
        }
        if (index >= this.state.dataSource.length) {
            index = 0;
        }
        clickCol = index + "." + next;
        this.setState({ clickCol: clickCol })
    }
    ///失去焦点触发的事件
    onBlur = (col, record, index, e) => {
        e.stopPropagation();
        let value = e.target.value;
        if (((col.normalRangeFrom !== "") || (col.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("请注意：" + col.title + "数据格式不正确");
            } else {
                if ((col.normalRangeFrom !== "") && (parseFloat(value) < parseFloat(col.normalRangeFrom))) {
                    // message.warn("请注意：" + col.title + "值小于正常低值");
                }
                if ((col.normalRangeTo !== "") && (parseFloat(value) > parseFloat(col.normalRangeTo))) {
                    // message.warn("请注意：" + col.title + "值大于正常高值");
                }
            }
        }

        if (((col.errorRangeFrom !== "") || (col.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("请注意：" + col.title + "数据格式不正确");
            } else {
                if ((col.errorRangeFrom !== "") && (parseFloat(value) < parseFloat(col.errorRangeFrom))) {
                    message.warn("请注意：" + col.title + "值小于错误低值");
                }
                if ((col.errorRangeTo !== "") && (parseFloat(value) > parseFloat(col.errorRangeTo))) {
                    message.warn("请注意：" + col.title + "值大于错误高值");
                }
            }
        }


        this.setState({ clickCol: "" })
    }
    ///单元格样式修改
    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";
        }
        if (((col.normalRangeFrom !== "") || (col.normalRangeTo !== "")) && (text !== "")) {
            if ((col.normalRangeFrom !== "") && (parseFloat(text) < parseFloat(col.normalRangeFrom))) {
                obj.props.className = "colors UnNormal";
            }
            if ((col.normalRangeTo !== "") && (parseFloat(text) > parseFloat(col.normalRangeTo))) {
                obj.props.className = "colors UnNormal";
            }

        }

        if (((col.errorRangeFrom !== "") || (col.errorRangeTo !== "")) && (text !== "")) {
            if ((col.errorRangeFrom !== "") && (parseFloat(text) < parseFloat(col.errorRangeFrom))) {
                obj.props.className = "colors ErrorValue";
            }
            if ((col.errorRangeTo !== "") && (parseFloat(text) > parseFloat(col.errorRangeTo))) {
                obj.props.className = "colors ErrorValue";
            }

        }
        if (((index + "." + colIndex) === this.state.clickCol) && (col.editable === "Y")) {
            if (col.blankItemFlag === "Y") {
                this.setState({
                    clickCol: "",
                })
                message.warn("明细界面不允许修改空白栏!");
            } else {
                text = (
                    <Input
                        autoFocus="autoFocus"
                        key={index + "." + col.dataIndex}
                        defaultValue={text}
                        onChange={this.onChange.bind(this, col, record, index)}
                        onPressEnter={this.onPressEnter.bind(this, colIndex, index)}
                        onBlur={this.onBlur.bind(this, col, record, index)}
                    />
                )
            }
        }
        obj.children = text;
        return obj;
    }
    handleStDateChange = (date, datetimeString) => {
        this.setState({
            stDate: datetimeString
        })
    }
    handleEndDateChange = (date, datetimeString) => {
        this.setState({
            endDate: datetimeString
        })
    }
    handleOnRef = (ref) => {
        this.commonChild = ref
    }
    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleSearch();
        })
    }
    //需测体征查询
    onSwitchChange = (flag) => {
        this.setState({ needFlag: flag }, () => {
            this.handleSearch();
        })
    }
    //日期禁用
    disabledDate = dateValue => {
        if (this.state.endDate === "") {
            return false;
        }
        let today = Moment(this.state.endDate)
        return dateValue.valueOf() > today.valueOf();
    };
    //预览体温单
    previewTemperature = () => {
        temperature.previewTemperature(this.state.patient);
    }
    render() {

        const columns = this.state.column.map((col, colIndex) => {
            return {
                ...col,
                render: this.renderColItem.bind(this, col, colIndex),
                onCell: this.onCell.bind(this, colIndex),
            };
        }); 
        var header0ffHeight=this.props.header0ffHeight;
        if(header0ffHeight==undefined){
            header0ffHeight=210;
        }
        // 组件所需参数
        const param = {
            // 表头配置
            columns: columns,
            // 表格数据
            data: this.state.dataSource,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            page: this.state.page, 
            // 表格的宽度
            y: store.getState().tableHeight.y + 11 -  header0ffHeight,
			height: store.getState().tableHeight.y + 126 - header0ffHeight + 'px',
            x: 900, 
            // 默认每页显示的数据
            pageSize:this.state.pageSize,
        }
        return (
            <div style={{ width: '100%', height: '100%', overflowY: 'hidden' }} className="VitalSignsSingle"> 
                  <Row style={{ margin: '12px 24px 0', height: '40px', lineHeight: '40px', background: '#F5F4F4', border: '1px solid rgba(225,225,225)', borderBottom: 0 }}>
                        &nbsp;&nbsp;&nbsp;&nbsp;  日期选择:  <DatePicker disabledDate={this.disabledDate} style={{ margin: '0px 15px 0 0' }} onChange={this.handleStDateChange} value={this.state.stDate === "" ? null : Moment(this.state.stDate, 'YYYY-MM-DD')} />
                        至:  <DatePicker disabledDate={this.disabledDate} style={{ margin: '0px 15px 0 0' }} onChange={this.handleEndDateChange} value={this.state.endDate === "" ? null : Moment(this.state.endDate, 'YYYY-MM-DD')} />
                        需测体征:  <Switch style={{ margin: '0 15px 0 0' }} checked={this.state.needFlag} onChange={this.onSwitchChange} />
                        <Button style={{ margin: '0px 15px 0 0', backgroundColor: '#FFFFFF' }} onClick={this.handleSearch}>查询</Button>
                        <Button type="primary" style={{ margin: '0px 15px 0 0' }} onClick={this.handleSave}>保存</Button>
                        <Button onClick={this.previewTemperature} type="primary" style={{ color: '#fff', margin: '0px 15px' }}>预览</Button>
                        <div className="contentnav" style={{ float: 'Right', marginTop: '-px', marginRight: '24px' }}>
                            <span className="content-nav"></span>&nbsp;&nbsp;错误数据
                                    <span className="content-tmp"></span>&nbsp;&nbsp;非正常数据
                                    <span className="content-tim"></span>&nbsp;&nbsp;需测未测
                                    <span className="content-opr"></span>&nbsp;&nbsp;需测已测

                               </div>
                    </Row>
                    <Row style={{ margin: '0 24px'}} className="table-body-height">
                        {/* handelThis将夫组件的属性与方法给子组件访问 */}
                        <PubilcTablePagination param={param} handelThis={this} onRef={this.handleOnRef} />
                    </Row>
            </div>
        )
    }

}

export default VitalSignsDetailComponent;