/*
 * Create:      柿子
 * CreateDate:  2023/12/29
 * Describe：   单人生命体征
 * */
import React, { Component } from 'react';
import { Icon, DatePicker, Switch, Button, Table, message, Input, Select } from 'antd';
import { temperature, dayFormat } from 'tools';
import moment from 'moment';
import store from 'store';
import ShowComponentModal from 'pages/workstation/component/ShowComponentModal';

class IndividualVitalSigns extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userData: React.$getSessionData(),
      currentDate: moment().format(dayFormat),
      visible: false,
      needFlag: false,
      columns: [],
      tableData: [],
      patient: '',
      saveData: {},
    }
  };

  componentDidMount() {

  };

  // 获取列表数据
  getTableData = async () => {
    try {
      const { userData, currentDate, needFlag, patient } = this.state;
      if ((patient === '') || (patient === undefined)) {
        return;
      }
      let data = {
        params: [{
          hospID: userData?.hospID || '', // 医院ID
          admID: patient,
          date: currentDate,
          status: 'Y',
          flag: needFlag ? 'Y' : 'N',
        }]
      };
      let res = await React.$asyncPost(this, '04040008', data);
      let toDay = this.state.toDay;
      if (toDay === "") {
        toDay = res.result.date
      }
      this.setState({
        columns: res.result?.column || [],
        currentDate: res.result.date,
        tableData: res.result?.dataSource || [],
        toDay: toDay,
        clickCol: '',
        saveData: {},
        errorList: res.result?.errorList || []
      })
    } catch (error) {
      console.log(error);
    }
  };

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

  // 前一天 | 后一天
  handlePreAndNextClick = (type) => {
    const { currentDate } = this.state;
    let day = moment(currentDate.date).add(type === 'pre' ? -1 : +1, 'day').format(dayFormat);
    this.setState({ currentDate: day }, () => {
      this.getTableData();
    })
  };

  handleNeedFlagChange = (e) => {
    this.setState({ needFlag: e }, () => {
      this.getTableData();
    })
  };

  // 保存
  handleSave = async () => {
    try {
      const { userData, currentDate } = this.state;
      let saveData = this.state.saveData;
      if (saveData.length === 0) {
        message.warn("无需要保存的数据!");
        return;
      }
      if (this.state.patient === '') {
        message.error('请选择患者');
        return;
      };
      let data = {
        params: [{
          dataList: this.state.saveData,
          hospID: userData?.hospID || '', // 医院ID
          userID: userData?.userID || '', // 用户ID
          date: currentDate,
          admID: this.state.patient,
        }]
      };
      let res = await React.$asyncPost(this, '04040009', data);
      let errorList = res?.errorList || [];
      if (Array.isArray(errorList) && errorList.length > 0) {
        message.error(errorList.join(';'));
      } else {
        message.success(res?.errorMessage || '保存成功！');
      }
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  };

  // 预览
  handlePreviewTemperature = () => {
    temperature.previewTemperature(this.state.patient);
  };

  // 历史查询弹窗
  modifyVisible = (visible) => {
    this.setState({
      visible
    })
  };

  ///单元格样式修改
  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
            disabled
            value=""
            defaultValue=""
            key="null"
            autoFocus="autoFocus"
          />
        )
        obj.children = text;
        return obj;
      }
      if (col.dataIndex === 'itemCode') {
        text = (
          <Select
            autoFocus
            allowClear
            key={index + '.' + col.dataIndex}
            style={{ width: '100%' }}
            defaultValue={text}
            onChange={(e) => this.handleSelectChange(col, record, index, colIndex, e)}
          >
            {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={(e) => this.handleInputChange(col, record, index, e)}
            onBlur={(e) => this.handleInputBlur(col, record, index, e)}
            onPressEnter={(e) => this.handleInputPressEnter(colIndex, index, e)}
            onKeyDown={(e) => this.handleInputKeyDown(colIndex, index, e)}
          />
        )
      }
      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;
  };

  //空白栏选择
  handleSelectChange = (col, record, index, colIndex, value) => {
    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.setState({});
  };

  //编辑框文本变化事件
  handleInputChange = (col, record, index, e) => {
    React.$stopPropagation(e);
    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 !== '')) {
      let regex = /^\d+(\.\d+)?$/
      errorList[index + '.' + col.dataIndex] = 0
      if (!regex.test(parseFloat(value))) {
        errorList[index + '.' + col.dataIndex] = 1
      } else {
        if ((record.normalRangeFrom !== '') && (parseFloat(value) < parseFloat(record.normalRangeFrom))) {
          errorList[index + '.' + col.dataIndex] = 2
        }
        if ((record.normalRangeTo !== '') && (parseFloat(value) > parseFloat(record.normalRangeTo))) {
          errorList[index + '.' + col.dataIndex] = 3
        }
      }
    }
    if (((record.errorRangeFrom !== '') || (record.errorRangeTo !== '')) && (value !== '')) {
      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.setState({});
  };

  ///失去焦点触发的事件
  handleInputBlur = (col, record, index, e) => {
    React.$stopPropagation(e);
    let value = e.target.value;
    if (((record.normalRangeFrom !== '') || (record.normalRangeTo !== '')) && (value !== '')) {
      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 !== '')) {
      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: '' })
  };

  //支持上下左右回车切换
  handleInputKeyDown = (col, row, e) => {
    React.$stopPropagation(e);
    if (e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40 && e.keyCode !== 13) {
      return false;
    }
    const { columns } = this.state;
    let flag = true;
    let first = 1, end = columns.length - 1; // 第一个和最后一个可编辑的列
    for (var i = 0; i < columns.length; i++) {
      if ((columns[i].editable === 'Y') && (first === '')) {
        first = i;
      }
      if (columns[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++;
        break;
      case 13:
        flag = false;
        this.handleInputPressEnter(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[columns[col].dataIndex] === undefined) {
      let j = col;
      col = '';
      if ((e.keyCode == '39') || (e.keyCode == '40')) {
        for (; j < columns.length; j++) {
          if (record[columns[j].dataIndex] !== undefined) {
            col = j;
          }
          if (col !== '') break;
        }
      }
      if ((e.keyCode == '37') || (e.keyCode == '38')) {
        for (; j > 0; j--) {
          if (record[columns[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 < columns.length; j++) {
          if (record[columns[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[columns[j].dataIndex] !== undefined) {
            col = j;
          }
          if (col !== '') break;
        }
      }
    }
    if (flag) {
      this.setState({ clickCol: row + '.' + col });
    }
  };

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

    if ((next === columns.length) || (next === '')) {
      next = first;
      index = index + 1;
    }
    if (index >= this.state.dataSource.length) {
      index = 0;
    }
    record = this.state.dataSource[index];
    if (record[columns[next].dataIndex] === undefined) {
      next = '';
      let j = first + 1;
      for (; j < columns.length; j++) {
        if (record[columns[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,
        })
      },
    }
  };

  render() {
    const { currentDate, needFlag, columns, tableData, patient, visible } = this.state;
    return (
      <div className="individual-vital-signs">
        <div>
          <span onClick={() => this.handlePreAndNextClick('pre')}>
            <Icon
              type="left"
              disabled={!(currentDate)}
            />
            前一天
          </span>
          <DatePicker
            value={currentDate ? moment(currentDate, dayFormat) : null}
            disabledDate={this.handleDisabledDate}
            onChange={this.handleDateChange}
          />
          <span onClick={() => this.handlePreAndNextClick('next')}>
            <Icon
              type="right"
              disabled={!(currentDate)}
            />
            后一天
          </span>
          需测体征：<Switch checked={needFlag} onChange={this.handleNeedFlagChange} />
          <Button type="primary" onClick={this.handleSave}>保存</Button>
          <Button type="primary" onClick={this.handlePreviewTemperature}>预览</Button>
          <Button ghost type="primary" disabled={!patient} onClick={() => this.modifyVisible(true)}>历史查询</Button>
          <div style={{ float: 'right' }}>
            <span className="nav-text"></span>错误数据
            <span className="navtep"></span>非正常数据
            <span className="navtemp"></span>需测未测
            <span className="navbar"></span>需测已测
          </div>
        </div>
        <div className="vitalSingTable">
          <Table
            bordered
            className="vitalHeight"
            pagination={false}
            columns={columns}
            dataSource={tableData}
            scroll={{ x: 900, y: store.getState().tableHeight.y + 90 }}
            style={{ height: (store.getState().tableHeight.y + 136) }}
          />
        </div>

        {/* 历史查询 */}
        <ShowComponentModal
          isShow={visible}
          dataSource={{
            ENDesc: '',
            title: '历史查询',
            component: 'pages/workstation/component/ConsultationHistory.jsx',
          }}
          onHide={() => this.modifyVisible(false)}
        />
      </div>
    )
  }
};

export default IndividualVitalSigns;