/*
 * Create:      柿子
 * CreateDate:  2023/06/29
 * Describe：   查看病历/门诊住院通用
 * */
import React, { Component } from 'react';
import { Tree, Input, Icon, Modal, message, Popconfirm, Tabs, Spin, Button, Tooltip, Empty } from 'antd';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import { Util } from 'tools/index';
import { $fastReportTemplate } from 'pages/lodop/Common/FastReportPrint';
import store from 'store';
import PublicTableEditable from 'pages/common/PublicTableEditable';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import '../../pharmacy/outpha/style/outpha.less';
import '../style/CMOrderSave.less';

const { TabPane } = Tabs;
const { TreeNode } = Tree;
const { confirm } = Modal;

class ViewingMedicalRecords extends Component {
  constructor(props) {
    super(props)
    var recordData = JSON.parse(sessionStorage.getItem('patientData'));
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    var titleData = JSON.parse(sessionStorage.getItem('titleData'));
    this.newTabIndex = 0;
    this.state = {
      recordData,
      userData,
      titleData,
      expandedKeys: [],
      selectedKeys: [],
      treeSelectData: {},
      treeData: [],
      templateName: '',
      autoExpandParent: true,
      modalTemplateData: [],
      oldModalTemplateData: [],
      modalRowData: {},
      showValidateResult: 'show', // 是否显示错误下拉框
      spinLoading: false, // 全局loading
      defaultMillisecond: 0, // 默认倒计时毫秒数
      isDeleteRecord: false, // 是否可以删除病历
      loadingTitle: '', // loading加载描述
      isUnlocking: true,
      recordDataID: '', // 病历记录数据ID
      historyAdmID: '',
      visible: false,
      panes: [],
      recordActiveKey: '0',
      templateID: undefined,
      templateValue: undefined,
      templateParams: [],
      recordSheetLoading: false,
      recordSheetColumns: [],
      recordSheetTotalWidth: 1000,
      templateColumnsInfo: {},
      rowId: '',
    };
    this.columns = [{
      title: '序号',
      dataIndex: 'key',
      key: '1',
      width: '50px',
      align: 'center'
    }, {
      title: '模板名称',
      dataIndex: 'descripts',
      key: '2',
      width: '300px',
      align: 'center'
    }, {
      title: '模板版本号',
      dataIndex: 'releaseVersion',
      key: '3',
      width: '100px',
      align: 'center'
    }];
  }

  componentDidMount() {
    this.props && this.props.onRef && this.props.onRef(this);
    this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
    this.getChineseAndEnglishData();
    this.getTreeData('patientRecords');
    this.props && this.props.onRef && this.props.onRef(this);
    window.sessionStorage.setItem('showMessagePopUp', 'N');
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    //该方法内禁止访问this
    if (nextProps.historyAdmID !== prevState.historyAdmID) {
      //通过对比nextProps和prevState，返回一个用于更新状态的对象
      return true
    }
    //不需要更新状态，返回null
    return null
  }

  componentDidUpdate() {
    // 做一些需要this.props的事
    if (this.props.historyAdmID && (this.props.historyAdmID !== this.state.historyAdmID) && this.props.isDidUpdate && this.props.isDidUpdate === 'Y') {
      this.setState({ historyAdmID: this.props.historyAdmID, panes: [], recordActiveKey: '0', selectedKeys: [] }, () => {
        this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
        this.getTreeData('patientRecords');
      })
    }
  }

  componentWillUnmount() {
    this.handleClearComponentInformation();
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 切换病人更新相关数据
  loadPatientMsg = () => {
    this.setState({
      recordData: React.$getSessionData('patientData'),
      titleData: React.$getSessionData('titleData'),
      panes: []
    }, () => {
      this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
      this.getTreeData('patientRecords');
    })
  }

  // 组件销毁时清除组件信息
  handleClearComponentInformation = () => {
    let { panes } = this.state;
    if (panes && panes.length > 0) {
      for (var i = 0; i < panes.length; i++) {
        // 关闭当前组件前解锁所有打开的病历
        let eMRRecordID = panes[i] && panes[i].modalRowData && panes[i].modalRowData.patEMRRecordID ? panes[i].modalRowData.patEMRRecordID : '';
        if (eMRRecordID && this.props.isOperable !== 'Y') {
          this.jqAjax(eMRRecordID, (res) => {
            console.log(res)
          })
        }
      }
    }
    window.onresize = null;
    window.sessionStorage.setItem('showMessagePopUp', 'Y');
  }

  // 同步请求 -- 解锁
  jqAjax = (eMRRecordID, success, error) => {
    if (window && window.$ && window.$.ajax) {
      let userData = JSON.parse(sessionStorage.getItem('userData'));
      if (!(eMRRecordID && userData && userData.userID)) {
        return;
      }
      let url = httpConfig.ipDeault + httpConfig.urlAddress;
      let json = {
        params: [{
          patEMRRecordID: eMRRecordID,
        }]
      }
      let formData = Object.assign({}, json);
      let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
      windowHost = windowHost + '/bdhealth/';
      // 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
      url = windowHost && windowHost.indexOf('localhost') !== -1 ? url : windowHost;
      let { ipConfig } = window.sessionStorage
      formData.code = '06050015';
      if (userData) {
        let ip = JSON.parse(ipConfig)
        formData.session = [{
          userID: userData.userID || '',
          locID: userData.locID || '',
          groupID: userData.groupID || '',
          hospID: userData.hospID || '',
          sessionID: userData.sessionID || '',
          hostName: ip.hostName || '',
          ipv4: ip.ipv4 || '',
          ipv6: ip.ipv6 || '',
          mac: ip.mac || '',
        }]
      }
      $.ajax({
        type: 'post',                          //请求方式
        url,     //请求地址
        data: JSON.stringify(formData),                         //发送的数据，这里是json对象
        dataType: 'json',                      //数据类型
        // contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (data) {
          success && success(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          // console.log(XMLHttpRequest, textStatus, errorThrown)
          error && error(errorThrown);
        },
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': httpConfig.authorizationToken,
          'Access-Control-Allow-Origin': httpConfig.ipDeault
        },
      });
    }
  }

  // 获取中英文数据
  getChineseAndEnglishData = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        compontName: 'CaseInformationPage',
        type: 'C',
        reactCode: ['CaseInformationPage']
      }]
    }
    $http.post('urlDeault', this, {
      code: '01040073',
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          var totalWidth = 0;
          let arr = res.result.C && res.result.C.map((item, index) => {
            return {
              ...item,
              key: index,
              widthNum: parseInt(item.width),
              title: <div key={index} onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
            }
          });
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          let obj = {
            title: userData.language == 'EN' ? 'Operation' : '操作',
            key: 14,
            align: 'center',
            width: '80px',
            fixed: 'right',
            widthNum: 80,
            render: (text, record) => (
              <span>
                <Icon type='delete' style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                <Popconfirm title='删除不可恢复，你确定要删除吗?' onConfirm={() => this.handleDelete(record)} >
                  <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                </Popconfirm>
              </span>
            ),
          };
          filterArr.push(obj);
          for (var i = 0; i < filterArr.length; i++) {
            totalWidth += filterArr[i].widthNum;
          }
          this.setState({
            // columns: filterArr,
            // totalWidth,
            localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
          })
        }
      }
    })
  }

  onMainColumnRef = ref => {
    this.mainColumnRef = ref;
  }

  //国际化
  setMessage = (name, message, defaultTitle) => {
    return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
  }

  handleDelete = record => {
    console.log(record)
  }

  // 获取板分组科室下默认模板
  getDefaultTemplate = () => {
    let { recordData, userData } = this.state;
    let data = {
      params: [{
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        admLanguage: userData && userData.admLanguage ? userData.admLanguage : 'CN',
      }]
    }
    $http.post('urlS', this, {
      code: '06010094',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let dataAry = res.result.dataAry;
          let defaultMillisecond = res.result && res.result.autoSaveTime ? Number(res.result.autoSaveTime) : 0;
          let maxOpenTablePanel = res.result && res.result.MaxOpenTablePanel ? Number(res.result.MaxOpenTablePanel) : 5;
          if (!(dataAry && dataAry.length > 0)) {
            this.setState({ defaultMillisecond, maxOpenTablePanel })
            return;
          }
          let key = [];
          let treeSelectData = JSON.parse(JSON.stringify(dataAry[0]));
          treeSelectData.ID = treeSelectData.wTemplateCatID;
          treeSelectData.descripts = treeSelectData.templateDesc;
          treeSelectData.treeType = treeSelectData && treeSelectData.templateTreeType ? treeSelectData.templateTreeType : 'CATALOG';
          if (treeSelectData && 'patEMRRecordID' in treeSelectData && treeSelectData.patEMRRecordID) {
            key.push(treeSelectData.patEMRRecordID);
          } else {
            key.push(treeSelectData.wTemplateCatID);
          }
          this.setState({
            selectedKeys: key,
            defaultMillisecond,
            maxOpenTablePanel,
            spinLoading: true,
            loadingTitle: '病历模板加载中……'
          }, () => {
            let obj = JSON.parse(JSON.stringify(dataAry[0]));
            obj.ID = obj.templateID;
            obj.releaseVersion = obj.eMRReleaseVersion; // 版本号
            if (obj && 'patEMRRecordID' in obj && obj.patEMRRecordID) {
              obj.flag = 'patientRecords';
              obj.treeType = 'TEMPLATE';
              obj.closable = 'N';
              obj.descripts = obj?.templateDesc || '病历';
              this.handleLoadingMedicalRecords(treeSelectData, obj, 'patientRecords');
            } else {
              this.setState({ modalRowData: obj }, () => { // 加载病历模板
                this.getModalTemplateData(treeSelectData, 'default');
              })
            }
          })
        }
      }
    })
  }

  // 3.6.2.根据分组目录获取模板
  getModalTemplateData = Util.debounce((treeSelectData, isHanle) => {
    let { modalRowData, recordData } = this.state;
    let data = {
      params: [{
        groupTemplateID: treeSelectData.ID, // 分组目录ID - 导航目录ID
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
      }]
    }
    $http.post('urlS', this, {
      code: '06050007',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          for (var i = 0; i < res.result.length; i++) {
            if (res.result[i].ID === modalRowData.ID) {
              res.result[i].checked = true;
              modalRowData = res.result[i];
              break;
            }
          }
          let modalTemplateData = res.result.filter(function (item) { return item.releaseVersion });
          this.setState({ modalTemplateData, oldModalTemplateData: modalTemplateData, isHanle: isHanle ? isHanle : '' }, () => {
            if (this.state.isHanle !== 'default') {
              if (this.state.modalTemplateData && this.state.modalTemplateData.length > 1) {
                this.showModal();
              } else {
                // 获取患者病历数据
                let obj = this.state.modalTemplateData && this.state.modalTemplateData.length > 0 ? this.state.modalTemplateData[0] : {};
                this.getPatienHistoryData(treeSelectData, obj, 'loadTemplate')
              }
            } else {
              this.setState({ modalRowData }, () => {
                this.getPatienHistoryData(treeSelectData, { ...modalRowData, isHanle, closable: 'N' }, 'loadTemplate')
              })
            }
          })
        } else {
          this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false })
        }
      },
      error: function () {
        this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false })
      }
    })
  })

  // 处理tree数据
  filterTreeData = (treeData, type, oldItem) => {
    let data = treeData && treeData.map(item => {
      // 当为首程并且首程下存在病程时则首程的progressID就为病程ID;
      let progressID = item && item.subCatalog && item.subCatalog.length > 0 && item.subCatalog[0].treeType && item.subCatalog[0].treeType === 'PROGRESS' ? 'first' : '';
      return {
        title: item.descripts,
        key: item.ID,
        ID: item && item.treeType && item.treeType === 'PROGRESS' ? (oldItem && oldItem.ID ? oldItem.ID : '') : item.ID,
        progressID: item && item.treeType && item.treeType === 'PROGRESS' ? item.ID : progressID,
        treeType: item && item.treeType ? item.treeType : (item && item.subCatalog ? 'CATALOG' : 'TEMPLATE'),
        ...item,
        ...oldItem,
        children: this.filterTreeData(item.subCatalog, type, item && item.treeType && item.treeType === 'TEMPLATE' ? item : {})
      }
    });
    return data;
  }

  // 3.6.1.根据患者获取病历模板分组目录树
  getTreeData = (type) => {
    let { recordData } = this.state;
    let data = {
      params: [{
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        wTempVer: type === 'patientRecords' ? 'Y' : undefined, // 是否查询导航目录模板版本信息
        patEMRRec: type === 'patientRecords' ? 'Y' : undefined, // 是否查询患者已填写病历信息
        locID: type === 'patientRecords' ? (this.props && this.props.locID ? this.props.locID : '') : undefined, // 患者病历预览界面专用 -- 科室ID
        fGroup: type === 'patientRecords' ? (this.props && this.props.fGroup ? this.props.fGroup : '') : undefined, // 患者病历预览界面专用 -- 职能科室
      }]
    }
    $http.post('urlS', this, {
      code: '06050006',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = this.filterTreeData(res.result, type);
          if (type === 'patientRecords') {
            this.setState({ treeData: arr, commitFlag: res.result && res.result.length > 0 ? res.result[0].commitFlag : '', commitBtnDesc: res.result && res.result.length > 0 ? res.result[0].commitBtnDesc : '' }, () => {
              this.generateList(this.state.treeData, 'patientRecords')
            })
          } else {
            this.setState({ treeData: arr }, () => {
              this.generateList(this.state.treeData, 'treeData')
            })
          }
        } else {
          if (type === 'patientRecords') {
            this.setState({ patientRecords: [] })
          } else {
            this.setState({ treeData: [] })
          }
        }
      }
    })
  }

  // 渲染树节点
  renderTreeNodes = data => data && data.map((item) => {
    let inputValue = this.state.templateName;
    const index = item.title && item.title.indexOf(inputValue);
    const beforeStr = item.title && item.title.substr(0, index);
    const afterStr = item.title && item.title.substr(index + inputValue.length);
    const title = index > -1 ? (
      <span>
        {beforeStr}
        <span style={{ color: '#FF7F00' }}>{inputValue}</span>
        {afterStr}
      </span>
    ) : <span>{item.title}</span>;
    // progressID存在并且不等于first则为病程 为first则为首程（病程主节点）
    let type = item.treeType === 'CATALOG' ? 'folder-open' : ((item.treeType === 'TEMPLATE' && !(item.progressID && item.progressID !== 'first')) ? 'folder' : 'file');
    if (item.children) {
      return (
        <TreeNode
          key={item.key}
          dataRef={item}
          icon={<Icon type={type} />}
          title={(
            <Tooltip title={title} placement="right">
              <span
                className='ellipsis'
                style={{ width: '120px', display: 'inline-block' }}
                onClick={() => this.handleAnchorPositioning(item)}
              >
                {title}
              </span>
            </Tooltip>
          )}
        >
          {this.renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return (
      <TreeNode
        key={item.key}
        dataRef={item}
        icon={<Icon type={type} />}
        title={(
          <Tooltip title={title} placement="right">
            <span
              className='ellipsis'
              style={{ width: '150px', display: 'inline-block' }}
              onClick={() => this.handleAnchorPositioning(item)}
            >
              {title}
            </span>
          </Tooltip>
        )}
      />
    )
  })

  // 锚点定位
  handleAnchorPositioning = item => {
    let { recordActiveKey } = this.state;
    let recordID = 'record' + item.ID;
    if (item && item.treeType === 'PROGRESS') {
      recordActiveKey && this[recordActiveKey] && this[recordActiveKey].handleAnchorPositioning ?
        this[recordActiveKey].handleAnchorPositioning(recordID) :
        (this.caseTemplateChild && this.caseTemplateChild.handleAnchorPositioning && this.caseTemplateChild.handleAnchorPositioning(recordID));
    }
  }

  getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  dataList = []; // 病历模板
  generateList = (data, type) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      this.dataList.push({ key, title: node.title });
      if (node.children) {
        this.generateList(node.children, type);
      }
    }

    // 默认进来tree全部加载
    let treeData = this.state.treeData;
    let dataList = this.dataList;
    const expandedKeys = dataList.map((item) => {
      return this.getParentKey(item.key, treeData);
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
    });
  };

  handleTemplateNameChange = e => {
    const templateName = e.target.value;
    let dataList = this.dataList;
    let treeData = JSON.parse(JSON.stringify(this.state.treeData));
    const expandedKeys = dataList.map((item) => {
      if (templateName.length === 0) return null;
      if (item.title && item.title.indexOf(templateName) > -1) {
        return this.getParentKey(item.key, treeData);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys: expandedKeys && expandedKeys.length > 0 ? expandedKeys : [],
      templateName: e.target.value,
      autoExpandParent: true,
    });
  }

  handleRecordsExpand = (expandedKeys) => {
    // console.log('触发了onExpand', expandedKeys)
    this.setState({
      expandedKeys: expandedKeys,
      autoExpandParent: false,
    });
  }

  // 选择患者病历目录
  handleRecordsSelect = (keys, event) => {
    let { spinLoading } = this.state;
    let selectData = event.node.props.dataRef;
    let treeSelectData = JSON.parse(JSON.stringify(selectData));
    if (!(keys && keys.length > 0)) {
      return;
    }
    if ((selectData && !(selectData.treeType === 'TEMPLATE' || selectData.treeType === 'NurseTEMPLATE' || (selectData.treeType === 'CATALOG' && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
      return;
    }
    this.setState({ selectedKeys: keys }, () => {
      treeSelectData.ID = treeSelectData.wTempCataID;
      selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
      if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && (selectData.treeType === 'TEMPLATE' || selectData.treeType === 'NurseTEMPLATE' || selectData.treeType === 'PROGRESS')) {
        this.getPatienHistoryData(treeSelectData, selectData, 'patientRecords')
      }
    })
  }

  // 双击患者病历目录树
  handleRecordsDoubleClickTreeNodes = (status, record) => {
    let { spinLoading } = this.state;
    let selectData = record.props != undefined ? record.props.dataRef : record;
    if ((selectData && !(selectData.treeType === 'TEMPLATE' || selectData.treeType === 'NurseTEMPLATE' || (selectData.treeType === 'CATALOG' && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
      return;
    }
    let treeSelectData = JSON.parse(JSON.stringify(selectData));
    let key = [selectData?.ID || ''];
    this.setState({ selectedKeys: key }, () => {
      treeSelectData.ID = treeSelectData.wTempCataID;
      selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
      if (selectData && (selectData.treeType === 'TEMPLATE' || selectData.treeType === 'NurseTEMPLATE' || selectData.treeType === 'PROGRESS')) {
        this.getPatienHistoryData(treeSelectData, selectData, 'patientRecords');
      }
    })
  }

  // 确认引用
  handleOk = () => {
    let messageTrue = false;
    let obj = {};
    let modalTemplateData = JSON.parse(JSON.stringify(this.state.modalTemplateData));
    if (modalTemplateData && modalTemplateData.length > 0) {
      for (let i = 0; i < modalTemplateData.length; i++) {
        if (modalTemplateData[i].checked == true) {
          messageTrue = true
          obj = modalTemplateData[i];
          break;
        } else {
          messageTrue = false
        }
      }
    }
    // console.log(arr)
    if (messageTrue === false) {
      message.error('请选择模板', this.state.userData && this.state.userData.messageTime)
    } else {
      obj.isHanle = this.state.isHanle;
      let treeSelectData = JSON.parse(JSON.stringify(obj));
      treeSelectData.ID = treeSelectData.wTempCataID;
      this.setState({ rowId: '', }, () => {
        this.getPatienHistoryData(treeSelectData, obj, 'cancel')
      })
    }
  }

  handleCancel = () => {
    this.setState({ spinLoading: false });
  }

  // 3.6.8.获取患者病历数据
  getPatienHistoryData = Util.debounce((treeSelectData, obj, flag) => {
    let oldModalRowData = this.state.modalRowData && this.state.modalRowData.ID ? JSON.parse(JSON.stringify(this.state.modalRowData)) : obj; // 历史选择的模板数据
    let isModify = false;
    if (treeSelectData?.treeType === 'NurseTEMPLATE') { // 新护理记录单
      isModify = this.handleDifferenceComparison();
    } else {
      isModify = this.getModified();
    }
    let _this = this;
    if (obj.isHanle !== 'default' && isModify) {
      confirm({
        title: <div>当前病历 <span style={{ fontWeight: '900' }}>{oldModalRowData.descripts}</span> 已修改，是否需要保存？</div>,
        okText: "是->保存",
        cancelText: "否->无需保存",
        onOk() {
          obj.load = true; // 是否加载切换的病历模板
          obj.flag = flag;
          obj.saveType = 'auto';
          _this.setState({ spinLoading: true, loadingTitle: '保存中…' }, () => {
            if (treeSelectData?.treeType === 'NurseTEMPLATE') {
              _this.handleRecordSheetSave(() => _this.handleLoadingMedicalRecords(treeSelectData, obj, flag));
            } else {
              _this.handleSave(treeSelectData, obj);
            }
          })
        },
        onCancel() {
          _this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
        },
      });

      if (flag === 'cancel') {
        this.handleCancel();
      }
    } else {
      _this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
    }
  })

  // 判断是否修改数据 - 修改后提示保存
  handleDifferenceComparison = () => {
    const { recordActiveKey } = this.state;
    return this['tableEditableRef' + recordActiveKey] && this['tableEditableRef' + recordActiveKey].handleDifferenceComparison ? this['tableEditableRef' + recordActiveKey].handleDifferenceComparison() : false;
  }

  // 判断文件内容是否修改
  getModified = () => {
    let { recordActiveKey } = this.state;
    let isModify = recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getModified ?
      this[recordActiveKey].getModified() :
      (this.caseTemplateChild && this.caseTemplateChild.getModified ? this.caseTemplateChild.getModified() : false);
    return isModify
  }

  // 病历加载
  handleLoadingMedicalRecords = (treeSelectData, obj, flag) => {
    this.handleAddTab(obj, () => {
      this.setState({ spinLoading: true, loadingTitle: "病历加载中…", templateID: obj.templateID }, () => {
        if (flag === "patientRecords") {
          // let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID; // 病程记录ID
          // if (obj && obj.addLockFlag === "N") { // 判断病历加载是否需要加锁操作
          let modifyParams = [{
            keys: 'isDeleteRecord',
            values: true
          }]
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          this.setState({ panes: newPanes }, () => { // 加载已保存的患者病历模板可以删除
            if (treeSelectData?.treeType === 'NurseTEMPLATE') { // 新护理记录单
              this.setCurrentTabsCloumns(flag, 'N');
              this.getRecordSheetTableData();
            } else { // 正常病历加载
              this.newLoadingMedicalRecords(treeSelectData, obj, flag);
            }
          })
        } else {
          if (treeSelectData?.treeType === 'NurseTEMPLATE') { // 新护理记录单
            this.setCurrentTabsCloumns(flag);
          } else { // 正常病历加载
            this.SaveMedicalRecord(treeSelectData, obj, flag)
          }
        }
      })
    });
  }

  // 获取列表数据
  getRecordSheetTableData = async () => {
    try {
      const { recordData, recordActiveKey } = this.state;
      let activeRecord = this.getDataRelatedToMedicalRecords('recordObj');
      this.setState({ recordSheetLoading: true });
      let data = {
        params: [{
          recordID: activeRecord?.patEMRRecordID || '',
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        }]
      }
      let res = await React.$asyncPost(this, '06030102', data);
      let recordSheetTableData = res?.result?.dataSource || [];
      let modifyParams = [{
        keys: 'recordDataID',
        values: res.result?.recordDataID || ''
      }, {
        keys: 'printTemplate',
        values: res.result?.printTemplate || ''
      }]
      let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
      this.setState({ panes: newPanes, recordSheetTableData, recordSheetLoading: false });
      this['tableEditableRef' + recordActiveKey] && this['tableEditableRef' + recordActiveKey].setTableData(recordSheetTableData);
    } catch (error) {
      console.log(error);
      this.setState({ recordSheetLoading: false });
    }
  }

  // 设置当前页签的表头数据
  setCurrentTabsCloumns = async (flag, isSetTableData) => {
    let { templateColumnsInfo, recordActiveKey } = this.state;
    flag === 'cancel' && this.handleCancel(); // 关闭弹窗
    let currentRecord = this.getDataRelatedToMedicalRecords('recordObj');
    let currentColumns = currentRecord?.columns || [];
    if (!(currentColumns && currentColumns.length > 0)) { // 没打开过的获取table列
      let templateID = currentRecord?.templateID || '';
      let columnsInfo = templateColumnsInfo && ('template' + templateID) in templateColumnsInfo && templateColumnsInfo['template' + templateID] ? templateColumnsInfo['template' + templateID] : {};
      let columns = columnsInfo?.columns || [];
      if (!(columns && columns.length > 0)) {
        columnsInfo = await this.getRecordSheetColumns(templateID);
        templateColumnsInfo['template' + templateID] = columnsInfo; // 将模板数据存起来，避免多次请求
        if (columnsInfo?.errorFlag === 'Y') { // 获取数据异常
          this.setState({ spinLoading: false });
          return;
        }
      }
      let recordSheetColumns = JSON.parse(JSON.stringify(columnsInfo?.columns || []));
      let recordSheetTotalWidth = columnsInfo?.totalWidth || 1000;
      let modifyParams = [{
        keys: 'columns',
        values: recordSheetColumns
      }, {
        keys: 'totalWidth',
        values: recordSheetTotalWidth
      }, {
        keys: 'tableRenderType',
        values: columnsInfo?.tableRenderType || ''
      }]
      let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
      this.setState({ panes: newPanes, recordSheetColumns, recordSheetTotalWidth, templateColumnsInfo, spinLoading: false }, () => {
        this['tableEditableRef' + recordActiveKey] && this['tableEditableRef' + recordActiveKey].setTableColumns(recordSheetColumns);
        isSetTableData !== 'N' && this['tableEditableRef' + recordActiveKey] && this['tableEditableRef' + recordActiveKey].setTableData([]);
      })
    } else {
      this.setState({ spinLoading: false })
    }
  }

  // 获取护理记录单表头数据
  getRecordSheetColumns = async (templateID) => {
    try {
      if (!templateID) return;
      let data = {
        params: [{
          templateID
        }]
      }
      let res = await React.$asyncPost(this, '06030100', data);
      let columns = res?.result || [];
      for (let i = 0; i < columns.length; i++) {
        columns[i].ellipsis = false; // 不溢出隐藏
      }
      return {
        columns,
        totalWidth: res?.totalWidth || 1000,
        tableRenderType: res?.tableRenderType || '', // 护理记录单列表渲染方式
      }
    } catch (error) {
      return {
        errorFlag: 'Y',
      }
    }
  }

  // 加载病历模板
  handleLoadingMedicalRecordTemplate = (treeSelectData, obj, flag) => {
    let { recordData, titleData, recordActiveKey } = this.state;
    let newPanes = JSON.parse(JSON.stringify(this.state.panes));
    let data = {
      params: [{
        patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        groupTemplateID: obj.ID, // 分组模板ID
        power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ''
      }]
    }
    $http.post('urlS', this, {
      code: "06050016",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let authority = res.result && res.result.authority ? res.result.authority : {};
          let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === "Y" || authority.updateOrNot === "Y")) ? "N" : "Y"); // 是否可操作
          obj.flag = flag; // 保存调用类型
          obj.removeLockFlag = authority.removeLockFlag;
          let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
          let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID;
          let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
          for (var j = 0; j < newPanes.length; j++) {
            if (newPanes[j].key === recordActiveKey) {
              newPanes[j].treeSelectData = treeSelectData;
              newPanes[j].modalRowData = obj;
              newPanes[j].templatePath = templatePath;
              newPanes[j].isUnlocking = true;
              newPanes[j].eMRRecordID = eMRRecordID;
            }
          }
          this.setState({
            templatePath, eMRRecordID, treeSelectData, panes: newPanes,
            modalRowData: obj, spinLoading: false, isUnlocking: true
          }, () => {
            this.state.templatePath ?
              (recordActiveKey && this[recordActiveKey] && this[recordActiveKey].setElementTextByID ?
                this[recordActiveKey].setElementTextByID(this.state.templatePath, res.result.dataSource, isOperable, "boolFalse", titleData && titleData.patSexDesc ? titleData.patSexDesc : '', obj.releaseVersion, obj.templateID, progressID) :
                this.caseTemplateChild.setElementTextByID(this.state.templatePath, res.result.dataSource, isOperable, "boolFalse", titleData && titleData.patSexDesc ? titleData.patSexDesc : '', obj.releaseVersion, obj.templateID, progressID)) :
              this.caseTemplateChild.NewFile();
            if (flag === "cancel") {
              this.handleCancel();
            }
            this.props.changeTipFlag === 'Y' && authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
          })
        } else {
          this.setState({ patientHistoryData: [], spinLoading: false })
        }
      },
      error: function () {
        this.setState({ patientHistoryData: [], spinLoading: false })
      }
    })
  }

  // 加载病历 - 加载已保存的患者病历模板可以删除
  newLoadingMedicalRecords = (treeSelectData, obj, flag) => {
    let { recordData, titleData, recordActiveKey } = this.state;
    let newPanes = JSON.parse(JSON.stringify(this.state.panes));
    let data = {
      params: [{
        patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ''
      }]
    }
    $http.post('urlS', this, {
      code: '06050008',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let authority = res.result && res.result.authority ? res.result.authority : {};
          let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
          // let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
          obj.flag = flag; // 保存调用类型
          obj.removeLockFlag = authority.removeLockFlag;
          let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
          let isUnlocking = this.props.isOperable === 'Y' ? true : false;
          let recordDataID = res.result && res.result.recordDataID ? res.result.recordDataID : '';
          let eMRRecordID = res.result && res.result.eMRRecordID ? res.result.eMRRecordID : '';
          let needUpdateData = res.result && res.result.needUpdateData && res.result.needUpdateData.length ? res.result.needUpdateData : [];
          let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
          let existFieldValIDData = res.result && res.result.existFieldValIDData ? res.result.existFieldValIDData : []; // 回带弹窗选择的基本数据
          let isPrintFlag = authority && 'noChangeTip' in authority && authority.noChangeTip && authority.noChangeTip.indexOf('病历已提交') > -1 ? 'Y' : 'N';
          for (var i = 0; i < needUpdateData.length; i++) {
            needUpdateData[i].key = i + 1;
          }
          for (var j = 0; j < newPanes.length; j++) {
            if (newPanes[j].key === recordActiveKey) {
              newPanes[j].treeSelectData = treeSelectData;
              newPanes[j].modalRowData = obj;
              newPanes[j].templatePath = templatePath;
              newPanes[j].isUnlocking = isUnlocking;
              newPanes[j].recordDataID = recordDataID;
              newPanes[j].eMRRecordID = eMRRecordID;
            }
          }
          this.setState({ // recordDataID -- 病历记录数据ID
            templatePath, eMRRecordID, treeSelectData, modalRowData: obj, spinLoading: false, isUnlocking, recordDataID, panes: newPanes
          }, () => {
            this.state.templatePath ? (recordActiveKey && this[recordActiveKey] && this[recordActiveKey].setElementTextByID ?
              this[recordActiveKey].setElementTextByID(
                this.state.templatePath,
                res.result.dataSource,
                isOperable, 'boolFalse',
                titleData && titleData.patSexDesc ? titleData.patSexDesc : '',
                obj.releaseVersion, obj.templateID, progressID, needUpdateData,
                existFieldValIDData,
                res.result.RYJLCorrectionFieldID,
                isPrintFlag
              ) :
              this.caseTemplateChild.setElementTextByID(
                this.state.templatePath,
                res.result.dataSource,
                isOperable,
                'boolFalse',
                titleData && titleData.patSexDesc ? titleData.patSexDesc : '',
                obj.releaseVersion,
                obj.templateID,
                progressID,
                needUpdateData,
                existFieldValIDData,
                res.result.RYJLCorrectionFieldID,
                isPrintFlag
              )
            ) :
              this.caseTemplateChild.NewFile();
            if (flag === 'cancel') {
              this.handleCancel();
            }
            this.props.changeTipFlag === 'Y' && authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
          })
        } else {
          this.setState({ patienHistoryData: [], spinLoading: false })
        }
      },
      error: function (error) {
        console.log('error', error);
        this.setState({ patienHistoryData: [], spinLoading: false })
      }
    })
  }

  // 3.6.3.保存病历记录
  SaveMedicalRecord = Util.debounce((treeSelectData, obj, flag, selectionXml) => {
    let { recordData, recordActiveKey } = this.state;
    let data = {
      params: [{
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        cataLogID: treeSelectData.ID, // 分组模板目录ID
        seqNo: '',
        templateID: obj.ID, // 病历模板ID
        sPatRecPower: flag === "courseOfDisease" ? "saveEMRProgress" : undefined
      }]
    }
    $http.post('urlS', this, {
      code: "06050001",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let recordID = res && res.ID ? res.ID : '';
          obj.BSEMRRDParRef = recordID;
          let modifyParams = [{
            keys: "isDeleteRecord",
            values: false
          }]
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          if (flag === "courseOfDisease") { // 插入病程
            recordActiveKey && this[recordActiveKey] && this[recordActiveKey].insertTheCourseOfDisease ?
              this[recordActiveKey].insertTheCourseOfDisease(selectionXml, recordID) :
              (this.caseTemplateChild && this.caseTemplateChild.insertTheCourseOfDisease && this.caseTemplateChild.insertTheCourseOfDisease(selectionXml, recordID))
          } else if (flag === "sampleDirectory") { // 加载范例病历
            this.setState({ panes: newPanes }, () => {
              this.handleLoadSampleMedicalRecord(treeSelectData, obj, flag);
            })
          } else if (flag === "loadTemplate" || flag === "cancel") { // 加载病历模板
            this.setState({ panes: newPanes }, () => { // 加载的病历模板不能删除
              this.handleLoadingMedicalRecordTemplate(treeSelectData, obj, flag);
            })
          } else {
            modifyParams[0].values = true;
            this.setState({ panes: newPanes }, () => { // 加载已保存的患者病历模板可以删除
              this.newLoadingMedicalRecords(treeSelectData, obj, flag);
            })
          }
        } else {
          this.setState({ spinLoading: false })
        }
      },
      error: function () {
        this.setState({ spinLoading: false })
      }
    })
  })

  // 加载范例病例
  handleLoadSampleMedicalRecord = async (treeSelectData, obj, flag) => {
    try {
      let { recordData, titleData, recordActiveKey } = this.state;
      let newPanes = JSON.parse(JSON.stringify(this.state.panes));
      let data = {
        params: [{
          // obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID
          patEMRRecordID: '',
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
          groupTemplateID: obj.ID, // 分组模板ID
          power: this.props.medicalType == 'Z' ? 'OutHospRecord' : '',
          examTempID: treeSelectData?.examTempID || ''
        }]
      }
      let res = await React.$asyncPost(this, '06050106', data);
      let authority = res.result && res.result.authority ? res.result.authority : {};
      let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
      // let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
      obj.flag = flag; // 保存调用类型
      obj.removeLockFlag = authority.removeLockFlag;
      let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
      let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID;
      let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
      let templateParams = [templatePath, res.result.dataSource, isOperable, 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID];
      for (var j = 0; j < newPanes.length; j++) {
        if (newPanes[j].key === recordActiveKey) {
          newPanes[j].treeSelectData = treeSelectData;
          newPanes[j].modalRowData = obj;
          newPanes[j].templatePath = templatePath;
          newPanes[j].isUnlocking = true;
          newPanes[j].eMRRecordID = eMRRecordID;
          newPanes[j].templateParams = templateParams;
        }
      }
      this.setState({
        templatePath, eMRRecordID, treeSelectData, panes: newPanes, templateParams,
        modalRowData: obj, spinLoading: false, isUnlocking: true
      }, () => {
        this.state.templatePath ?
          (recordActiveKey && this[recordActiveKey] && this[recordActiveKey].setElementTextByID ?
            this[recordActiveKey].setElementTextByID(...templateParams) :
            this.caseTemplateChild?.setElementTextByID(...templateParams)) :
          this.caseTemplateChild?.NewFile();
        this.props.changeTipFlag === 'Y' && authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
      })
    } catch (error) {
      console.log(error);
      this.setState({ spinLoading: false });
    }
  }

  // 保存插入的病程记录
  handleSaveTheInsertedCourse = (selectionXml, templateID) => {
    let treeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData');
    let obj = {};
    obj.ID = templateID;
    this.SaveMedicalRecord(treeSelectData, obj, 'courseOfDisease', selectionXml);
  }

  // 3.6.5.保存患者病历数据
  savePatientMedicalRecord = (newWTreeSelectData, record, fn) => {
    let { recordActiveKey } = this.state;
    let modalRowData = this.getDataRelatedToMedicalRecords('modalRowData');
    let oldTreeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData');
    let templateData = recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getTemplateXml ?
      this[recordActiveKey].getTemplateXml('form') :
      (this.caseTemplateChild && this.caseTemplateChild.getTemplateXml ? this.caseTemplateChild.getTemplateXml('form') : '');
    let data = {
      params: [{
        BSEMRRDParRef: modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID, // 病历记录ID
        recordData: templateData && templateData.xmlStr ? templateData.xmlStr : '', // 病历记录数据 --- 模板xml
        progressRecIDAry: templateData && templateData.allRecordID ? templateData.allRecordID : [], // 病历记录数据 --- 病程记录ID
        progressRecDataSource: templateData?.recordDataSource || [],
        submitOrNot: 'N', // submitOrNot
        auditOrNot: 'N', // 是否审核标志
        lockStatus: 'Y', // 锁定标志
        archivingStatus: 'U', // 归档标志
        wCatalogueID: oldTreeSelectData.ID, // 分组目录ID
        versionID: modalRowData && modalRowData.releaseVersion ? modalRowData.releaseVersion : '', // 病历模板ID
        patRecDataSource: recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getMedicalRecordFileIDAndValue ?
          this[recordActiveKey].getMedicalRecordFileIDAndValue() :
          (this.caseTemplateChild && this.caseTemplateChild.getMedicalRecordFileIDAndValue && this.caseTemplateChild.getMedicalRecordFileIDAndValue()), // 病历所有的输入域以及对应的值
      }]
    }
    $http.post('urlS', this, {
      code: '06050004',
      data: data,
      success: async function (res) {
        if (+res.errorCode === 0) {
          let recordDataID = res.result && res.result.recordDataID ? res.result.recordDataID : ''; // recordDataID -- 病历记录数据ID
          let templateParams = await this.newLoadingMedicalRecords(oldTreeSelectData, modalRowData, 'templateParams');
          let modifyParams = [{
            keys: 'recordDataID',
            values: recordDataID
          }, {
            keys: 'isDeleteRecord',
            values: true
          }, {
            keys: 'templateParams',
            values: templateParams
          }];
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          this.setState({ isHanle: '', spinLoading: false, recordDataID, panes: newPanes });
          this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历
          recordActiveKey && this[recordActiveKey] && this[recordActiveKey].resetModified ?
            this[recordActiveKey].resetModified('isModifyPermissions') :
            (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('isModifyPermissions') : ''); // 保存成功后修改编辑状态
          // handleLoadingMedicalRecordTemplate -- 病历模板   newLoadingMedicalRecords -- 已写过的病历
          if (newWTreeSelectData === 'handleLoadingMedicalRecordTemplate' || newWTreeSelectData === 'newLoadingMedicalRecords' || newWTreeSelectData === 'handleLoadSampleMedicalRecord' || newWTreeSelectData === 'saveBeforePrinting') { // 自动保存
            if (newWTreeSelectData === 'saveBeforePrinting' && fn) { // 如果为打印前保存的则保存完成后唤起打印
              fn();
              return;
            }
            return;
          }; // BSEMRRDParRef
          let key = [];
          key.push(modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID);
          message.success('保存成功', this.state.userData && this.state.userData.messageTime ? this.state.userData.messageTime : 3);
          if (newWTreeSelectData && newWTreeSelectData.ID) { // 判断是否自动保存的，
            this.setState({ treeSelectData: oldTreeSelectData });
          } else {
            this.setState({ selectedKeys: key })
          }
          if (record && record.load) { // 判断是否保存后需要加载新操作的模板，需要的话传入新模板数据
            this.handleLoadingMedicalRecords(newWTreeSelectData, record, record.flag);
          }
          if (fn) {
            fn();
          }
        } else {
          this.setState({ spinLoading: false });
          recordActiveKey && this[recordActiveKey] && this[recordActiveKey].resetModified ?
            this[recordActiveKey].resetModified('clearSaveBtnLoading') :
            (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '');
        }
      },
      error: function () {
        this.setState({ spinLoading: false });
        recordActiveKey && this[recordActiveKey] && this[recordActiveKey].resetModified ?
          this[recordActiveKey].resetModified('clearSaveBtnLoading') :
          (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '');
      }
    })
  }

  // 保存
  handleSave = (treeSelectData, record, fn) => {
    if (record && record.saveType === 'auto') { // 自动保存不需要加载loading提示
      this.savePatientMedicalRecord(treeSelectData, record, fn);
    } else if (record && record.saveType === 'print') { // 打印前如果有修改先保存
      this.setState({ spinLoading: true, loadingTitle: '加载中' }, () => {
        this.savePatientMedicalRecord(treeSelectData, record, fn);
      })
    } else {
      this.setState({ spinLoading: true, loadingTitle: '保存中' }, () => {
        this.savePatientMedicalRecord(treeSelectData, record, fn);
      })
    }
  }

  // 供病历公共组件调用获取知识库数据
  getChildKnowledgeBaseTreeData = (filedId) => {
    let modalRowData = this.getDataRelatedToMedicalRecords('modalRowData');
    if (this.state.courseID !== filedId) {// 点击同一个病程则不再调用查询知识库方法
      this.setState({ courseID: filedId }, () => {
        this.caseInformationChild && this.caseInformationChild.getKnowledgeBaseTreeData && this.caseInformationChild.getKnowledgeBaseTreeData(this.state.courseID, modalRowData);
      })
    }
  }

  //跳转到西药及其他
  goDoctorAdviceStepPage = () => {
    var params = {
      params: [{
        locID: this.state.userData.locID,
        hospID: this.state.userData.hospID,
        groupID: this.state.userData.groupID
      }]
    }
    $http.post('urlDeault', this, {
      code: '03050093',
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          for (var i = 0; i < res.result.length; i++) {
            if (res.result[i].code === 'CaseInformationPageHospital') {
              var { upDataComponentSource } = this.props;
              upDataComponentSource && upDataComponentSource(res.result[i]);
              return;
            }
          }
        }
      }
    });
  }

  // 双击患者病历节点加载相应病历模板
  handleStepDoubleClick = (item) => {
    let treeSelectData = JSON.parse(JSON.stringify(item));
    let key = [];
    treeSelectData.ID = treeSelectData.wTemplateCatID;
    let modalRowData = JSON.parse(JSON.stringify(item));
    modalRowData.ID = modalRowData.eMRTemplateID;
    modalRowData.releaseVersion = modalRowData.eMRReleaseVersion;
    key.push(treeSelectData.wTemplateCatID);
    this.setState({ selectedKeys: key }, () => {
      this.getPatienHistoryData(treeSelectData, modalRowData);
    });
  }

  // 更新患者病历记录锁状态
  updateMedicalRecordLockStatus = Util.debounce((eMRRecordID, treeSelectData, obj, flag) => {
    let userData = JSON.parse(sessionStorage.getItem('userData'));
    if (!(eMRRecordID && userData && userData.userID)) {
      if (!eMRRecordID) {
        // message.error('模板加载失败')
      }
      return;
    }
    let data = {
      // lockStatus为Y则为加锁
      params: [{
        patEMRRecordID: eMRRecordID,
        lockStatus: flag === 'patientRecords' ? 'Y' : undefined,
        uEMRRecLockPow: treeSelectData === 'forceUnlock' ? 'removeOtherLock' : undefined, // 强制解锁标志
      }]
    }
    $http.post('urlS', this, {
      code: '06050015',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let modifyParams = [{
            keys: 'isDeleteRecord',
            values: true
          }]
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          if (flag === 'patientRecords') { // 加载患者病历
            this.setState({ panes: newPanes }, () => { // 加载已保存的患者病历模板可以删除
              this.newLoadingMedicalRecords(treeSelectData, obj, flag);
            })
          }
          if (treeSelectData === 'forceUnlock') { // 强制解锁
            let oldModalRowData = this.getDataRelatedToMedicalRecords('modalRowData') ? this.getDataRelatedToMedicalRecords('modalRowData') : this.state.modalRowData;
            let oldTreeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData') ? this.getDataRelatedToMedicalRecords('treeSelectData') : this.state.treeSelectData;
            modifyParams[0].values = false;
            this.setState({ panes: newPanes }, () => {
              this.getPatienHistoryData(oldTreeSelectData, oldModalRowData, oldModalRowData && oldModalRowData.flag ? oldModalRowData.flag : '')
            })
          }
        }
      }
    })
  })

  // 向外输出当前模板名称
  getTemplateDesc = () => {
    let { modalRowData } = this.state;
    return modalRowData && modalRowData.descripts ? modalRowData.descripts : '';
  }

  // 切换病历tab
  handleRecordChange = activeKey => {
    let { panes } = this.state;
    let currenTabInfo = {}
    panes.map(item => {
      if (item.key == this.state.recordActiveKey)
        currenTabInfo = item
    })
    this.setState({ recordActiveKey: activeKey, templateID: currenTabInfo.templateID });
  }

  onEdit = (targetKey, action) => {
    if (action === 'remove') {
      this.handleRemoveRecordATab(targetKey)
    }
    // this[action](targetKey);
  };

  handleCaseTemplateRef = (ref, tabCaseTemplateChild) => {
    if (tabCaseTemplateChild) {
      this[tabCaseTemplateChild] = ref;
    } else {
      this.caseTemplateChild = ref;
    }
  }

  // 将ID中的||替换成_
  handleReplaceWithUnderline = (str) => {
    if (str && str.indexOf('||') !== -1) {
      return str.replace('||', '_');
    }
    return str;
  }

  // 添加tab
  handleAddTab = (obj, callback) => {
    const activeKey = obj && obj.ID && obj.treeType ? (obj.treeType + obj.ID) : (obj && obj.ID ? obj.ID : `newTab${this.newTabIndex++}`);
    let replaceActiveKey = this.handleReplaceWithUnderline(activeKey);
    let isExist = false;
    let panes = JSON.parse(JSON.stringify(this.state.panes));
    let maxOpenTablePanel = this.state.maxOpenTablePanel ? this.state.maxOpenTablePanel : 5; // 最大打开的病历页签数
    if (panes && panes.length > 0) {
      for (var i = 0; i < panes.length; i++) {
        let activeIndexKey = panes[i] && panes[i].ID && panes[i].treeType ? (panes[i].treeType + panes[i].ID) : (panes[i] && panes[i].ID ? panes[i].ID : `newTab${this.newTabIndex++}`)
        if (activeIndexKey === activeKey) {
          isExist = true;
          break;
        }
      }
    }
    // console.log(panes, activeKey)
    if (isExist) { // 判断是否已经存在该页签，存在则直接跳转，不存在则创建
      this.setState({ recordActiveKey: replaceActiveKey }, () => {
        if (callback) {
          callback();
        }
      });
    } else {
      if ((panes.length + 1) > maxOpenTablePanel) {
        message.error("为了不影响病历程序运行效率，同时打开的病历页签不能超过" + maxOpenTablePanel + "个。");
        return;
      }
      panes.push({
        ...obj,
        closable: obj && obj.closable ? obj.closable : 'Y',
        title: obj && obj.descripts ? obj.descripts : '病历',
        key: replaceActiveKey,
        onRef: (ref) => this.handleCaseTemplateRef(ref, replaceActiveKey)
      });
      this.setState({ panes, recordActiveKey: replaceActiveKey }, () => {
        if (callback) {
          callback();
        }
      });
    }
  }

  // 删除病历页签
  handleRemoveRecordATab = targetKey => {
    let { recordActiveKey } = this.state;
    let oldModalRowData = this.getDataRelatedToMedicalRecords('modalRowData', targetKey);
    let lastIndex;
    this.state.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.state.panes.filter(pane => pane.key !== targetKey);
    if (panes.length && recordActiveKey === targetKey) {
      if (lastIndex >= 0) {
        recordActiveKey = panes[lastIndex].key;
      } else {
        recordActiveKey = panes[0].key;
      }
    } else {
      recordActiveKey = '0'; // 默认展示暂无数据
    }
    this.setState({ panes, recordActiveKey }, () => {
      if (oldModalRowData && oldModalRowData.patEMRRecordID) {
        this.updateMedicalRecordLockStatus(oldModalRowData && oldModalRowData.patEMRRecordID ? oldModalRowData.patEMRRecordID : ''); // 解锁
      }
    });
  };

  // 获取当前病历所在tab所需的数据
  getDataRelatedToMedicalRecords = (param, targetKey) => {
    let { panes, recordActiveKey } = this.state;
    // tabs所对应的key值 不传则默认当前选中的key值
    let key = targetKey ? targetKey : recordActiveKey;
    if (panes && panes.length > 0) {
      for (var i = 0; i < panes.length; i++) {
        if (panes[i].key === key) {
          if (param === 'recordObj') {
            return panes[i]
          }
          return panes[i][param];
        }
      }
    } else {
      return param === 'recordObj' ? {} : '';
    }
  }

  // 修改当前病历所在tab的数据
  modifyDataRelatedToMedicalRecords = (params) => {
    let { recordActiveKey } = this.state;
    let newPanes = JSON.parse(JSON.stringify(this.state.panes));
    for (var i = 0; i < newPanes.length; i++) {
      if (newPanes[i].key === recordActiveKey) {
        for (var j = 0; j < params.length; j++) {
          newPanes[i][params[j].keys] = params[j].values;
        }
        break;
      }
    }
    return newPanes;
  }

  showModal = () => {
    let modalTemplateData = JSON.parse(JSON.stringify(this.state.modalTemplateData));
    this.setState({ visible: true }, () => {
      if (!(modalTemplateData && modalTemplateData[0].key)) { // 给弹窗赋值key
        for (var i = 0; i < modalTemplateData.length; i++) {
          modalTemplateData[i].key = i + 1;
        }
        this.setState({ modalTemplateData, oldModalTemplateData: modalTemplateData })
      }
      setTimeout(() => {
        this.commonTableChild && this.commonTableChild.handleLoading && this.commonTableChild.handleLoading();
      }, 300)
    });
  }

  commonTableRef = ref => {
    this.commonTableChild = ref;
  }

  // 操作行 --- 发药列表
  onClickRowPublic = (record, index) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowId === '') {
          // 保存行数据以及ID
          this.setState({ rowId: record.key }, () => {
            this.compileChecked(record, index)
          })
        } else {
          if (this.state.rowId !== record.key) {
            this.setState({ rowId: record.key }, () => {
              this.compileChecked(record, index)
            })
          }
        }
      },
      onDoubleClick: () => {
        this.setState({ rowId: record.key }, () => {
          this.compileChecked(record, index, 'ok')
        })
      }
    }
  }

  // 选中行操作 --- 发药列表
  setRowClassNamePublic = (record) => {
    return record.key === this.state.rowId ? 'clickRowStyle' : ''
  }

  // Checkbox的onChange事件
  compileChecked = (item, index, isOK) => {
    let modalTemplateData = [...this.state.modalTemplateData];
    for (var i = 0; i < modalTemplateData.length; i++) {
      let indexChecked = modalTemplateData[index].checked;
      modalTemplateData[i].checked = false;
      modalTemplateData[index].checked = indexChecked;
      if (modalTemplateData[i].ID === item.ID) {
        modalTemplateData[i].checked = true;
      }
    }
    this.setState({ modalTemplateData }, () => {
      if (isOK === "ok") {
        this.handleOk();
      }
    })
  }

  // 模板名称
  handleTemplateValue = e => {
    this.setState({ templateValue: e.target.value }, () => {
      if (!this.state.templateValue) {
        this.setState({ modalTemplateData: this.state.oldModalTemplateData })
      }
    })
  }

  // 回车筛选模板数据
  handleTemplateValuePressEnter = () => {
    let { templateValue } = this.state;
    let oldModalTemplateData = JSON.parse(JSON.stringify(this.state.oldModalTemplateData));
    var reg = new RegExp(templateValue);
    var arr = [];
    for (var i = 0; i < oldModalTemplateData.length; i++) {
      if (reg.test(oldModalTemplateData[i].descripts) || reg.test(oldModalTemplateData[i].spCode) || reg.test(oldModalTemplateData[i] && oldModalTemplateData[i].spCode ? oldModalTemplateData[i].spCode.toLowerCase() : '')) {
        arr.push(oldModalTemplateData[i]);
      }
    }
    this.setState({ modalTemplateData: arr });
  }

  // 护理记录单保存
  handleRecordSheetSave = async (fn) => {
    try {
      const { recordData, recordActiveKey, spinLoading } = this.state;
      if (!spinLoading) {
        this.setState({ spinLoading: true, loadingTitle: '保存中…' })
      }
      let activeRecord = this.getDataRelatedToMedicalRecords('recordObj');
      let recordSheetData = this['tableEditableRef' + recordActiveKey] && this['tableEditableRef' + recordActiveKey].handleSave();
      let data = {
        params: [{
          recordID: activeRecord?.patEMRRecordID || '',
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
          templateID: activeRecord?.templateID || '',
          dataSource: recordSheetData
        }]
      }
      let res = await React.$asyncPost(this, '06030101', data);
      message.success(res?.errorMessage || '保存成功');
      let modifyParams = [{
        keys: 'recordDataID',
        values: res.recordDataID || ''
      }, {
        keys: 'patEMRRecordID',
        values: res.recordID || ''
      }, {
        keys: 'printTemplate',
        values: res.printTemplate || ''
      }];
      let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
      this.setState({ panes: newPanes, spinLoading: false }, () => {
        this.getTreeData("patientRecords"); // 保存成功之后重新加载患者病历
        fn && fn();
        this['tableEditableRef' + recordActiveKey] && this['tableEditableRef' + recordActiveKey].handleClearRecord(); // 保存成功更新操作状态
      });
    } catch (error) {
      console.log(error);
      this.setState({ spinLoading: false });
    }
  }

  // 护理记录单打印
  handleRecordSheetPrint = async () => {
    try {
      const { userData } = this.state;
      let activeRecord = this.getDataRelatedToMedicalRecords('recordObj');
      let data = {
        params: [{
          recordDataID: activeRecord?.recordDataID || '',
        }],
        code: '06030105'
      }
      // console.log("data", data, this.state.panes)
      let res = await $fastReportTemplate(activeRecord?.printTemplate || '', userData?.hospID || '', '', data, 'N', '', 'N');
      console.log(res)
    } catch (error) {
      console.log(error)
    }
  }

  // 先保存
  handleSaveBeforeSelectPrint = (selectedRowKeys, selectedRows) => {
    this.handleRecordSheetSave(() => this.handleRecordSheetSelectPrint(selectedRowKeys, selectedRows));
  }

  // 护理记录单选择打印
  handleRecordSheetSelectPrint = async (selectedRowKeys, selectedRows) => {
    try {
      const { userData } = this.state;
      let activeRecord = this.getDataRelatedToMedicalRecords('recordObj');
      let data = {
        params: [{
          recordDataID: activeRecord?.recordDataID || '',
          selectedRowKeys
        }],
        code: '06030105'
      }
      console.log(data)
      let res = await $fastReportTemplate(activeRecord?.printTemplate || '', userData?.hospID || '', '', data, 'N', '', 'N');
      console.log(res)
    } catch (error) {
      console.log(error)
    }
  }

  render() {
    let { spinLoading, treeData, showValidateResult, templateName, autoExpandParent, expandedKeys, selectedKeys, loadingTitle, recordActiveKey, panes, visible, templateValue, modalTemplateData, recordSheetTotalWidth,
      recordSheetLoading
    } = this.state;

    // 获取当前病历所在的tabs的相对数据
    let eMRRecordID = this.getDataRelatedToMedicalRecords('eMRRecordID') ? this.getDataRelatedToMedicalRecords('eMRRecordID') : this.state.eMRRecordID;
    let modalRowData = this.getDataRelatedToMedicalRecords('modalRowData') ? this.getDataRelatedToMedicalRecords('modalRowData') : this.state.modalRowData;
    let treeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData') ? this.getDataRelatedToMedicalRecords('treeSelectData') : this.state.treeSelectData;
    let isDelete = this.getDataRelatedToMedicalRecords('isDeleteRecord') ? this.getDataRelatedToMedicalRecords('isDeleteRecord') : false;
    let isUnlocking = this.getDataRelatedToMedicalRecords('isUnlocking') !== undefined || this.getDataRelatedToMedicalRecords('isUnlocking') !== '' ? this.getDataRelatedToMedicalRecords('isUnlocking') : true;
    let param = {
      setChapter: 'show',
      formView: 'Normal',
      isInsert: 'hidden',
      headerFooterEditable: 'noEditable',
      prCont: false,
      isFont: true,
      isBasicOperation: true,
      isDelete, // 删除按钮操作状态
      isUnlocking, // 解锁按钮操作状态
      showValidateResult,
      viewEMRFlag: this.props.viewEMRFlag || 'Y', // 查看标志，查看时支持打印功能
    }

    return (
      <Spin tip={loadingTitle} spinning={spinLoading} delay={300} style={{ height: '100%' }}>
        <div style={{ height: this.props.clpHeader ? this.props.clpHeader : store.getState().tableHeight.y + 158 }} className="case-information-page case-information-page-hospital">
          <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', display: this.props.clpHeader ? 'none' : 'block' }}></div>
          <div style={{ width: "260px", height: 'calc(100% - 6px)', display: 'inline-block', overflow: 'hidden', paddingRight: '6px', position: 'relative' }}>
            <div style={{ width: '100%', padding: "8px 8px 0" }}>
              <Input
                style={{ width: '100%' }}
                value={templateName}
                onChange={this.handleTemplateNameChange}
                placeholder={this.setMessage('CaseInformationPageTemplate_name_query', 'descripts', '请输入模板名称查询')}
              />
            </div>
            <div
              style={{
                height: 'calc(100% - 42px)',
                paddingRight: '4px'
              }}
            >
              <Tree
                showIcon
                className="scroll-bar-style"
                style={{ height: '100%', paddingRight: '6px', overflow: 'auto' }}
                expandedKeys={expandedKeys}
                selectedKeys={selectedKeys}
                autoExpandParent={autoExpandParent}
                onExpand={this.handleRecordsExpand}
                onSelect={this.handleRecordsSelect}
                onDoubleClick={this.handleRecordsDoubleClickTreeNodes}
              >
                {this.renderTreeNodes(treeData)}
              </Tree>
            </div>
            <div style={{ position: 'absolute', right: '0', top: '0', width: '6px', background: 'rgba(240, 242, 245, 1)', height: '100%' }}></div>
          </div>
          <div style={{ width: 'calc(100% - 260px)', position: 'relative', height: 'calc(100% - 6px)', overflow: 'hidden', display: 'inline-block' }} >
            <Tabs
              hideAdd
              style={{ height: '100%' }}
              type="editable-card"
              className="record-tabs"
              activeKey={recordActiveKey}
              onEdit={this.onEdit}
              onChange={this.handleRecordChange}
            >
              {panes && Array.isArray(panes) && panes.length > 0 ? panes.map((pane, index) => {
                return (
                  <TabPane tab={pane.title} key={pane.key} style={{ height: recordActiveKey === pane.key ? '100%' : '0px' }} closable={pane?.closable === 'N' ? false : true}>
                    {pane.treeType === 'NurseTEMPLATE' ? ( // 新护理记录单走表单不走病历
                      <div style={{ height: '100%', padding: '12px', paddingBottom: 0 }}>
                        <PublicTableEditable
                          _key={pane?.key || (index + 1)}
                          admID={this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : '')}
                          versionID={pane?.versionID || pane?.releaseVersion || ''}
                          // rowClickFlag="Y"
                          viewEMRFlag={this.props.viewEMRFlag || 'N'}
                          tooltipFlag={this.props.tooltipFlag || 'N'}
                          operationFlag={this.props.operationFlag || 'N'}
                          operationFixed="right"
                          operationBtnFlag={this.props.operationBtnFlag || 'N'}
                          loading={recordSheetLoading}
                          tableRenderType={pane?.tableRenderType || 'native'}
                          // columns={pane?.columns || recordSheetColumns}
                          totalWidth={pane?.totalWidth || recordSheetTotalWidth}
                          maxHeight={this.props.clpHeader ? (parseInt(this.props.clpHeader) - 140) : store.getState().tableHeight.y + 18}
                          onRef={ref => this['tableEditableRef' + (pane?.key || (index + 1))] = ref}
                          handleSave={this.handleRecordSheetSave}
                          handlePrint={() => this.handleRecordSheetSave(this.handleRecordSheetPrint)}
                          handleSelectPrint={this.handleSaveBeforeSelectPrint}
                          handleViewEMR={this.props.handleViewEMR || null}
                        />
                      </div>
                    ) : (
                      <div style={{ height: '100%' }}>
                        <ElectronicCaseTemplate
                          param={param}
                          onRef={pane && pane.onRef ? pane.onRef : this.handleCaseTemplateRef}
                          handleSave={this.handleSave}
                          undoDeleted={this.undoDeleted}
                          // handleDelete={this.deletePatientHistory}
                          getKnowledgeBaseTreeData={this.getChildKnowledgeBaseTreeData}
                          handleExampleTemplate={this.handleExampleTemplate}
                          handleExampleknow={this.handleExampleknow}
                          handleReload={this.handleOk}
                          handleViewEMR={this.props.handleViewEMR || null}
                          handleOnReload={modalRowData && modalRowData.ID ? () => this.getPatienHistoryData(treeSelectData, modalRowData, modalRowData && modalRowData.flag ? modalRowData.flag : '') : ''} // goDoctorAdviceStepPage
                          editorID={this.props.editorID ? (pane && pane.key ? (this.props.editorID + '_' + pane.key) : '') : (pane && pane.key ? ('CIHWriterControl_' + pane.key) : '')}
                          handleSaveTheInsertedCourse={this.handleSaveTheInsertedCourse} // 保存插入的病程记录
                          updateMedicalRecordLockStatus={() => this.updateMedicalRecordLockStatus(modalRowData && modalRowData.patEMRRecordID ? modalRowData.patEMRRecordID : eMRRecordID, "forceUnlock")}
                        />
                      </div>
                    )}
                  </TabPane>
                )
              }) : (
                <TabPane tab="暂无数据" key='0' style={{ height: '100%' }} closable={false}>
                  <Empty style={{ paddingTop: '120px' }} description="暂无数据，请选择左侧模板" />
                </TabPane>
              )}
            </Tabs>
          </div>
          <Modal
            title="病历模板"
            visible={visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            style={{ minWidth: '680px' }}
          >
            <div style={{ display: "flex", alignItems: "center", padding: "24px 12px", paddingTop: 0 }}>
              病历模板：<Input allowClear placeholder="支持模板名称或首拼检索（Enter）" style={{ width: "300px" }} value={templateValue} onChange={this.handleTemplateValue} onPressEnter={this.handleTemplateValuePressEnter} />
              <Button style={{ marginLeft: "12px" }} type="primary" onClick={this.handleTemplateValuePressEnter}>查询</Button>
            </div>
            <div style={{ height: "400px" }}>
              <PubilcTablePagination
                handelThis={this}
                param={{
                  // 表头配置
                  columns: this.columns,
                  // 表格数据
                  data: modalTemplateData,
                  // 表格的宽度
                  x: 450,
                  y: 360,
                  height: "360px",
                  loading: false,
                  isOnRow: true,
                  rowClassName: true
                }}
                onRef={this.commonTableRef}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          </Modal>
          <ColumnAuthoritysModel
            clientWidth="800px"
            compontName="CaseInformationPageHospital"
            configType="C"
            onRef={this.onMainColumnRef}
            reloadData={this.getChineseAndEnglishData}
          />
        </div>
      </Spin>
    )
  }
};

export default ViewingMedicalRecords;