<template>
  <div ref="editorMainRef">
    <div v-if="tiShiBiaoTi?.length > 0" class="editor__title">
        <span v-for="item in tiShiBiaoTi">
            {{ item }}
        </span>
    </div>
    <div class="ribbon">
      <button @click="qingKong">清空工作台</button>
      <button @click="toAddAnOrder">录入医嘱</button>
      <button @click="duplicateAndPaste">复制并粘贴</button>
      <button @click="openTheOrderPopUpWindow">打开医嘱弹窗</button>
    </div>
    <div class="editing_area"
         ref="editingAreaRef"
         :style="{color: isEdit ? '#0014fc' : ''}">
      <div class="yz_editor__disable" v-if="isEdit"></div>
      <div class="yz_input__box">
        <div>
          医嘱名称：
          <xc-combo-grid
              style="width: 240px"
              ref="searchRef"
              :disabled="isEdit"
              v-model="yiZhuData.orderName"
              :table-header="tableHeader"
              :query-data-func="searchOrders"
              :current-key="yiZhuData.orderCode + yiZhuData.orderName"
              @rowClick="xuanZhongFeiYong">
            <el-table-column label="说明书" fixed="left">
              <template #default="{row}">
                <el-button @click.stop="drugManual.open(row.orderCode,row.serial)"
                           :disabled="row.groupNo === '00'">
                  说明书
                </el-button>
              </template>
            </el-table-column>
          </xc-combo-grid>
        </div>
        <div class="input__style">
          {{ yiZhuData.drugSpecification }}
        </div>
        <div>
          频率:
          <xc-select-v3 style="width: 120px"
                        @rowClick="pingLvRowClick"
                        :disabled="queryParam.frequCode === 1"
                        v-model="yiZhuData"
                        :data="yaoPinPingLvData"
                        code="frequCode"
                        name="frequCodeName"
                        :remote-method="pinLvRemoteMethod"
                        id="yz_frequCode"
                        ref="pingLv"/>
        </div>
        <div>
          一次剂量:
          <el-input-number v-model="yiZhuData.dose"
                           :min="0"
                           :controls="false"
                           ref="doseRef"
                           id="yz_dose"
                           :precision="dosePrecision()"
                           style="width: 110px"
                           @change="jiSuanLingLiang"/>
          <XcSelect v-model="yiZhuData"
                    :data="yaoPinJiLiangData"
                    :name="['doseUnit', 'doseUnitName']"
                    :width="80"
                    @change="xuanZheJiLiang">
            <XcOption label="value"/>
            <XcOption label="name"/>
          </XcSelect>
        </div>
        <div>
          领量:
          <span v-if="yiZhuData.serial === '00'">
            <el-input-number
                style="width: 60px"
                v-model="yiZhuData.drugQuan"
                :min="0"
                :controls="false"/>
          </span>
          <span v-else>
            {{ yiZhuData.drugQuan }}
            {{ yiZhuData.miniUnitName }}
          </span>
        </div>
      </div>
      <div class="yz_input__box">
        <div>
          给药方式:
          <xc-select-v3
              :disabled="yiZhuData.serial === '00'"
              style="width: 120px"
              v-model="yiZhuData"
              :data="geiYaoFangShiData"
              id="yz_supplyCode"
              code="supplyCode"
              name="supplyCodeName"
              :remote-method="geiYaoFangShiRemoteMethod"
              clearable/>
        </div>
        <div>
          开始时间：
          <el-date-picker
              style="width: 160px"
              v-model="yiZhuData.startTime"
              :disabled-date="disabledDate"
              id="yz_startTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </div>
        <div>
          停止时间：
          <el-date-picker
              style="width: 160px"
              v-model="yiZhuData.endTime"
              id="yz_endTime"
              :disabled="yiZhuData.frequCode === 'ONCE'"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </div>
        <div class="input__style" style="width: 120px">
          医生： {{ yiZhuData.enterOperName ? yiZhuData.enterOperName : store.state.user.info.name }}
        </div>
        <div>
          执行科室：
          <xc-select-v3
              style="width: 120px"
              v-model="yiZhuData"
              :data="zhiXingKeShiData"
              id="yz_execUnit"
              code="execUnit"
              name="execUnitName"
              :remote-method="metZhiXingKeShi"/>
        </div>
      </div>
      <div class="yz_input__box">
        <div class="div_center__box">
          医嘱时间:
          <div class="input__style"> {{ yiZhuData.orderTime }}</div>
        </div>
        <div>
          父医嘱：
          <xc-combo-grid v-model="yiZhuData.parentNoName"
                         style="width: 120px;"
                         placeholder="父医嘱"
                         clearable
                         @clear="clearDoctorSOrder"
                         @focus="fuYiZhuClick"
                         @rowClick="modifyDosingMethod"
                         :table-header="parentOrder"
                         :data="fuYiZhuData">
          </xc-combo-grid>
        </div>
        <div :title="yiZhuData.discription" class="div_center__box">
          描述：
          <div class="input__style" style="overflow: auto;width: 240px">
            {{ yiZhuData.discription }}
          </div>
        </div>
        <div>
          <!--  皮试药品    -->
        </div>
      </div>
      <div class="yz_input__box">
        <div class="div_center__box" :title="yiZhuData.instruction">
          <div style="width: 87px">
            医生嘱托：
          </div>
          <el-input v-model="yiZhuData.instruction"
                    clearable
                    maxlength="50"
                    show-word-limit/>
        </div>
        <div class="div_center__box">
          <el-select
              v-model="yiZhuData.kfFlag"
              id="yz_kfFlag"
              clearable
              style="width: 80px"
              @clear="yiZhuData.kfFlag = null">
            <el-option key="1" label="饭前" value="1"></el-option>
            <el-option key="2" label="饭后" value="2"></el-option>
          </el-select>
        </div>
        <div>
          费用标志:
          <el-select v-model="yiZhuData.selfBuy"
                     :disabled="yiZhuData.serial === '00' || currentPage === 'takeMedicine'"
                     clearable style="width: 120px"
                     @clear="yiZhuData.selfBuy = null">
            <el-option label="自备" value="1"/>
            <el-option label="嘱托" value="2"/>
            <el-option label="基数药" value="3"/>
            <el-option :disabled="currentPage !== 'takeMedicine'" label="出院带药" value="4"/>
          </el-select>
        </div>
        <div class="div_center__box">
          <xc-checkbox
              label="医保自费"
              v-model="yiZhuData.ybSelfFlag"
              inactive-value="0"
              active-value="1"/>
          &nbsp;&nbsp;&nbsp;
          <xc-checkbox
              label="紧急"
              v-model="yiZhuData.emergencyFlag"
              @keydown.tab="toAddAnOrder"
              active-value="1"
              inactive-value="0"/>
        </div>
        <div>
          录入/确认/停止
          <div style="display: inline-block">
            <span style="background-color:#05ff00;padding: 2px;">
            {{ yiZhuData.enterOperName }}
            </span>
            /
            <span style="background-color:#0000fa;padding: 2px;color: white ">
              {{ yiZhuData.signerName }}
            </span>
            /
            <span style="background-color:red;padding: 2px;">
            {{ yiZhuData.modifierName }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <!--  报错信息  -->
    <bao-cun-xin-xi @clickError="clickError"
                    :data="errorMessageData"
                    :currentKey="yiZhuData.actOrderNo"
                    ref="baoCunXinXiRef"/>
    <!--  弹窗医嘱  -->
    <yz-dialog :yz-data="yiZhuData" ref="yzDialogRef"/>
  </div>
</template>

<script setup name='YzEditor'>
import {
  confirmOrders,
  enterOrders, getCostFreeDosing,
  getOrderNo,
  getParentOrders,
  huoQuFeiYongXinXi,
  huoQuGeiYaoFangShi,
  huoQuXiangMu,
  huoQuZhiXinKeShi,
  huoQuZhuYuanPinLv,
  toDeleteAnOrder
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {listNotBlank, stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {getServerDateApi} from '@/api/public-api'
import Sleep from '@/utils/sleep'
import XcComboGrid from "@/components/xiao-chan/combo-grid/XcComboGrid";
import XcSelectV3 from "@/components/xiao-chan/select-v3/XcSelectV3";
import XcOption from "@/components/xiao-chan/select/XcOption";
import XcSelect from "@/components/xiao-chan/select/XcSelect";
import store from "@/store"
import XcCheckbox from "@/components/xiao-chan/checkbox/XcCheckbox";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import BaoCunXinXi from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/BaoCunXinXi";
import {clone} from "@/utils/clone";
import {
  winsize,
  queryParam,
  yiZhuData,
  yzData,
  currentPage,
  isCydy,
  drugManual,
  tableHeader
} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import {ElMessageBox} from "element-plus";
import YzDialog from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/dialog/YzDialog";
import {logoutShortcut, xcHotKey} from "@/utils/xckeydown";


const props = defineProps({
  patientInfo: {
    type: Object,
    default: null
  },
  successfullyEntered: Function,
  openGroupOrderTemplate: Function,
})

let parentOrder = [
  {prop: 'actOrderNo', label: "医嘱号"},
  {prop: 'orderName', label: "医嘱名称", width: 250},
  {prop: 'orderTime', label: "时间"}
]

const searchOrders = (val) => {
  return huoQuXiangMu(val, queryParam.value.groupNo)
}

/*提示信息*/
const tiShiBiaoTi = ref([])
// 填充数据
const xuanZhongFeiYong = async (row, laiyuan = 1) => {
  if (row.serial === '0000' && row.groupNo === '0000') {
    props.openGroupOrderTemplate(row.orderCode);
    return;
  }
  if (row.serial === '00' && isCydy()) {
    qingKong()
    return BizException(ExceptionEnum.LOGICAL_ERROR, '出院带药不能开项目')
  }
  if (yiZhuData.value.actOrderNo === 'tempOrderNo') {
    yiZhuData.value.actOrderNo = await getOrderNo()
  }
  let tempOrderNo = null
  // 查询医嘱是不会有医嘱号的，医生会在原来的医嘱上面修改成项目或者药品
  // 保留一下医嘱号 不然  yiZhuData.value = row 这个会把医嘱号给干掉
  if (laiyuan === 1) {
    tempOrderNo = yiZhuData.value.actOrderNo
  }
  await fuYiZhuClick()
  qingKong()
  await Sleep(200)
  // 克隆一下数据防止有问题
  yiZhuData.value = clone(row) // clone(row)
  if (tempOrderNo !== null) {
    yiZhuData.value.actOrderNo = tempOrderNo;
    yiZhuData.value.statusFlag = '1'
  }
  let newData = yiZhuData.value.statusFlag === '1'
  if (row.serial === '01' || row.serial === '99') {
    try {
      let queryKey = row.orderCode + '_' + row.serial + '_' + props.patientInfo.zkWard + '_' + queryParam.value.groupNo
      let res = await huoQuFeiYongXinXi(queryKey)
      // 加载药品计量
      yaoPinJiLiangData.value = res.yaoPingJiLiang
      if (newData) {
        // 判断是否 是皮试的药 如果是就只能有这些 给药方式
        geiYaoFangShiData.value = res.piShi
        // 是否是 抗菌药物
        yiZhuData.value.kjywFlag = res.data.kjywFlag
        // 提示信息
        tiShiBiaoTi.value = res.prompt
        // 最小单位名称
        yiZhuData.value.miniUnit = res.data.miniUnit
        yiZhuData.value.miniUnitName = res.data.miniUnitName
        yiZhuData.value.drugVolume = res.data.volum
        yiZhuData.value.drugVolUnit = res.data.volUnit
        // 加载 剂量单位
        if (stringNotBlank(yiZhuData.value.doseUnit)) {
          yaoPinJiLiangData.value.forEach((item) => {
            if (item.code === yiZhuData.value.doseUnit) {
              jiLiangValue.value = item.value
            }
          })
        } else if (listNotBlank(yaoPinJiLiangData.value)) {
          // 没有剂量单位的时候默认加载第一个计量单位 并且计算
          yiZhuData.value.doseUnit = yaoPinJiLiangData.value[0].code
          yiZhuData.value.dose = yaoPinJiLiangData.value[0].value
          jiLiangValue.value = yaoPinJiLiangData.value[0].value
        }
        jiSuanLingLiang(yiZhuData.value.dose)
        // 加载默认频率 如果已经填写了 就用有的
        if (stringIsBlank(row.frequCode)) {
          // 如果药品中自带了 频率就用药品表的频率
          if (stringNotBlank(res.data.frequCode)) {
            yiZhuData.value.frequCode = res.data.frequCode
            yiZhuData.value.frequCodeName = res.data.frequCodeName
          } else {
            yiZhuData.value.frequCode = 'ONCE'
            yiZhuData.value.frequCodeName = '一次'
          }
        }
        // 加载给药方式 如果已经有了就没事了
        if (stringIsBlank(yiZhuData.value.supplyCode)) {
          if (stringNotBlank(res.data.supplyCode)) {
            yiZhuData.value.supplyCode = res.data.supplyCode
            yiZhuData.value.supplyCodeName = res.data.supplyCodeName
          }
        }
      }
      openTheOrderPopUpWindow()
    } catch (e) {
      if (yiZhuData.value.statusFlag === '1') {
        await Sleep(200)
        qingKong()
      }
    }
  } else {
    yiZhuData.value.kjywFlag = 0
    try {
      let queryKey = row.orderCode + '_' + '00' + '_' + props.patientInfo.zkWard + '_' + queryParam.value.groupNo
      let res = await huoQuFeiYongXinXi(queryKey)
      if (newData) {
        openTheOrderPopUpWindow('请输入处置医嘱名')
        if (stringNotBlank(res.prompt)) {
          tiShiBiaoTi.value = res.prompt
        }
        if (!row.dose) {
          yiZhuData.value.dose = 1
        }
        // 如果是项目就不需要给药方式
        yiZhuData.value.supplyCode = null
        yiZhuData.value.supplyCodeName = ''
      }
    } catch (e) {
      if (yiZhuData.value.statusFlag === '1') {
        await Sleep(200)
        qingKong()
      }
    }
  }
  if (newData) {
    // 判断这个是不是 新添加的数据 如果是空的就是 新数据
    let serverDate = await getServerDateApi()

    if (!yiZhuData.value.orderTime) {
      yiZhuData.value.orderTime = serverDate
    }
    if (!yiZhuData.value.startTime) {
      yiZhuData.value.startTime = serverDate
    }
    // 用来加载默认的执行科室
    if (stringIsBlank(row.execUnit)) {
      if (stringNotBlank(props.patientInfo.zkWard)) {
        yiZhuData.value.execUnit = props.patientInfo.zkWard
        yiZhuData.value.execUnitName = props.patientInfo.zkWardName
      }
    } else if (props.patientInfo.zkWard && row.execUnit.startsWith("8")) {
      yiZhuData.value.execUnit = props.patientInfo.zkWard
      yiZhuData.value.execUnitName = props.patientInfo.zkWardName
    }
    if (!yiZhuData.value.frequCode) {
      yiZhuData.value.frequCode = 'ONCE'
      yiZhuData.value.frequCodeName = '一次'
    }
    try {
      pingLv.value.focus()
    } catch (e) {
      console.log(e)
    }
    if (queryParam.frequCode === 1) {
      yiZhuData.value.frequCode = 'ONCE'
      yiZhuData.value.frequCodeName = '一次'
    }
  }
  if (currentPage.value === 'takeMedicine') {
    yiZhuData.value.selfBuy = '4'
  }
  // 显示父医嘱的名称
  if (yiZhuData.value.statusFlag !== '1' && yiZhuData.value.parentNo) {
    fuYiZhuData.value = []
    fuYiZhuData.value.push({
      actOrderNo: yiZhuData.value.parentNo,
      orderName: yiZhuData.value.parentNoName,
    })
  }

  // 如果搜索了医嘱那么 这里就需要 重新赋值,不认表格就没办法变化了,把原来的换掉
  for (let i = 0, len = yzData.value.length; i < len; i++) {
    let item = yzData.value[i];
    if (yiZhuData.value.actOrderNo === item.actOrderNo) {
      yzData.value[i] = yiZhuData.value
      return
    }
  }
}


/* 频率 */
const pingLv = ref()
const yaoPinPingLvData = ref([])
// 获取药品频率
const pinLvRemoteMethod = (val) => {
  if (val.length < 0) return
  huoQuZhuYuanPinLv(val).then((res) => {
    yaoPinPingLvData.value = res
  })
}

/*计算领量*/
const jiSuanLingLiang = (val) => {
  // 出院带药就不要计算领量了
  if (yiZhuData.value.selfBuy === '4') {
    return;
  }
  if (jiLiangValue.value <= 0) {
    return;
  }
  yiZhuData.value.drugQuan = Math.ceil(val / jiLiangValue.value)
}
/* 选择剂量 */
const yaoPinJiLiangData = ref([])
const jiLiangValue = ref(0)
const xuanZheJiLiang = (val) => {
  jiLiangValue.value = val.value
  yiZhuData.value.dose = val.value
  jiSuanLingLiang(yiZhuData.value.dose)
}

/* 给药方式 */
const geiYaoFangShiData = ref([])
const geiYaoFangShiRemoteMethod = (val) => {
  if (isCydy()) {
    getCostFreeDosing(val).then((res) => {
      geiYaoFangShiData.value = res
    });
  } else {
    huoQuGeiYaoFangShi(val).then((res) => {
      geiYaoFangShiData.value = res
    });
  }

}

// 医嘱限制时间不能在之前
const disabledDate = (time) => {
  if (props.patientInfo?.admissDate) {
    return time.getTime() < new Date(props.patientInfo?.admissDate).getTime() - 8.64e7
  }
  return true
}

/* 获取执行科室 */
const zhiXingKeShiData = ref([])
const metZhiXingKeShi = (val) => {
  huoQuZhiXinKeShi(val).then((res) => {
    zhiXingKeShiData.value = res
  })
}

/* 父医嘱 */
const fuYiZhuData = ref([])
const fuYiZhuClick = async () => {
  fuYiZhuData.value = []
  fuYiZhuData.value = await getParentOrders(props.patientInfo.inpatientNo, props.patientInfo.admissTimes)
  let tempIndex = fuYiZhuData.value.findIndex(item => {
    return item.actOrderNo == yiZhuData.value.actOrderNo
  })
  if (tempIndex > -1) {
    fuYiZhuData.value.splice(tempIndex, 1)
  }
}

const modifyDosingMethod = (val) => {
  if (yiZhuData.value.actOrderNo == val.actOrderNo) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '无法选择自己');
  }
  yiZhuData.value.parentNo = val.actOrderNo
  yiZhuData.value.parentNoName = val.orderName
  yiZhuData.value.orderTime = val.orderTime
  yiZhuData.value.startTime = val.startTime
  yiZhuData.value.endTime = val.endTime

  yiZhuData.value.supplyCode = '044'
  yiZhuData.value.supplyCodeName = '副药'

  yiZhuData.value.frequCode = val.frequCode
  yiZhuData.value.frequCodeName = val.frequCodeName
  yiZhuData.value.groupNo = val.groupNo
  yiZhuData.value.groupNoName = val.groupNoName
}

const clearDoctorSOrder = () => {
  yiZhuData.value.parentNo = null
  yiZhuData.value.parentNoName = ''
}

/**
 * 添加医嘱
 * @returns {Promise<void>}
 */
const addOrderNo = async () => {
  if (stringIsBlank(props.patientInfo.inpatientNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }
  // 如果有录入数据的话就需要保存一下
  if (stringNotBlank(yiZhuData.value.actOrderNo) && yiZhuData.value.statusFlag === '1' && yiZhuData.value.actOrderNo !== 'tempOrderNo') {
    let param = {
      inpatientNo: props.patientInfo.inpatientNo,
      admissTimes: props.patientInfo.admissTimes,
      actOrderNo: yiZhuData.value.actOrderNo,
      groupNo: queryParam.value.groupNo,
      data: yiZhuData.value
    }
    try {
      let res = await enterOrders(param)
      // 如果有错误信息 就 提示
      if (res !== null && res.error) {
        baoCunXinXiRef.value.openOrClose()
        errorMessageData.value = res.data
        return
      }
      props.successfullyEntered(yiZhuData.value)
      // 医嘱保存超过了 就删除错误提示
      if (errorMessageData.value) {
        for (let key in errorMessageData.value) {
          if (key === yiZhuData.value.actOrderNo.toString()) {
            delete errorMessageData.value[key]
            break
          }
        }
      }
      // 如果没有了错误信息 就关闭
      if (!!errorMessageData.value) {
        baoCunXinXiRef.value.openOrClose(false)
      }
      qingKong()
      yiZhuData.value.actOrderNo = 'tempOrderNo'
      openSearch()
    } catch (e) {
      console.log(e)
    }
  } else {
    qingKong()
    yiZhuData.value.actOrderNo = 'tempOrderNo'
    openSearch()
  }


}

const qingKong = () => {
  yaoPinJiLiangData.value = []
  jiLiangValue.value = 0
  tiShiBiaoTi.value = []
  tempData = null
  yiZhuData.value = {
    id: '',
    actOrderNo: null,
    orderName: '',
    orderCode: '',
    // 频率
    frequCode: '',
    frequCodeName: '',
    drugSpecification: '',
    dose: 0,
    // 领量
    doseUnit: '',
    doseUnitName: '',
    supplyCode: '',
    supplyCodeName: '',
    startTime: '',
    endTime: '',
    orderTime: '',
    doctorName: '',
    drugFlag: '',
    execUnit: '',
    execUnitName: '',
    parentNo: '',
    parentNoName: '',
    physicianName: '',
    discription: '',
    instruction: null,
    kfFlag: null,
    selfBuy: null,
    ybSelfFlag: '0',
    emergencyFlag: '0',
    drugQuan: 0,
    miniUnitName: '',
    serial: '',
    miniUnit: '',
    psFlag: false,
    kjywFlag: 0,
    yyfs: null,
    ssqk: null,
    yysj: null,
    zkObj: '',
    zkWardCode: '',
    zkDeptCode: '',
    statusFlag: '1'
  }
}

// 判断是否可以编辑
const isEdit = computed(() => {
  return !!(stringIsBlank(yiZhuData.value.actOrderNo)
      || yiZhuData.value.statusFlag !== '1'
      || stringIsBlank(props.patientInfo.inpatientNo));
})

let baoCunXinXiRef = ref(null)
const toAddAnOrder = async () => {
  if (stringIsBlank(props.patientInfo.inpatientNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }
  if (stringIsBlank(yiZhuData.value.actOrderNo) || yiZhuData.value.actOrderNo === 'tempOrderNo') {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择一个医嘱')
  }
  // 有 医嘱 不是 录入就说明在看医嘱 直接清空就可以了
  if (stringNotBlank(yiZhuData.value.orderCode) && yiZhuData.value.statusFlag !== '1') {
    qingKong()
    return
  }
  let param = {
    inpatientNo: props.patientInfo.inpatientNo,
    admissTimes: props.patientInfo.admissTimes,
    actOrderNo: yiZhuData.value.actOrderNo,
    groupNo: queryParam.value.groupNo,
    data: yiZhuData.value
  }
  try {
    let res = await enterOrders(param)
    if (res !== null && res.error) {
      baoCunXinXiRef.value.openOrClose()
      errorMessageData.value = res.data
      return
    }
    if (errorMessageData.value) {
      for (let key in errorMessageData.value) {
        if (key === yiZhuData.value.actOrderNo.toString()) {
          delete errorMessageData.value[key]
          break
        }
      }
    }
    // 如果错误信息是空的就关闭
    if (Object.keys(errorMessageData.value).length === 0) {
      baoCunXinXiRef.value.openOrClose(false)
    }
    qingKong()
    props.successfullyEntered(yiZhuData.value)
  } catch (e) {
    console.log(e)
  }
}

/**
 * 点击了确认医嘱
 */
const confirmOrdersClick = async () => {
  try {
    let res = await confirmOrders(props.patientInfo)
    if (res !== null && res.error) {
      baoCunXinXiRef.value.openOrClose()
      errorMessageData.value = res.data
    }
  } catch (e) {

  }

}

const yzDialogRef = ref(null)
const openTheOrderPopUpWindow = () => {
  if (!isEdit.value) {
    yzDialogRef.value.openOrClose(true)
  }
}

// 错误信息
const errorMessageData = ref({})
/**
 * 点击了查看错误信息
 * @param val 数据
 */
const clickError = (val) => {
  if (yiZhuData.value.actOrderNo === 'tempOrderNo') {
    qingKong()
  }
  if (stringNotBlank(yiZhuData.value.actOrderNo)) {
    let param = {
      inpatientNo: props.patientInfo.inpatientNo,
      admissTimes: props.patientInfo.admissTimes,
      actOrderNo: yiZhuData.value.actOrderNo,
      data: yiZhuData.value
    }
    enterOrders(param).then((res) => {
      if (res !== null && res.error) {
        errorMessageData.value[yiZhuData.value.actOrderNo] = res.data[yiZhuData.value.actOrderNo]
        return
      }
      delete errorMessageData.value[yiZhuData.value.actOrderNo]
      xuanZhongFeiYong(val.data, 2)
    }).catch(e => {
    })
  } else {
    xuanZhongFeiYong(val.data, 2)
  }
}

/**
 * 填充 数据
 * @param data
 */
let tempData = null
const fillData = async (data) => {

  await fuYiZhuClick()
  await xuanZhongFeiYong(data, 2)
  tempData = JSON.stringify(yiZhuData.value)
}

/**
 * 复制粘贴医嘱
 * @returns {Promise<void>}
 */
const duplicateAndPaste = async () => {
  if (stringIsBlank(yiZhuData.value.actOrderNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择医嘱')
  }
  let temp = clone(yiZhuData.value)
  qingKong()
  temp.actOrderNo = await getOrderNo()
  temp.statusFlag = '1'
  let newDate = await getServerDateApi()
  temp.orderTime = newDate
  temp.startTime = newDate
  temp.endTime = null
  temp.enterOper = store.getters['user/info'].code
  temp.enterOperName = store.getters['user/info'].name
  temp.signerName = ''
  temp.signer = ''
  temp.modifierName = ''
  temp.modifier = ''

  await xuanZhongFeiYong(temp, 2)
}

// 删除医嘱
const toDeleteAnOrderClick = () => {
  if (stringIsBlank(yiZhuData.value.actOrderNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择要删除的医嘱')
  }

  ElMessageBox.confirm(`确认是否要删除<span style="color: red"> ${yiZhuData.value.orderName} </span>`, '提示', {
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).then(() => {
    toDeleteAnOrder(yiZhuData.value.actOrderNo).then(() => {
      qingKong()
      props.successfullyEntered(yiZhuData.value)
    })
  })

}

const editorMainRef = ref()

const searchRef = ref(null)

const openSearch = () => {
  if (isEdit.value) return
  searchRef.value.focus()
}

const dosePrecision = () => {
  if (yiZhuData.value.serial === '00') {
    return 2
  } else {
    if (yiZhuData.value.doseUnitName === yiZhuData.value.miniUnitName) {
      return 0
    }
    return 3
  }
}

// 频率点击
const pingLvRowClick = (val) => {
  if (isCydy()) {
    yiZhuData.value.instruction = val.name;
  }
}

let shortcutKeyRegistration = {
  ctrl: {s: toAddAnOrder, f: openSearch},
  alt: {a: addOrderNo}
}

onDeactivated(() => {
  logoutShortcut()
})

onActivated(() => {
  xcHotKey(shortcutKeyRegistration)
})

const editingAreaRef = ref()
onMounted(async () => {
  await nextTick()
  await Sleep(100)
  if (winsize.value.editor === 0) {
    // 获取编辑器的宽度
    winsize.value.editor = editingAreaRef.value.clientWidth
  }
})


defineExpose({
  addOrderNo,
  fillData,
  toDeleteAnOrderClick,
  confirmOrdersClick,
  isEdit
})

</script>

<style scoped lang="scss">
.editing_area {
  position: relative;
  width: max-content;
}

.editor__title {
  background-color: #ffdb04;
  padding: 5px;
  width: 100%;
  overflow-x: auto;
}

.yz_editor__disable {
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: 89;
  border: 1px solid red;

  &::before {
    position: absolute;
    content: '只读';
    bottom: 0;
    right: 0;
    color: red;
  }
}

.yz_input__box {
  display: flex;
  margin-top: 6px;
  flex-wrap: wrap;

  div {
    margin-left: 3px;
  }

  .div_center__box {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .input__style {
    width: 125px;
    line-height: 22px;
    height: 22px;
    border: 1px solid
  }

}


</style>
