/*
 * Create:      柿子
 * CreateDate:  2023/09/14
 * Describe：   手术护理记录
 * */
import React from 'react'
import { Modal, Row, Col, Card, Button, message } from 'antd';
import { Util } from 'tools';
import { $fastReportTemplate } from '../../lodop/Common/FastReportPrint.js';
import store from 'store';
import PatientInfo from '../Patient/PatientInfo.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import './style/index.less';

class OperationPatDispatch extends React.Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    let patientData = React.$getSessionData('patientData');
    this.state = {
      userData,
      patientData,
      visible: false,
      rowData: {},
      selectData: {},
      formRecordData: {}, // 表单回显数据
      entrySequenceData: {},
      preoperativeFormData: [], // 术前
      intraoperativeFormData: [], // 术中
      postoperativeFormData: [], // 术后
      handoverRecordFormData: [], // 术后转运交接记录
      printLoading: false,
      saveLoading: false
    }
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  modifyVisible = (visible, rowData = {}, selectData = {}, formRecordData = {}, entrySequenceData = {}) => {
    const { preoperativeFormData, intraoperativeFormData, postoperativeFormData, handoverRecordFormData } = this.state;
    if (visible) {
      if (!(preoperativeFormData && preoperativeFormData.length > 0)) {
        this.getPreoperativeFormData(selectData, formRecordData);
      } else {
        formRecordData = this.handleFilterFormRecordData(preoperativeFormData, selectData, formRecordData); // 后台返回的多选值为字符串，需前端自行处理成数组回显
      }
      if (!(intraoperativeFormData && intraoperativeFormData.length > 0)) {
        this.getIntraoperativeFormData(selectData, formRecordData);
      } else {
        formRecordData = this.handleFilterFormRecordData(intraoperativeFormData, selectData, formRecordData);
      }
      if (!(postoperativeFormData && postoperativeFormData.length > 0)) {
        this.getPostoperativeFormData(selectData, formRecordData);
      } else {
        formRecordData = this.handleFilterFormRecordData(postoperativeFormData, selectData, formRecordData);
      }
      if (!(handoverRecordFormData && handoverRecordFormData.length > 0)) {
        this.getHandoverRecordFormData(selectData, entrySequenceData);
      } else {
        entrySequenceData = this.handleFilterFormRecordData(handoverRecordFormData, selectData, entrySequenceData);
      }
      // 清除数据缓存
      this.state.formRecordData = {};
      this.state.entrySequenceData = {};
    }
    this.setState({ visible, rowData, selectData, formRecordData, entrySequenceData });
  }

  // 处理表单回显数据
  handleFilterFormRecordData = (formData, selectData, recordData) => {
    let copyRecordData = JSON.parse(JSON.stringify(recordData));
    for (let i = 0; i < formData.length; i++) {
      let dataIndex = formData[i]?.dataIndex || '';
      let currentVal = formData[i] && dataIndex && copyRecordData ? copyRecordData[dataIndex] : '';
      if (dataIndex && formData[i].typeCode === 'CheckBoxGroup' && currentVal && currentVal.indexOf(';' > -1)) {
        let currentSelectData = selectData[dataIndex] || [];
        let elementData = currentVal.split(';');
        let printData = [];
        for (let j = 0; j < elementData.length; j++) {
          printData.push(Util.returnDataCccordingToAttributes(currentSelectData, elementData[j], 'code')?.descripts || '')
        }
        copyRecordData[dataIndex] = printData;
      }
    }
    return copyRecordData;
  }

  // 获取术前表单数据
  getPreoperativeFormData = async (selectData, recordData) => {
    try {
      let data = {
        params: [{
          compontName: 'SurgicalCareRecordsPreoperative',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let preoperativeFormData = res.result?.formData || [];
      let formRecordData = this.handleFilterFormRecordData(preoperativeFormData, selectData, recordData);
      this.setState({ preoperativeFormData, formRecordData });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取术前表单数据
  getIntraoperativeFormData = async (selectData, recordData) => {
    try {
      let data = {
        params: [{
          compontName: 'SurgicalCareRecordsIntraoperative',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let intraoperativeFormData = res.result?.formData || [];
      let formRecordData = this.handleFilterFormRecordData(intraoperativeFormData, selectData, recordData);
      this.setState({ intraoperativeFormData, formRecordData });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取术前表单数据
  getPostoperativeFormData = async (selectData, recordData) => {
    try {
      let data = {
        params: [{
          compontName: 'SurgicalCareRecordsPostoperative',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let postoperativeFormData = res.result?.formData || [];
      let formRecordData = this.handleFilterFormRecordData(postoperativeFormData, selectData, recordData);
      this.setState({ postoperativeFormData, formRecordData });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取术前表单数据
  getHandoverRecordFormData = async (selectData, recordData) => {
    try {
      let data = {
        params: [{
          compontName: 'SurgicalCareRecordsHandoverRecord',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let handoverRecordFormData = res.result?.formData || [];
      let entrySequenceData = this.handleFilterFormRecordData(handoverRecordFormData, selectData, recordData);
      this.setState({ handoverRecordFormData, entrySequenceData });
    } catch (error) {
      console.log(error);
    }
  }

  // 录入顺序
  handleEntrySequence = (componentName) => {
    componentName && this.preoperativeFormRef && this.preoperativeFormRef.showFromMaintenanceModal(componentName);
  }

  // 保存
  handleSave = async () => {
    try {
      let preoperativeValue = await this.preoperativeFormRef.handleSave();
      if (preoperativeValue && preoperativeValue.error) {
        message.wrr('请完善术前记录中的必填项。');
        return;
      }
      let intraoperativeValue = await this.intraoperativeFormRef.handleSave();
      if (intraoperativeValue && intraoperativeValue.error) {
        message.wrr('请完善术中记录中的必填项。');
        return;
      }
      let postoperativeValue = await this.postoperativeFormRef.handleSave();
      if (postoperativeValue && postoperativeValue.error) {
        message.wrr('请完善术后记录中的必填项。');
        return;
      }
      let handoverRecordValue = await this.handoverRecordFormRef.handleSave();
      if (handoverRecordValue && handoverRecordValue.error) {
        message.wrr('请完善术后转运交接记录中的必填项。');
        return;
      }
      const { userData, rowData, selectData, handoverRecordFormData } = this.state;
      for (let i = 0; i < handoverRecordFormData.length; i++) {
        if (handoverRecordFormData[i].typeCode === 'CheckBoxGroup') { // 多选框值处理，适配小程序端
          let currentCheckData = handoverRecordValue[handoverRecordFormData[i].dataIndex]; // 当前选中的值
          if (currentCheckData && Array.isArray(currentCheckData) && currentCheckData.length > 0) {
            let currentCopyCheckData = JSON.parse(JSON.stringify(currentCheckData));
            let currentSelectData = selectData[handoverRecordFormData[i].dataIndex] || [];
            let elementData = [];
            for (let j = 0; j < currentCopyCheckData.length; j++) {
              elementData.push(Util.returnDataCccordingToAttributes(currentSelectData, currentCopyCheckData[j], 'descripts')?.code || '')
            }
            handoverRecordValue[handoverRecordFormData[i].dataIndex] = {
              printData: currentCopyCheckData,
              elementData
            };
          }
        }
      }
      this.setState({ saveLoading: true });
      let data = {
        params: [{
          ...rowData,
          updateUserID: userData?.userID || '',
          templateCode: 'SSHLJLD2',
          IEMRTempElementData: { // 表单数据
            ...preoperativeValue,
            ...intraoperativeValue,
            ...postoperativeValue,
            ...handoverRecordValue
          }
        }]
      }
      let res = await React.$asyncPost(this, '04220022', data);
      message.success(res?.errorMessage || '保存成功');
      this.setState({ saveLoading: false });
      // this.modifyVisible(false);
      // this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
      this.setState({ saveLoading: false });
    }
  }

  // 打印
  handlePrint = async () => {
    try {
      const { rowData, userData } = this.state;
      this.setState({ printLoading: true });
      const data = {
        params: [{
          ...rowData,
          templateID: '295',
          templateCode: 'SSHLJLD2',
          userID: userData?.userID || '',
          hospID: userData?.hospID || '',
        }]
      }
      const res = await React.$asyncPost(this, '04220020', data);
      this.setState({ printLoading: false });
      let printData = res.result?.data || [];
      let templateName = res?.result?.template || '';
      for (let i = 0; i < printData.length; i++) {
        let dataResult = printData[i];
        $fastReportTemplate(templateName, userData?.hospID, dataResult, '');
      }
    } catch (error) {
      console.log(error);
      this.setState({ printLoading: false });
    }
  }

  render() {
    const { visible, rowData, patientData, preoperativeFormData, intraoperativeFormData, postoperativeFormData, handoverRecordFormData, selectData, formRecordData, saveLoading, printLoading, entrySequenceData } = this.state;
    return (
      <Modal
        title="手术护理记录"
        width="95vw"
        okText="保存"
        visible={visible}
        bodyStyle={{ padding: '12px' }}
        onCancel={() => this.modifyVisible(false)}
        footer={[
          <Button key="1" type="primary" loading={saveLoading} onClick={() => this.handleSave()}>
            保存
          </Button>,
          <Button key="2" ghost type="primary" loading={printLoading} onClick={this.handlePrint}>
            打印
          </Button>
        ]}
      >
        <div className="operation-pat-dispatch" style={{ maxHeight: '80vh', overflow: 'auto' }}>
          <PatientInfo admID={rowData?.admID || patientData?.admID || ''} />
          <Row style={{ marginTop: '6px' }}>
            <Col span={5}>
              <Card
                type="inner"
                title={<div>术前记录</div>}
                size="small"
                extra={(
                  selectData?.entrySequenceBtnFlag !== 'N' ? (
                    <Button
                      size="small"
                      onClick={() => this.handleEntrySequence('SurgicalCareRecordsPreoperative')}
                    >
                      录入顺序
                    </Button>
                  ) : ''
                )}
              >
                <div style={{ height: store.getState().tableHeight.y - 100 + 'px', overflow: 'auto', paddingRight: '6px' }} className="scroll-bar-style">
                  <DynamicRenderingForm
                    className="opd-form"
                    selectData={selectData}
                    rowData={formRecordData}
                    formData={preoperativeFormData}
                    onRef={ref => this.preoperativeFormRef = ref}
                  />
                </div>
              </Card>
            </Col>
            <Col span={9}>
              <div
                style={{ position: 'relative', height: '100%', padding: '0 8px' }}
              >
                <div className="common-card-left-split-line" style={{ width: 8, background: '#fff' }}></div>
                <Card
                  type="inner"
                  title={<div>术中记录</div>}
                  size="small"
                  extra={(
                    selectData?.entrySequenceBtnFlag !== 'N' ? (
                      <Button
                        size="small"
                        onClick={() => this.handleEntrySequence('SurgicalCareRecordsIntraoperative')}
                      >
                        录入顺序
                      </Button>
                    ) : ''
                  )}
                >
                  <div style={{ height: store.getState().tableHeight.y - 100 + 'px', overflow: 'auto', paddingRight: '6px' }} className="scroll-bar-style">
                    <DynamicRenderingForm
                      className="opd-form"
                      selectData={selectData}
                      rowData={formRecordData}
                      formData={intraoperativeFormData}
                      onRef={ref => this.intraoperativeFormRef = ref}
                    />
                  </div>
                </Card>
                <div className="common-card-right-split-line" style={{ width: 8, background: '#fff' }}></div>
              </div>
            </Col>
            <Col span={5}>
              <div
                style={{ position: 'relative', height: '100%', paddingRight: '8px' }}
              >
                <Card
                  type="inner"
                  title={<div>术后记录</div>}
                  size="small"
                  extra={(
                    selectData?.entrySequenceBtnFlag !== 'N' ? (
                      <Button
                        size="small"
                        onClick={() => this.handleEntrySequence('SurgicalCareRecordsPostoperative')}
                      >
                        录入顺序
                      </Button>
                    ) : ''
                  )}
                >
                  <div style={{ height: store.getState().tableHeight.y - 100 + 'px', overflow: 'auto', paddingRight: '6px' }} className="scroll-bar-style">
                    <DynamicRenderingForm
                      className="opd-form"
                      selectData={selectData}
                      rowData={formRecordData}
                      formData={postoperativeFormData}
                      onRef={ref => this.postoperativeFormRef = ref}
                    />
                  </div>
                </Card>
                <div className="common-card-right-split-line" style={{ width: 8, background: '#fff' }}></div>
              </div>
            </Col>
            <Col span={5}>
              <Card
                type="inner"
                title={<div>术后转运交接记录</div>}
                size="small"
                extra={(
                  selectData?.entrySequenceBtnFlag !== 'N' ? (
                    <Button
                      size="small"
                      onClick={() => this.handleEntrySequence('SurgicalCareRecordsHandoverRecord')}
                    >
                      录入顺序
                    </Button>
                  ) : ''
                )}
              >
                <div style={{ height: store.getState().tableHeight.y - 100 + 'px', overflow: 'auto', paddingRight: '6px' }} className="scroll-bar-style">
                  <DynamicRenderingForm
                    className="opd-form"
                    selectData={selectData}
                    rowData={entrySequenceData}
                    formData={handoverRecordFormData}
                    onRef={ref => this.handoverRecordFormRef = ref}
                  />
                </div>
              </Card>
            </Col>
          </Row>
        </div>
      </Modal>
    )
  }
};

export default OperationPatDispatch