/*
 * Create:      刘丹
 * CreateDate:  2023/7/31
 * Describe：   电子病历模板-自研电子病历emr
 * */
import React from 'react';
import CaseInformationPageTabs from '../workstation/component/CaseInformationPageTabs.jsx';
import DoctorAdviceStepPage from 'pages/workstation/component/DoctorAdviceStepPage';
import ShowDiagnosisModal from 'pages/common/ShowDiagnosisModal.jsx';
import store from 'store';
import { Modal } from 'antd';
import { $http } from 'containers/config/https';
import { initIframeUrl } from './utils/index.js';

class CaseInformation extends React.Component {
  constructor(props) {
    super(props);
    // 登录用户数据 hospCode userCode userName locID
    const userData = React.$getSessionData(); //
    // 病人数据 admID, patID
    const recordData = React.$getSessionData('patientData');
    // 选中的当前病人的详情数据
    const titleData = React.$getSessionData('titleData');
    const { historyAdmID = '' } = this.props || {};
    this.state = {
      recordData,
      historyAdmID: historyAdmID || recordData.admID || titleData?.admID,
      titleData,
      userData,
      treeSelectData: {},
      modalRowData: {},
      iframeUrl: '',
      ref: React.createRef(),
      diagnosisSearch: false, // 诊断录入显示
      medicalOrderVisible: false, // 医嘱录入显示
      doctorAdviceRef: null,
      showDiagnosisChild: null,
      visibleRight: false,
    };
  }
  componentDidMount () {
    if (!this.props?.hideQute) {
      this.getDefaultTemplate();
    }
    this.initIframeUrl();
  }
  // 获取his的session数据
  getSessionData = () => {
    const { userData } = window.sessionStorage;
    if (userData) {
      const user = JSON.parse(userData);
      const ip = React.$getSessionData('ipConfig');
      return [{
        userID: user.userID || '',
        locID: user.locID || '',
        groupID: user.groupID || '',
        hospID: user.hospID || '',
        sessionID: user.sessionID || '',
        hostName: ip?.hostName || '',
        ipv4: ip?.ipv4 || '',
        ipv6: ip?.ipv6 || '',
        mac: ip?.mac || ''
      }];
    }
    return [];
  }
  // 接收emr的数据
  getMessage = () => {
    window.addEventListener('message', (event) => {
      let { data } = event;
      if (!data) {
        return;
      }
      if (typeof data === 'string') {
        data = JSON.parse(data);
        const { openName } = data;
        if (openName === 'initEMRSuccess') {
          const iframe = this.state.ref?.current;
          iframe?.contentWindow?.postMessage(JSON.stringify({
            openName: 'getHisSession',
            session: JSON.stringify(this.getSessionData()),
          }), '*');
        }
        // 打开医嘱
        if (openName === 'openHisdoctorAdvice') {
          this.setState({
            medicalOrderVisible: true,
          }, function () {
            this.depAdviceRef && this.depAdviceRef.loadData();
          });
        }
        // 打开诊断
        if (openName === 'openHisdiagnosis') {
          this.setState({
            diagnosisSearch: true,
          });
        }
      }
    });
  }
  // 获取板分组科室下默认模板右侧引用数据组件需要的传值获取
  getDefaultTemplate = () => {
    $http.post('urlS', this, {
      code: '06010094',
      data: {
        params: [{
          admID: this.state.historyAdmID,
          admLanguage: this.state.userData.admLanguage || 'CN',
        }],
      },
      success: (res) => {
        if (+res.errorCode === 0) {
          const { dataAry = [] } = res.result;
          const data = dataAry[0] || {};
          const treeSelectData = {
            ...data,
            ID: data.wTemplateCatID || '',
          }
          const modalRowData = {
            ...data,
            ID: data.templateID || '',
            releaseVersion: data?.eMRReleaseVersion,
          }
          this.setState({
            treeSelectData,
            modalRowData,
          }, function () {
            // 获取知识数据
            this.getChildKnowledgeBaseTreeData();
          });
        }
      }
    })
  }
  // 初始化IFRAM地址的url地址
  initIframeUrl = () => {
    const url = initIframeUrl('/nav/editorEdit', this.state.userData, {
      historyAdmID: this.state.historyAdmID,
      queID: this.state.titleData.queID,
      areaRoomID: this.state.titleData.areaRoomID,
      ...this.props,
    });
    this.setState({
      iframeUrl: url,
    });
    this.getMessage();
  }
  /**
   *
   * @param {*} data 要引用的内容
   * @param {*} isCover 是否覆盖数据，默认追加组件内容
   * @returns
   */
  rightQuote = (data, isCover = false) => {
    if (typeof (data) !== 'string') {
      return;
    }
    const iframe = this.state.ref?.current;
    iframe.contentWindow.postMessage(JSON.stringify({
      openName: 'componentDataQuote',
      text: data,
      isCover,
    }), '*');
  }
  // 右侧知识库引用
  rightKnowledgeQuotev = (field, value) => {
    value = value.replaceAll('\n', '<br/>');
    value = value.replaceAll(' ', '&nbsp;');;
    this.rightQuote(value);
  }
  // 赋值知识库对象
  handleCaseInformationRef = ref => {
    this.caseInformationChild = ref;
  }
  // 获取知识库数据
  getChildKnowledgeBaseTreeData = () => {
    this.caseInformationChild.getKnowledgeBaseTreeData('1', this.state.modalRowData);
  }
  /**
    * @ByShizi: 新增医嘱录入弹窗操作
    * Create 2022-08-10
  * */
  handleMedicalOrderOk = async (clickSource) => {
    const ruleOfReferences = await this.getRuleOfReference('QuoteResourcesOrder');
    // 插入诊断前先判断是否有需要保存的数据
    let isSave = this.depAdviceRef && this.depAdviceRef.handleDetermineWhetherToSave
      ? this.depAdviceRef.handleDetermineWhetherToSave()
      : true;
    if (isSave && clickSource === 'confirm') { // 如果有需要保存的数据并且是点击的确认按钮则需要先保存
      this.depAdviceRef.insuTypeCodeFlagFun && this.depAdviceRef.insuTypeCodeFlagFun(clickSource);
    } else {
      let medOrderArr = this.depAdviceRef && this.depAdviceRef.getSelectedRows
        ? this.depAdviceRef.getSelectedRows()
        : [];
      medOrderArr = medOrderArr && medOrderArr.filter(item => !!(item.ordMedItemDesc));
      if (medOrderArr && medOrderArr.length > 0) {
        let domValue = this.handleRuleReference(medOrderArr, ruleOfReferences ? ruleOfReferences : 'ordMedItemDesc');
        this.rightQuote(domValue, true);
        this.setState({
          medicalOrderVisible: false,
        });
      } else {
        message.error('请勾选或者录入医嘱再进行插入。');
      }
    }
  }
  // 获取配置的引用规则
  getRuleOfReference = async (ruleCode) => {
    let ruleOfReferences = '';
    try {
      let data = {
        params: [{
          power: 'DocEMRResource',
          eMRResourceRuleCode: ruleCode
        }]
      }
      let res = await React.$asyncPost(this, '06010079', data);
      ruleOfReferences = res?.result || '';
      // ruleOfReferences = ruleOfReferences.replace('medDesc', 'ordMedItemDesc'); // 医嘱名称
      // ruleOfReferences = ruleOfReferences.replace('ordUsageDesc', 'ordUsageDesc'); // 用法
      ruleOfReferences = ruleOfReferences.replace('ordDoseUnit', 'ordDoseQtyUnit'); // 剂量
      ruleOfReferences = ruleOfReferences.replace('ordFreqDesc', 'ordFrequenceDesc'); // 频次
      // ruleOfReferences = ruleOfReferences.replace('ordbodyPartDesc', 'ordbodyPartDesc'); // 部位
    } catch (error) {
      ruleOfReferences = '';
      console.log(error)
    }
    return ruleOfReferences;
  }
  // 医嘱引用规则文案处理
  handleRuleReference = (arr, values) => {
    let insertMethod = this.depAdviceRef && this.depAdviceRef.getInsertMethod
      ? this.depAdviceRef.getInsertMethod()
      : 'transverse'; // 横排： transverse  竖排： vertical
    let valueArr = values.split('+');
    let str = ''
    for (let i = 0; i < arr.length; i++) {
      str += i + 1 + '、';
      for (let j = 0; j < valueArr.length; j++) {
        if (arr[i][valueArr[j]]) {
          str += arr[i][valueArr[j]] + '  ';
        }
      }
      str += (insertMethod === 'vertical' ? ((i === arr.length - 1) ? '' : '</br>') : '  ');
    }
    return str;
  }
  // 插入诊断
  handleDiagnosisSearchOk = (clickSource) => {
    // 插入诊断前先判断是否有需要保存的数据
    let isSave = this.showDiagnosisChild && this.showDiagnosisChild.handleDetermineWhetherToSave
      ? this.showDiagnosisChild.handleDetermineWhetherToSave()
      : true;
    if (isSave && clickSource === 'confirm') { // 如果有需要保存的数据并且是点击的确认按钮则需要先保存
      this.showDiagnosisChild.saveDiagnosisMsg && this.showDiagnosisChild.saveDiagnosisMsg(clickSource);
    } else {
      let diagDescArr = this.showDiagnosisChild && this.showDiagnosisChild.getSelectedRows
        ? this.showDiagnosisChild.getSelectedRows()
        : [];
      if (diagDescArr && diagDescArr.length > 0) {
        this.handleInsertDiagnosis(diagDescArr, 'checkout');
      } else {
        let { diagnosisRowData } = this.state;
        let data = {
          params: [{
            admID: this.state.historyAdmID,
          }]
        }
        $http.post('urlS', this, {
          code: diagnosisRowData && diagnosisRowData.serviceCode ? diagnosisRowData.serviceCode : '',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              let diagnosisSourse = res.result;
              this.handleInsertDiagnosis(diagnosisSourse);
            }
          }
        })
      }
    }
  }
  // 插入诊断
  handleInsertDiagnosis = (diagnosisSourse, sourse) => {
    const insertMethod = this.showDiagnosisChild && this.showDiagnosisChild.getInsertMethod
      ? this.showDiagnosisChild.getInsertMethod()
      : 'transverse'; // 横排： transverse  竖排： vertical
    if (diagnosisSourse && diagnosisSourse.length > 0) {
      let domValue = '';
      for (var k = 0; k < diagnosisSourse.length; k++) {
        domValue += (k + 1) + '、' + diagnosisSourse[k] + (insertMethod === 'vertical' ? ((k === diagnosisSourse.length - 1) ? '' : '</br>') : '  ');
      }
      this.rightQuote(domValue, true);
    } else {
      message.error('请勾选或者录入同类诊断再进行插入。');
      return;
    }
    this.handleDiagnosisSearchCancel(); // 关闭插入弹窗
  }
  // 关闭诊断弹窗
  handleDiagnosisSearchCancel = () => {
    this.setState({
      diagnosisSearch: false,
    });
  }
  // 切换右侧的显示
  toggleRight = () => {
    this.setState({
      visibleRight: !this.state.visibleRight,
    });
  }
  render () {
    return (
      <>
        <div style={{
          paddingTop: '6px',
          background: 'rgb(240, 242, 245)',
          height: store.getState().tableHeight.y + 158, display: 'flex'
        }}>
          <div style={{ paddingTop: '6px', background: 'rgb(240, 242, 245)', }}> </div>
          <iframe
            ref={this.state.ref}
            src={this.state.iframeUrl}
            frameborder="0"
            style={{ height: '100%', flex: 1, paddingRight: '6px', background: 'rgb(240, 242, 245)' }}
          ></iframe>
          {this.props?.hideQute
            ? null
            : <div style={{
              width: this.state.visibleRight ? '500px' : '0px',
              height: '100%', position: 'relative', background: '#fff'
            }}>
              <CaseInformationPageTabs
                hideHistory={true}
                modalRowData={this.state.modalRowData}
                historyAdmID={this.state.historyAdmID}
                treeSelectData={this.state.treeSelectData}
                handleQuote={this.rightQuote}
                onRef={this.handleCaseInformationRef}
                knowledgeBaseAssignment={this.rightKnowledgeQuotev}
              />
              <span
                style={{
                  position: 'absolute', left: '-20px', top: '50%', border: '1px solid #ddd',
                  background: '#fff', borderRadius: '12px 0 0 12px', wordBreak: 'break-all',
                  width: '20px', textAlign: 'center', padding: '8px 4px', borderRight: 'none', cursor: 'pointer'
                }}
                onClick={this.toggleRight}>
                {this.state.visibleRight ? '收起' : '展开'}
              </span>
            </div>}
        </div >
        <Modal
          title="诊断录入"
          visible={this.state.diagnosisSearch}
          onOk={() => this.handleDiagnosisSearchOk("confirm")}
          style={{ minWidth: '75vw' }}
          onCancel={this.handleDiagnosisSearchCancel}
          className="electronic-case-template-modal"
        >
          <div style={{ width: "100%" }}>
            <ShowDiagnosisModal
              onRef={ref => this.showDiagnosisChild = ref}
              handleDiagnosisSearchOk={this.handleDiagnosisSearchOk}
            />
          </div>
        </Modal>

        <Modal
          title="医嘱录入"
          visible={this.state.medicalOrderVisible}
          onOk={() => this.handleMedicalOrderOk('confirm')}
          style={{ minWidth: '75vw' }}
          onCancel={() => this.setState({ medicalOrderVisible: false })}
          className="electronic-case-template-modal"
        >
          <div style={{ width: '100%', height: '55vh' }}>
            <DoctorAdviceStepPage
              patStatus="1"
              heightVH={46}
              componentSourse="EMR" // 用于区分住院，列表数据保存之后是否清空
              // adviceList={this.state.adviceList}
              // ordPriorityID={this.state.priorityID}
              hideStatus={false}
              onRef={ref => this.depAdviceRef = ref}
              handleMedicalOrderOk={this.handleMedicalOrderOk}
            // dstroyAdviceList={this.dstroyAdviceList.bind(this)}
            />
          </div>
        </Modal>
      </>
    )
  }
};
export default CaseInformation;
