/*
 * Create:      柿子
 * CreateDate:  2022/08/23
 * Describe：   电子病历tabs - 生命体征
 * */
import React, { Component } from 'react';
import { Radio, Button, Collapse, Select, Empty, DatePicker, Input } from 'antd';
import { Util, dayFormat } from 'tools';
import moment from 'moment';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Panel } = Collapse;
const InputGroup = Input.Group;

class EMRVitalSigns extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recordData: React.$getSessionData('patientData'),
      historyAdmID: '',
      loading: false,
      selectData: {}, // 生命体征初始化数据
      settDataActive: '', // 默认全部
      startDate: moment(),
      endDate: moment(),
      vitalSignsTableData: [], // 生命体征列表数据
      collapseActive: 1,
      relatedEventsID: '', // 关联事件
    };
    this.vitalSignsPanelColumns = [{
      key: 1,
      title: '时间',
      dataIndex: 'time',
      align: 'center',
      width: 60
    }, {
      key: 2,
      title: '项目',
      dataIndex: 'itemDesc',
      align: 'center',
      width: 100
    }, {
      key: 3,
      title: '值',
      dataIndex: 'value',
      align: 'center',
      width: 60
    }, {
      key: 4,
      title: '单位',
      dataIndex: 'unit',
      align: 'center',
      width: 80
    }]
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.historyAdmID !== prevState.historyAdmID) {
      return true
    }
    return null
  }

  componentDidMount() {
    this.getSelectData();
  }

  // 获取生命体征初始化数据
  getSelectData = async () => {
    try {
      let { historyAdmID, recordData } = this.state;
      let data = {
        params: [{
          admID: historyAdmID || recordData.admID,
        }]
      }
      let res = await React.$asyncPost(this, '04040026', data);
      let selectData = res?.result || {};
      let startDate = selectData && 'startDate' in selectData && selectData.startDate ? moment(selectData.startDate, dayFormat) : moment();
      let endDate = selectData && 'stopData' in selectData && selectData.stopData ? moment(selectData.stopData, dayFormat) : moment();
      this.setState({ selectData, startDate, endDate }, () => {
        this.getVitalSignsTableData();
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 获取生命体征列表数据
  getVitalSignsTableData = async () => {
    try {
      this.setState({ loading: true });
      let { historyAdmID, recordData, startDate, endDate, settDataActive } = this.state;
      let data = {
        params: [{
          admID: historyAdmID || recordData.admID,
          startDate: moment(startDate).format(dayFormat),
          stopDate: moment(endDate).format(dayFormat),
          time: settDataActive
        }]
      }
      let res = await React.$asyncPost(this, '04040025', data);
      let vitalSignsTableData = res?.result || [];
      if (vitalSignsTableData && vitalSignsTableData.length > 0) {
        vitalSignsTableData[0].checked = true;
        this.state.collapseActive = 1;
      }
      this.setState({ vitalSignsTableData, loading: false });
    } catch (error) {
      console.log(error)
      this.setState({ loading: false });
    }
  }

  // 选择时间段
  handleSettDataClick = record => {
    this.setState({ settDataActive: record?.time || '' }, () => {
      this.getVitalSignsTableData()
    })
  }

  // 修改
  handleInputChange = (e, dataIndex) => {
    this.state[dataIndex] = e;
    this.setState({});
  }

  handleCollapseChange = (key) => {
    this.setState({ collapseActive: Array.isArray(key) && key.length > 0 ? key[key.length - 1] : key });
  }

  handleRadioChange = (index, e) => {
    React.$stopPropagation(e);
    let { vitalSignsTableData } = this.state;
    if (e.target.checked) {
      for (var i = 0; i < vitalSignsTableData.length; i++) {
        vitalSignsTableData[i].checked = false;
      }
    }
    vitalSignsTableData[index].checked = e.target.checked;
    this.setState({});
  }

  // 引用
  handleQuote = () => {
    let { selectData, relatedEventsID, vitalSignsTableData } = this.state;
    let quoteRecord = Util.returnDataCccordingToAttributes(vitalSignsTableData, true, 'checked');
    let quoteArr = quoteRecord?.valueArr || [];
    let quoteStr = quoteRecord?.valueStr || '';
    if (relatedEventsID) {
      let dataArr = selectData?.dataArr || [];
      let relatedEventsObj = Util.returnDataCccordingToAttributes(dataArr, relatedEventsID);
      let date = relatedEventsObj?.startDate || '';
      let time = relatedEventsObj?.startTime || '';
      let separator = relatedEventsObj?.separator || ','; // 分割符
      if (quoteArr && quoteArr.length > 0) { // 关联事件
        quoteArr[0] = date;
        quoteArr[1] = time;
      }
      if (quoteStr && quoteStr.indexOf(separator) > -1) { // 处理字符串引用
        let quoteSplit = quoteStr.split(separator);
        quoteSplit[0] = date;
        quoteSplit[1] = time;
        quoteStr = quoteSplit.join(separator);
      }
    }
    this.props.handleQuote && this.props.handleQuote(quoteArr, quoteStr);
  }

  render() {
    const { loading, startDate, endDate, selectData, settDataActive, vitalSignsTableData, collapseActive, relatedEventsID } = this.state;
    return (
      <div className="cipt-vital-signs">
        <div style={{ paddingRight: '12px' }}>
          <div className="flex-align-items">
            <InputGroup style={{ width: '280px', display: 'flex' }} compact>
              <DatePicker
                format={dayFormat}
                showToday={false}
                allowClear
                value={startDate}
                onChange={(e) => this.handleInputChange(e, 'startDate')}
              />
              <Input value="至" disabled style={{ width: 39, color: '#999' }} />
              <DatePicker
                format={dayFormat}
                showToday={false}
                allowClear
                value={endDate}
                onChange={(e) => this.handleInputChange(e, 'endDate')}
              />
            </InputGroup>
            <Button loading={loading} style={{ marginLeft: '12px' }} type="primary" onClick={this.getVitalSignsTableData}>查询</Button>
          </div>
          <div style={{ margin: '12px 0' }}>
            {selectData && 'settData' in selectData && Array.isArray(selectData.settData) && selectData.settData.map((item, index) => {
              return (
                <Button style={{ marginRight: '6px' }} type={settDataActive === item.time ? 'primary' : 'default'} ghost={!!(settDataActive === item.time)} key={index} size="small" onClick={() => this.handleSettDataClick(item)}>
                  {item.timeDesc}
                </Button>
              )
            })}
          </div>
        </div>
        <div style={{ height: store.getState().tableHeight.y - 84 + 'px', overflow: 'auto' }} className="scroll-bar-style">
          {vitalSignsTableData && vitalSignsTableData.length > 0 ? (
            <div style={{ paddingRight: '12px' }}>
              <Collapse
                bordered={false}
                expandIconPosition="right"
                activeKey={collapseActive}
                onChange={this.handleCollapseChange}
              >
                {vitalSignsTableData && vitalSignsTableData.map((item, index) => {
                  return (
                    <Panel
                      key={index + 1}
                      header={
                        <div>
                          <Radio checked={item.checked} onChange={(e) => this.handleRadioChange(index, e)} onClick={(e) => React.$stopPropagation(e)}>{item.date}</Radio>
                        </div>
                      }
                    >
                      <div style={{ minHeight: item && 'result' in item && item.result.length > 0 ? '' : '220px' }}>
                        <PubilcTablePagination
                          param={{
                            data: item?.result || [], // 表格数据
                            x: 300, // 表格的宽度
                            y: 'N',
                            height: 'auto',
                            loading: false,
                            columns: this.vitalSignsPanelColumns, // 表头配置
                          }}
                        // setRowClassNamePublic={this.handleVitalSignsPanelRowClassName}
                        />
                      </div>
                    </Panel >
                  )
                })}
              </Collapse>
            </div>
          ) : <Empty style={{ marginTop: '80px' }} />}
        </div>
        <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
        <div style={{ paddingRight: '12px' }}>
          <div style={{ margin: '8px 0' }}>
            关联事件：
            <Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              style={{ width: '250px' }}
              value={relatedEventsID}
              onChange={(e) => this.handleInputChange(e, 'relatedEventsID')}
            >
              {React.$SelectOptions(selectData?.dataArr || [], 'id', 'desc')}
            </Select>
          </div>
          <Button block type="primary" onClick={this.handleQuote}>
            引用
          </Button>
        </div>
      </div >
    )
  }
};

export default EMRVitalSigns;