// 患者病历预览
import React, { Component } from 'react';
import {Card, Row, Col, Input, Select, Button, Table, Switch, message, Popconfirm, Modal, notification} from 'antd';
import { $http } from 'containers/config/https';
// import { handleExcel } from 'tools/handleExcel.js';
import store from 'store';
import Moment from 'moment';
import { dayFormat, Util } from 'tools/index';
import iconListvisits from 'assets/images/icon_listvisits.png';
import CommonPagination from 'components/pagination/index';
import RangeDatePicker from 'components/rangePicker/index';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CaseInformationPage from 'pages/workstation/component/CaseInformationPage.jsx';
import CaseInformationPageHospital from 'pages/workstation/component/CaseInformationPageHospital.jsx';

const { Option } = Select;

class PreviewOfPatientsMedicalRecord extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      patientColumns: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 50,
      patientWidth: 0,
      basicHeight: 0,
      loading: false,
      patMessage: undefined, // 人员标识
      medicalNo: undefined, // 住院号
      bedID: undefined, // 床号
      locID: userData && userData.locID ? userData.locID : undefined, // 科室名称
      locSelectData: [],
      bedData: [],
      medicalRecordTemplateSelectData: [],
      medicalRecordTemplateID: undefined,
      rowId: "",
      rowRow: {},
      admStatusCode: undefined, // 患者类型
      admStatusSelectData: [],
      admTypeSelectData: [],
      admissionDate: undefined,
      dateFrom: undefined,
      dateTo: undefined,
      admSTDate: undefined,
      admSPDate: undefined,
      locType: "O^I^E^W^OI^OP",
      admStatusAble: false,
      bedIDAble: false,
      medicalNoAble: false,
      isSubmit: "ALL",
      submitSelectData: [],
      locDocData: [],
      admDocID: undefined, // 主管医生
      docNameAble: false,
      currentEMRStatus: '',// 病历状态
      btnStatus: 'N', //审核。归档按钮状态
      backOffBtnStatus: "N",//退回按钮状态 
      visible: false,//病案号输入框
      admMedicalNo: '', //病案号
      btnTips: "",
      backOffBtnTips: "",
      selectedRowKeys: [],  //选中行集合
      qualityControlFormData: [], // 质控表单
      copyQualityControlFormData: [],
      qualityControlRowData: {},
      oualityControlType: 'add', // 弹窗类型
      exportStatus:'' , //导出状态
    };

    this.detailColumns = [
      {
        key: 1,
        title: '输入域编码',
        dataIndex: 'internalCode',
        align: 'center',
        width: "220px"
      }, {
        key: 2,
        title: '输入域名称',
        dataIndex: 'fieldName',
        align: 'center',
        width: "200px"
      }, {
        key: 3,
        title: '输入域值',
        dataIndex: 'fieldData',
        align: 'center',
      }
    ];
    this.myRef1 = React.createRef();
  }

  componentDidMount() {
    this.setState({ basicHeight: document.getElementById("patient-medical-record-inquiry-basic").clientHeight }, () => {
      setTimeout(() => {
        this.myRef1 && this.myRef1.current && this.myRef1.current.focus();
      }, 300)
    });
    const sessionObj = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
    const ipconfigObj = React.$getSessionData('ipConfig');
    this.setState({ sessionObj, ipconfigObj });
    this.getAdmTypeSelect();
    this.getPatAdmStatus();
    this.getEMRStatusSelect();
    this.getPatientColumns();
    this.initDefaultValue()
    this.handleQuery();
    this.loadBedData();
    this.getMedicalRecordTemplateSelectData();
    this.getQualityControlFormData();
  }

  //获取就诊类型下拉框
  getAdmTypeSelect = () => {
    let data = {}
    $http.post('urlS', this, {
      code: '03050088',
      data: data,
      success: function (res) {
        if (res.errorCode == 0) {
          this.setState({
            admTypeSelectData: res.result.Data
          })
        }
      }
    })
  }

  /**查询患者就诊状态数据 */
  getPatAdmStatus = () => {
    let data = { params: [{}] }
    $http.post('urlS', this, {
      code: '06080006',
      data: data,
      success: function (res) {
        if (res.errorCode == 0) {
          this.setState({
            admStatusSelectData: res.result.data
          })
        }
      }
    })
  }

  /**
   * 查询病历状态下拉框
   */
  getEMRStatusSelect = () => {
    let data = {}
    $http.post('urlS', this, {
      code: '06080005',
      data: data,
      success: function (res) {
        if (res.errorCode == 0) {
          this.setState({
            submitSelectData: res.result.data
          })
        }
      }
    })
  }

  //查询默认数据
  initDefaultValue = () => {
    let data = {
      params: [{
        defaultAppObj: {
          EMRBaseConfiger: ["PreviewOfPatEMRLocType", "PreviewOfPatEMRDefStatus", "PreviewOfPatAdmDefStatus"],
        }
      }]
    }
    $http.post('urlS', this, {
      code: "04110023",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          const regex = /@/g;
          this.setState({
            // defaultValueObj: res.result,
            locType: res.result.PreviewOfPatEMRLocType ? (res.result.PreviewOfPatEMRLocType.replace(regex, '^')) : this.state.locType,
            isSubmit: res.result.PreviewOfPatEMRDefStatus ? (res.result.PreviewOfPatEMRDefStatus.replace(regex, '^')) : this.state.isSubmit,
            admStatusCode: res.result.PreviewOfPatAdmDefStatus ? (res.result.PreviewOfPatAdmDefStatus.replace(regex, '^')) : this.state.admStatusCode,
          }, () => {
            this.getLocSelectData();
          })
        }
      }
    })
  }

  // 获取病历模板下拉数据
  getMedicalRecordTemplateSelectData = () => {
    var params = {
      params: [{
        findTemp: "RELEASED"
      }]
    }
    $http.post('urlDeault', this, {
      code: "06050018",
      data: params,
      success: function (res) {
        if (+res.errorCode === 0) {
          let medicalRecordTemplateSelectData = res.result && res.result.data.length > 0 ? res.result.data : [];
          let medicalRecordTemplateID = medicalRecordTemplateSelectData && medicalRecordTemplateSelectData.length > 0 ? medicalRecordTemplateSelectData[0].id : undefined;
          this.setState({
            medicalRecordTemplateSelectData,
            medicalRecordTemplateID
          })
        }
      }
    });
  }

  //获取护理分组
  getLocSelectData = () => {
    let { userData, locType, locID } = this.state;
    let data = {
      params: [{
        hospID: userData && userData.hospID ? userData.hospID : "",
        type: locType,
        docFlag: "1",
      }]
    }
    $http.post('urlS', this, {
      code: "04020008",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let locSelectData = res.result && res.result.Data && res.result.Data.length > 0 ? res.result.Data : [];
          let allLocID = [];
          let locDoctor = [];
          let existUserLocIDFlag = false
          for (var i = 0; i < locSelectData.length; i++) {
            allLocID.push(locSelectData[i].id);
            if (locSelectData[i].code === "zhybek" || locSelectData[i].code === "zhybyk") {
              locDoctor = locDoctor.concat(locSelectData[i].locDoctor)
            }
            if ((!existUserLocIDFlag) && (locSelectData[i].id === locID)) { existUserLocIDFlag = true }
          }
          let allLoc = {
            id: "all",
            descripts: "全部",
            descriptsSPCode: "qu",
            allLocID,
            locTypeCode: "I",
            locTypeDesc: "住院",
            locDoctor: Util.unique(locDoctor, "id")
          }
          // console.log(allLoc)
          locID = existUserLocIDFlag ? locID : (locSelectData.length > 0 ? locSelectData[0].id : undefined)
          locSelectData.unshift(allLoc);
          this.setState({
            locSelectData,
            locID: locID,
          }, () => {
            this.handleLocIDChange(locID ? locID : "")
          })
        } else {
          this.setState({ locSelectData: [] })
        }
      }
    })
  }

  loadBedData = () => {
    let { locID } = this.state;
    if (!locID) return;
    var params = {
      params: [{
        locID, // userData && userData.locID ? userData.locID : ""
      }]
    }
    $http.post('urlDeault', this, {
      code: "03060005",
      data: params,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            bedData: res.data
          })
        }
      }
    });
  }

  // 获取患者表头数据
  getPatientColumns = () => {
    let data = {
      params: [{
        compontName: "PreviewOfPatEMRPatList",
        type: "C",
      }]
    }
    $http.post('urlDeault', this, {
      code: "01040073",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          var columns = res.result.C;
          var dynColumns = []
          for (var i = 0; i < columns.length; i++) {
            dynColumns.push({
              title: columns[i].title,
              dataIndex: columns[i].dataIndex,
              width: parseInt(columns[i].width),
              align: columns[i].align || 'center'
            })
          }
          this.setState({
            patientColumns: dynColumns,
            patientWidth: res.totalWidth
          })
        }
      }
    })
  }

  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

  // 查询条件 --- 人员标识
  handlePatMessageChange = e => {
    this.setState({ patMessage: e.target.value })
  }

  // 查询条件 --- 住院号
  handleMedicalNoChange = e => {
    this.setState({ medicalNo: e.target.value })
  }

  // 病案号
  handleAdmMedicalNoChange = e => {
    this.setState({ admMedicalNo: e.target.value })
  }

  // 查询条件 --- 床号
  handleBedIDChange = e => {
    this.setState({ bedID: e }, () => {
      this.handleQuery();
    })
  }

  // 查询条件 --- 主管医生
  handleAdmDocChange = e => {
    this.setState({ admDocID: e }, () => {
      this.handleQuery();
    })
  }

  // 查询条件 --- 科室名称
  handleLocIDChange = e => {
    let locTypeCode = ""
    let { locSelectData, locDocData, admDocID } = this.state
    let selLocDocData = []
    let selectLocAry = locSelectData.filter((item, index) => (item.id === e))
    if (selectLocAry.length > 0) {
      locTypeCode = selectLocAry[0].locTypeCode
      selLocDocData = selectLocAry[0].locDoctor
    }
    this.setState({
      locID: e,
      // admStatusCode: undefined, 
      admDocID: undefined,
      admStatusAble: ((locTypeCode !== "W") & (locTypeCode !== "I")) ? true : false,
      bedIDAble: ((locTypeCode !== "W") & (locTypeCode !== "I")) ? true : false,
      medicalNoAble: ((locTypeCode !== "W") & (locTypeCode !== "I")) ? true : false,
      locDocData: selLocDocData
    }, () => {
      this.handleQuery();
      this.loadBedData();
    })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  getAllLocID = () => {
    let { locSelectData, locID } = this.state;
    let allLocID = [];
    for (var i = 0; i < locSelectData.length; i++) {
      if (locSelectData[i].id === locID) {
        allLocID = locSelectData[i].allLocID;
      }
    }
    return allLocID;
  }

  // 获取患者列表数据
  getTableData = (isRefresh) => {
    this.setState({ loading: true });
    let { admTypeCode, userData, patMessage, bedID, medicalNo, locID, admStatusCode, page, pageSize, admissionDate, dateFrom, dateTo, admSTDate, admSPDate, isSubmit, admDocID } = this.state;
    let data = {
      params: [{
        admTypeCode: admTypeCode,
        locID: locID === "all" ? this.getAllLocID() : locID, // userData && userData.locID ? userData.locID : "",
        // userID: 164, // userData && userData.userID ? userData.userID : "",
        hospID: userData && userData.hospID ? userData.hospID : "",
        patMessage,
        bedID,
        medicalNo,
        admStatusCode,
        admissionDate: admissionDate ? Moment(admissionDate).format('YYYY-MM-DD') : undefined,
        dateFrom: admStatusCode === 'D' ? dateFrom : '',
        dateTo: admStatusCode === 'D' ? dateTo : '',
        admSTDate: admStatusCode !== 'D' ? admSTDate : '',
        admSPDate: admStatusCode !== 'D' ? admSPDate : '',
        IsSubmit: isSubmit,
        purpose: "PreviewPatRecord",
        componentCode: "PreviewOfPatEMRPatList", // 组件名称
        admDocID
      }],
      pagination: [{
        pageSize,
        currentPage: page
      }]
    }
    $http.post('urlDeault', this, {
      code: "06080002",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          if (isRefresh === "noRefresh") {
            this.setState({ // 一键提交后不更新选中数据
              tableData: res.result.data,
              total: res.result.totalCount,
              loading: false
            })
          } else {
            this.setState({
              tableData: res.result.data,
              total: res.result.totalCount,
              rowId: "",
              rowRow: {},
              selectedRowKeys: [],
              loading: false
            })
          }
        } else {
          this.setState({
            tableData: [],
            total: 0,
            rowId: "",
            rowRow: {},
            selectedRowKeys: [],
            loading: false
          })
        }
      },
      error: function () {
        this.setState({ loading: false })
      }
    });
  };

  //延时执行
  sleep = (millisecond) => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, millisecond)
    })
  };

  // 导出
  exportFun = async () => {
    //导出状态
    this.setState({
      exportStatus: true,
      loading: true
    });
    let { sessionObj, ipconfigObj } = this.state;
    let { admTypeCode, userData, patMessage, bedID, medicalNo, locID, admStatusCode, page, pageSize, admissionDate, dateFrom, dateTo, admSTDate, admSPDate, isSubmit, admDocID } = this.state;
    let data = {
      params: [{
        queryParams: {
          params: [{
            admTypeCode: admTypeCode,
            locID: locID === "all" ? this.getAllLocID() : locID, // userData && userData.locID ? userData.locID : "",
            // userID: 164, // userData && userData.userID ? userData.userID : "",
            hospID: userData && userData.hospID ? userData.hospID : "",
            patMessage,
            bedID,
            medicalNo,
            admStatusCode,
            admissionDate: admissionDate ? Moment(admissionDate).format('YYYY-MM-DD') : undefined,
            dateFrom: admStatusCode === 'D' ? dateFrom : '',
            dateTo: admStatusCode === 'D' ? dateTo : '',
            admSTDate: admStatusCode !== 'D' ? admSTDate : '',
            admSPDate: admStatusCode !== 'D' ? admSPDate : '',
            IsSubmit: isSubmit,
            purpose: "PreviewPatRecord",
            componentCode: "PreviewOfPatEMRPatList", // 组件名称
            admDocID
          }],
          code: '06080002',
          pagination: [{
            pageSize,
            currentPage: page
          }],
          session: [{
            userID: sessionObj.userID,
            locID: sessionObj.locID,
            groupID: sessionObj.groupID,
            hospID: sessionObj.hospID,
            sessionID: sessionObj.sessionID,
            hospCode: sessionObj.hospCode,
            language: sessionObj.language,
            hostName: ipconfigObj?.hostName || '',
            ipv4: ipconfigObj?.ipv4 || '',
            ipv6: ipconfigObj?.ipv6 || '',
            mac: ipconfigObj?.mac || ''
          }]
        },
        queryCode: '06080002',
        componentCode: 'PreviewOfPatEMRPatList'
      }],
      pagination: [{
        pageSize,
        currentPage: page
      }],
      session: [{
        userID: sessionObj.userID,
        locID: sessionObj.locID,
        groupID: sessionObj.groupID,
        hospID: sessionObj.hospID,
        sessionID: sessionObj.sessionID,
        hospCode: sessionObj.hospCode,
        language: sessionObj.language,
        hostName: ipconfigObj?.hostName || '',
        ipv4: ipconfigObj?.ipv4 || '',
        ipv6: ipconfigObj?.ipv6 || '',
        mac: ipconfigObj?.mac || ''
      }]
    };
    await this.sleep(1000); //延时，按钮效果
    const resObj = await React.$asyncPost(this, "11020007", data);
    if (resObj) {
      let errorCode = resObj.errorCode;
      if (+errorCode === 0) {
        let downLoadUrl = resObj.result.downloadURL;
        //异步--消息提醒
        if (downLoadUrl === '') {
          this.exportNotification(); //提示栏
          store.dispatch({
            type: 'downloadTask',
            value: {
              timeStamp: new Date().getTime(),
              startDate: Moment(new Date()).format('YYYY-MM-DD'),
              endDate: Moment(new Date()).format('YYYY-MM-DD'),
            }
          })
        } else { //同步-直接取到链接后下载
          window.open(downLoadUrl, '_parent')
        }

        this.setState({
          exportStatus: false,
          loading: false
        });
      } else {
        this.setState({
          exportStatus: false,
          loading: false
        });
        message.error(resObj.errorMessage)
      }
    }
  };

  //右上角提示栏
  exportNotification = () => {
    const msgValue = (<p>数据正在导出，导出完成后可在右上角<span style={{ color: 'red' }}>↗</span><span style={{ fontWeight: 'bold' }}>【导出任务列表】</span>中下载</p>);
    notification.info({
      message: '导出中..',
      description: msgValue,
      placement: 'topRight',
      style: {
        top: 30,
      },
    });
  };

  // 患者列表 -- 条数改变的回调
  handleLeftShowSizeChange = (current, size) => {
    this.setState({ page: 1, pageSize: size }, () => {
      this.getTableData();
    });
  }

  // 患者列表 -- 页码改变的回调
  handleLeftChange = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    });
  }

  // 操作行 --- 患者列表
  onClickRowPublic = (record) => {
    const selectedRowKeys = [...this.state.selectedRowKeys];
    return {
      // 单击行选中，可加入多选集合中
      onClick: () => {
        /**只有提交状态可多选审核 */
        if (this.state.userData.groupDesc.indexOf("医师") > -1 ? record?.EMRStatusedCode === 'F' : record?.EMRStatusedCode === 'A') {
          if (selectedRowKeys.indexOf(record.admID) >= 0) {
            selectedRowKeys.splice(selectedRowKeys.indexOf(record.admID), 1)
          } else { selectedRowKeys.push(record.admID) }
          this.setState({ selectedRowKeys: selectedRowKeys })
        }
        if (this.state.rowId === '') {
          // 保存行数据以及ID
          this.setState({
            rowId: record.admID,
            rowRow: record,
          }, () => {
            this.getPatEMRCurrentStatus();
            this.getPatEMRCurrentStatus('R');
            this.setPatientData();
          })
        } else {
          if (this.state.rowId !== record.admID) {
            this.setState({
              rowId: record.admID,
              rowRow: record,
            }, () => {
              this.getPatEMRCurrentStatus();
              this.getPatEMRCurrentStatus('R');
              this.setPatientData();
            })
          }
        }
      }
      // 双击
    }
  }

  setPatientData = () => {
    let { rowRow } = this.state;
    var patientData = {
      admID: rowRow?.admID,
      patID: rowRow?.patID,
    }
    sessionStorage.setItem('patientData', JSON.stringify(patientData));
  }

  getPatEMRCurrentStatus = (statusCode) => {
    var findStatusCode = statusCode;
    if (statusCode == undefined) {
      if (this.state.userData.groupDesc.indexOf("医师") > -1) {
        findStatusCode = "A"
      } else {
        findStatusCode = "AR"
      }
    }
    let { rowId } = this.state;
    if (!rowId) return;
    let data = {
      params: [{
        statusCode: findStatusCode,
        admID: rowId,
      }]
    }
    $http.post('urlS', this, {
      code: "06050025",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          if (statusCode != undefined) {
            this.setState({
              currentEMRStatus: res.result.currentStatusCode,// 病历状态 
              backOffBtnStatus: res.result.btnStatus,//退回按钮状态 
              backOffBtnTips: res.result.tips,//退回按钮状态 
            })
          } else {
            this.setState({
              currentEMRStatus: res.result.currentStatusCode,// 病历状态 
              btnStatus: res.result.btnStatus, //审核。归档按钮状态
              btnTips: res.result.tips,//退回按钮状态 
            })
          }
        }
      }
    })
  }

  setRowClassNamePublic = (record) => {
    return record.admID === this.state.rowId ? 'clickRowStyle' : "";
  }

  handleAdmTypeCodeChange = e => {
    this.setState({
      admTypeCode: e,
      admStatusAble: (e !== "I") ? true : false, bedIDAble: (e !== "I") ? true : false, medicalNoAble: (e !== "I") ? true : false
    }, () => {
      this.handleQuery();
    })
  }

  handleAdmStatusCodeChange = e => {
    this.setState({ admStatusCode: e }, () => {
      if (e === "D") {
        message.info("请选择出院开始截至日期进行查询！！！", 2)
      } else {
        this.handleQuery();
      }
    })
  }

  handleAdmissionDateChange = e => {
    this.setState({ admissionDate: e })
  }

  startChange = (e) => {
    this.setState({
      dateFrom: e ? Moment(e).format(dayFormat) : ''
    })
  }

  handleAdmSTDStartChange = (e) => {
    this.setState({
      admSTDate: e ? Moment(e).format(dayFormat) : ''
    })
  }

  endChange = (e) => {
    this.setState({
      dateTo: e ? Moment(e).format(dayFormat) : ''
    })
  }

  handleAdmSTDEndChange = (e) => {
    this.setState({
      admSPDate: e ? Moment(e).format(dayFormat) : ''
    })
  }

  // 一键回退
  handleBackOff = async () => {
    let { rowId, copyQualityControlFormData } = this.state;
    if (!rowId) {
      message.info("请选择需要操作的患者！！！")
      return;
    }
    let data = {
      params: [{
        statusCode: "R",
        type: "ALL",
        admID: rowId,
      }]
    }
    $http.post('urlS', this, {
      code: "06050022",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          Modal.confirm({
            title: '一键退回成功',
            content: '您还可以对病历及长嘱/临嘱进行点评',
            okText: '去点评',
            cancelText: '稍后点评',
            onOk: () => {
              this.setState({ oualityControlType: 'add', qualityControlFormData: copyQualityControlFormData, qualityControlRowData: {} }, () => {
                this.modifyQualityControlVisible(true)
              })
            },
            onCancel: () => {
              this.getTableData();
              this.getPatEMRCurrentStatus();
              this.getPatEMRCurrentStatus("R");
            },
          });
        }
      }
    })
  }

  // 是否已提交
  handleIsSubmitChange = e => {
    this.setState({ isSubmit: e }, () => {
      this.handleQuery();
    })
  }

  //病历审核  【批量审核】
  handleAudit = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      message.info("请选择需要病历审核的患者！！！")
      return
    }
    let data = {
      params: [{
        statusCode: "A",
        admID: selectedRowKeys,
      }]
    }
    $http.post('urlS', this, {
      code: "06050024",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success(res.errorMessage);
          this.getPatEMRCurrentStatus();
          this.getPatEMRCurrentStatus("R");
          this.handleQuery();
        }
      }
    })
  }

  // 显示病案号输入框
  showModal = () => {
    this.setState({
      visible: true,
    })
  }

  // 隐藏病案号输入框
  hideModal = () => {
    this.setState({
      visible: false,
    })
  }

  //病历归档
  handleArchived = () => {
    // let { selectedRowKeys, admMedicalNo } = this.state;
    // if (!rowId) {
    //   message.info("请选择需要操作的患者！！！")
    //   return;
    // }
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      message.info('请选择需要病历审核的患者！！！')
      return
    }
    let data = {
      params: [{
        statusCode: 'AR',
        admID: selectedRowKeys,
        // admMedicalNo: admMedicalNo,
      }]
    }
    $http.post('urlS', this, {
      code: '06050024',
      data: data,
      success: function (res) {
        message.success(res.errorMessage);
        this.hideModal();
        if (+res.errorCode === 0) {
          this.getPatEMRCurrentStatus();
          this.getPatEMRCurrentStatus('R');
          /**刷新患者列表数据 */
          this.handleQuery();
        }
      }
    })
  }

  // 多选行操作修改
  onSelectChange = selectedRowKeys => {
    // let { tableData } = this.state
    // let newSelRowKeys = selectedRowKeys.filter((item) => {
    //   let flag = false
    //   for (let index = 0; index < tableData.length; index++) {
    //     const tabData = tableData[index]
    //     if (tabData.admID == item) {
    //       if (tabData.EMRStatusedCode === 'F' || tabData.EMRStatusedCode === 'A') { flag = true }
    //       break
    //     }
    //   }
    //   return flag
    // })
    this.setState({ selectedRowKeys });
  };

  handleCaseInformationPageHospitalRef = ref => {
    this.caseInformationPageHospitalChild = ref;
  }

  // 获取质控表单数据
  getQualityControlFormData = async () => {
    try {
      let res = await React.$asyncPost(this, '06090001');
      let qualityControlFormData = res?.data || res?.result || [];
      qualityControlFormData = qualityControlFormData && Array.isArray(qualityControlFormData) ? qualityControlFormData.map(item => {
        return {
          ...item,
          dataIndex: item?.code || '',
          typeCode: item?.value || 'TextArea',
          title: item?.descripts || '',
        }
      }) : [];
      this.setState({ qualityControlFormData, copyQualityControlFormData: JSON.parse(JSON.stringify(qualityControlFormData)) });
    } catch (error) {
      console.log(error)
    }
  }

  // 记录表单的值
  recordQualityControlFormInput = record => {
    this.setState({ mainSaveRecord: { ...this.state.mainSaveRecord, ...record } })
  }

  // 打开质控弹窗
  modifyQualityControlVisible = (visible, clearFlag) => {
    this.qualityControlRef && this.qualityControlRef.modifyVisible(visible, clearFlag);
  }

  // 确认点评
  handleQualityControlSave = async (values) => {
    try {
      const { qualityControlFormData, rowId } = this.state;
      let content = [];
      for (let i = 0; i < qualityControlFormData.length; i++) {
        let currentItem = qualityControlFormData[i];
        let currentItemID = currentItem?.id || '';
        let currentDataIndex = currentItem?.dataIndex || '';
        if (currentItemID && currentItem?.disabled !== 'Y') { // 备注名字不传入
          content.push({
            itemID: currentItemID && currentItemID.indexOf('_') > -1 ? currentItemID.split('_')[1] : currentItemID, // 字段ID
            comment: values && currentDataIndex && currentDataIndex in values ? values[currentDataIndex] : '', // 保存的值
          })
        }
      }
      let data = {
        params: [{
          admID: rowId,
          content
        }]
      }
      let res = await React.$asyncPost(this, '06090002', data);
      message.success(res?.errorMessage || '点评成功');
      this.modifyQualityControlVisible(false, 'Y')
    } catch (error) {
      console.log(error)
    }
  }

  // 查看点评内容
  handleViewQualityControl = async () => {
    try {
      const { rowId, copyQualityControlFormData } = this.state;
      let data = {
        params: [{
          admID: rowId,
        }]
      }
      let res = await React.$asyncPost(this, '06090003', data);
      let SDArr = res.result?.SDArr || [];
      let MRArr = res.result?.MRArr || [];
      let qualityControlFormData = [];
      if (SDArr && SDArr.length > 0 && MRArr && MRArr.length > 0) {
        qualityControlFormData.push({
          dataIndex: 'SD_commentUser',
          typeCode: 'Text',
          title: '',
          col: 12,
          labelCol: 5,
          wrapperCol: 18
        }, {
          dataIndex: 'MR_commentUser',
          typeCode: 'Text',
          title: '',
          col: 12,
          labelCol: 5,
          wrapperCol: 18
        });
      }
      let qualityControlRowData = {
        SD_commentUser: res.result?.SDUser || '',
        MR_commentUser: res.result?.MRUser || '',
      };
      for (let i = 0; i < copyQualityControlFormData.length; i++) {
        let currentItem = copyQualityControlFormData[i];
        let currentDataIndex = currentItem?.code || '';
        if (SDArr && SDArr.length > 0 && MRArr && MRArr.length > 0) {
          let SD_recordData = Util.returnDataCccordingToAttributes(SDArr, currentItem?.id || '', 'itemID');
          let MR_recordData = Util.returnDataCccordingToAttributes(MRArr, currentItem?.id || '', 'itemID');
          qualityControlRowData['SD_' + currentDataIndex] = SD_recordData?.comment || '';
          qualityControlRowData['MR_' + currentDataIndex] = MR_recordData?.comment || '';
          qualityControlFormData.push({
            ...currentItem,
            dataIndex: 'SD_' + currentDataIndex,
            disabled: SD_recordData.editFlag === 'Y' ? 'N' : 'Y',
            col: 12,
            labelCol: 5,
            wrapperCol: 18
          }, {
            ...currentItem,
            dataIndex: 'MR_' + currentDataIndex,
            disabled: MR_recordData.editFlag === 'Y' ? 'N' : 'Y',
            col: 12,
            labelCol: 5,
            wrapperCol: 18
          })
        } else {
          let recordData = Util.returnDataCccordingToAttributes(SDArr && SDArr.length > 0 ? SDArr : MRArr, currentItem?.id || '', 'itemID');
          qualityControlRowData[currentDataIndex] = recordData?.comment || '';
          qualityControlFormData.push({
            ...currentItem,
            disabled: recordData?.editFlag === 'Y' ? 'N' : 'Y',
          })
        }
      }
      console.log('qualityControlRowData', qualityControlFormData, qualityControlRowData)
      this.setState({ qualityControlFormData, qualityControlRowData, oualityControlType: (MRArr && MRArr.length > 0 && SDArr && SDArr.length > 0) ? 'view' : 'add' }, () => {
        this.modifyQualityControlVisible(true);
      })
    } catch (error) {
      console.log(error)
    }
  }

  /**
  * @ByShizi: 患者病历预览展示右侧引用内容
  * 需求 #广州番禺
  * Create 2021-12-15
  * */
  render() {
    let { patientColumns, tableData, total, page, basicHeight, loading, patMessage, medicalNo, bedID, locID, patientWidth, bedData, locSelectData, qualityControlFormData, qualityControlRowData,
      medicalRecordTemplateSelectData, rowId, rowRow, admStatusCode, admStatusSelectData, isSubmit, admTypeSelectData, submitSelectData, oualityControlType,
      admStatusAble, bedIDAble, medicalNoAble, docNameAble, locDocData, admDocID, selectedRowKeys
    } = this.state;

    // 床号
    var bedDataOption = []
    bedData && bedData.map((item, index) => {
      bedDataOption.push(<Option key={index} value={item.bedID} title={item.bedNo} seatchprop={item.bedNo}>
        {item.bedNo}
      </Option>)
    })

    // 
    var locOption = []
    locSelectData && locSelectData.map((item, index) => {
      locOption.push(<Option key={index} code={item.descriptsSPCode} value={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    //科室医生
    var locDocDataOption = []
    locDocData && locDocData.map((item, index) => {
      locDocDataOption.push(<Option key={index} code={item.descriptsSPCode} value={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    // 病历模板
    var medicalRecordTemplateOption = [];
    medicalRecordTemplateSelectData && medicalRecordTemplateSelectData.map((item, index) => {
      medicalRecordTemplateOption.push(<Option key={index} code={item.descriptsSPCode} value={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    // 就诊类型
    let admTypeOption = [];
    admTypeSelectData && admTypeSelectData.map((item, index) => {
      admTypeOption.push(<Option key={index} code={item.admCode} value={item.admCode} seatchprop={item.admDesc + '^' + item.descriptsSPCode} title={item.admDesc}>{item.admDesc}</Option>)
    })

    // 患者类型
    let admStatusOption = [];
    admStatusSelectData && admStatusSelectData.map((item, index) => {
      admStatusOption.push(<Option key={index} code={item.descriptsSPCode} value={item.code} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    // 提交状态
    let submitOption = [];
    submitSelectData && submitSelectData.map((item, index) => {
      submitOption.push(<Option key={index} code={item.descriptsSPCode} value={item.code} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    //多选行
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => {
        return {
          disabled: this.state.userData.groupDesc.indexOf("医师") > -1 ? !(record?.EMRStatusedCode === 'F') : !(record?.EMRStatusedCode === 'A'),
        }
      },
    }

    return (
      <div className="patient-medical-record-inquiry">
        <div id="patient-medical-record-inquiry-basic" style={{ padding: '12px', paddingTop: 0 }}>
          科室：
          <Select value={locID} onChange={this.handleLocIDChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" style={{ width: '130px', margin: '12px 10px 0 0' }}>
            {locOption}
          </Select>
          患者类型：
          <Select value={admStatusCode} onChange={this.handleAdmStatusCodeChange}
            disabled={admStatusAble}
            showSearch optionFilterProp="seatchprop" allowClear placeholder="类型" style={{ width: '80px', margin: '12px 10px 0 0' }}>
            {admStatusOption}
          </Select>
          床号：
          <Select value={bedID} onChange={this.handleBedIDChange}
            disabled={bedIDAble}
            showSearch optionFilterProp="seatchprop" allowClear placeholder="床号" style={{ width: '80px', margin: '12px 10px 0 0' }}>
            {bedDataOption}
          </Select>
          住院号：
          <Input value={medicalNo} allowClear
            disabled={medicalNoAble}
            onChange={this.handleMedicalNoChange}
            placeholder='请输入'
            onPressEnter={this.handleQuery}
            style={{ width: '100px', margin: '12px 10px 0 0' }}
          />
          人员标识：
          <Input value={patMessage} allowClear
            onChange={this.handlePatMessageChange}
            ref={this.myRef1}
            onPressEnter={this.handleQuery}
            placeholder='请输入'
            style={{ width: '120px', margin: '12px 10px 0 0' }}
          />
          主管医生：
          <Select value={admDocID} onChange={this.handleAdmDocChange}
            disabled={docNameAble}
            showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" style={{ width: '100px', margin: '12px 10px 0 0' }}>
            {locDocDataOption}
          </Select>
          {admStatusCode !== 'D' ? (<div style={{ display: 'inline-block', margin: '12px 10px 0 0' }}>
            <RangeDatePicker label={'就诊(入院)日期：'} format='YYYY-MM-DD' width='270px'
              startChange={this.handleAdmSTDStartChange} endChange={this.handleAdmSTDEndChange} />
          </div>) : ""}
          {admStatusCode === 'D' ? (<div style={{ display: 'inline-block', margin: '12px 10px 0 0' }}>
            <RangeDatePicker label={'出院日期：'} format='YYYY-MM-DD' width='270px'
              startChange={this.startChange} endChange={this.endChange} />
          </div>) : ""}
          <div style={{ display: "inline-block" }}>
            状态：
            <Select mode="multiple" value={isSubmit} onChange={this.handleIsSubmitChange}
              showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" style={{ width: '300px', margin: '8px 10px 0 0' }}>
              {submitOption}
            </Select>
            <Button type="primary" style={{ marginTop: '8px' }} onClick={this.handleQuery}>查询</Button>
            {
              this.state.userData.groupDesc.indexOf("医师") > -1
                ? <Button ghost type="primary" style={{ marginTop: '12px', marginLeft: "10px" }} title={this.state.btnTips} disabled={this.state.btnStatus != "Y"} onClick={this.handleAudit}>审核</Button>
                : (<Popconfirm title="归档后将不允许再操作病历，确定归档吗?" onConfirm={this.handleArchived} disabled={this.state.btnStatus != "Y"}>
                  <Button ghost title={this.state.btnTips} type="primary" style={{ marginTop: '12px', marginLeft: "10px" }} disabled={this.state.btnStatus != "Y"}>归档</Button>
                </Popconfirm>)
            }
            <Popconfirm title="一键退回后所有病历将打回给医生，确定一键退回吗?" onConfirm={this.handleBackOff} disabled={this.state.backOffBtnStatus != "Y"}>
              <Button ghost type="danger" title={this.state.backOffBtnTips} style={{ marginTop: '12px', marginLeft: "10px" }} disabled={this.state.backOffBtnStatus != "Y"}>一键回退</Button>
            </Popconfirm>
          </div>
          <Button type="primary" disabled={this.state.tableData.length===0} style={{ marginTop: '8px',marginLeft:'10px' }} onClick={this.exportFun}>{this.state.exportStatus === true ? '导出中' : '导出'}</Button>
        </div>
        <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
        <Row>
          <Col span={4}>
            <div style={{ paddingRight: '6px', position: 'relative' }}>
              <Card
                size="small"
                title={<div className="card-title-left-img" style={{ height: '26px' }}><img src={iconListvisits} alt="" />患者列表</div>}
                extra={(
                  <div>
                    <span
                      style={{
                        color: !(rowId && (rowRow?.EMRQCFlag === 'Y' || rowRow?.EMRStatusedCode === 'F')) ? '#999' : '',
                        cursor: !(rowId && (rowRow?.EMRQCFlag === 'Y' || rowRow?.EMRStatusedCode === 'F')) ? 'no-drop' : 'pointer'
                      }}
                      className="span"
                      onClick={rowId && (rowRow?.EMRQCFlag === 'Y' || rowRow?.EMRStatusedCode === 'F') ? this.handleViewQualityControl : null}
                    >
                      查看点评
                    </span>
                  </div>
                )}
              >
                <div>
                  <Table
                    loading={loading}
                    columns={patientColumns && patientColumns.length > 0 ? patientColumns : []}
                    dataSource={tableData}
                    style={{ height: store.getState().tableHeight.y + 131 - basicHeight + 'px', }}
                    scroll={{ x: patientWidth, y: store.getState().tableHeight.y + 85 - basicHeight }}
                    rowSelection={rowSelection}
                    onRow={this.onClickRowPublic}
                    rowClassName={this.setRowClassNamePublic}
                    onHeaderRow={() => {
                      return {
                        onDoubleClick: () => {
                          this.columnRef.onOpenModel();
                        },
                      };
                    }}
                    bordered
                    rowKey={(data) => {
                      return data.admID
                    }}
                    pagination={false}
                    className="table-body-height"
                  />
                  <CommonPagination
                    pageSizeChange="N"
                    // totalFlag="N"
                    size='small'
                    search="search"
                    pageSize="50"
                    total={total}
                    current={page}
                    complete={false}
                    loading={loading}
                    dataSource={tableData}
                    onShowSizeChange={this.handleLeftShowSizeChange}
                    onChange={this.handleLeftChange}
                  />
                </div>
              </Card>
              <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
            </div>
          </Col>
          <Col span={20}>
            {rowId && rowRow && rowRow.admTypeCode == 'I' ? <CaseInformationPageHospital
              hideTabs={true}
              onRef={this.handleCaseInformationPageHospitalRef}
              editorID="POfPMRWriterControlHospital"
              isBasicOperation={false}
              prCont="Y"
              // caseInformationPageTabs="N"
              isDidUpdate="Y"
              historyAdmID={rowId}
              locID={rowRow && rowRow.locID ? rowRow.locID : locID}
              fGroup="previewEMRRec"
              componentSource="PreviewOfPatientsMedicalRecord" // 组件来源
              clpHeader={store.getState().tableHeight.y + 241 - basicHeight - 4 + 'px'}
              // isOperable="N"
            /> : (rowId && rowRow && rowRow.admTypeCode == 'O' ? <CaseInformationPage
              editorID="POfPMRWriterControl"
              isBasicOperation={true}
              caseInformationPageTabs="N"
              isDidUpdate="Y"
              historyAdmID={rowId}
              locID={rowRow && rowRow.locID ? rowRow.locID : locID}
              fGroupTempByInfo="previewEMRRec"
              fGroup="previewEMRRec"
              componentSource="PreviewOfPatientsMedicalRecord"
              clpHeader={store.getState().tableHeight.y + 241 - basicHeight - 4 + 'px'}
              isOperable="Y"
            /> : "")}
          </Col>
        </Row>
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName="PreviewOfPatEMRPatList"
          configType="C"
          onRef={this.onColumnRef}
          reloadData={this.getPatientColumns}
        />

        {/* 病案号录入 */}
        <Modal
          title="请输入病案号"
          visible={this.state.visible}
          onOk={this.handleArchived}
          onCancel={this.hideModal}
        >
          <div style={{ display: 'flex', flexDirection: 'row' }}>
            <div style={{ height: "32px", lineHeight: "32px" }}>病案号:</div><Input
              value={this.state.admMedicalNo}
              onChange={this.handleAdmMedicalNoChange}
              placeholder='请输入病案号'
              style={{ width: '400px' }} />
          </div>
        </Modal>

        {/* 主表新增弹窗 */}
        <PublicModalFormHooks
          title="病历质控"
          width={oualityControlType === 'view' ? '1200px' : '800px'}
          onRef={ref => this.qualityControlRef = ref}
          formData={qualityControlFormData}
          rowData={qualityControlRowData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          recordFormInput={this.recordQualityControlFormInput}
          handleSave={this.handleQualityControlSave}
        />
      </div>
    );
  }
}

export default PreviewOfPatientsMedicalRecord;