<template>
  <div ref="editorMainRef" style="width: max-content">
    <div class="editing_area"
         :style="{color: isEdit ? '#0014fc' : ''}">
      <div class="yz_editor__disable" v-if="isEdit"/>
      <div class="yz_input__box">
        <div>
          医嘱名称：
          <CyComboGrid
              ref="orderCodeRef"
              style="width: 220px"
              placement="bottom"
              :fallbackPlacements="['top', 'bottom']"
              v-model="yiZhuData"
              :disabled="isEdit"
              value="orderCode"
              label="orderName"
              :remote-method="searchOrders"
              @rowClick="({row}) => searchClickFunc(row)"
              :table-header="tableHeaderV2"
              :rowHeight="30"
          />
        </div>
        <div class="input__style">
          {{ yiZhuData.drugSpecification }}
        </div>
        <div>
          频率:
          <select-v4
              :data="yaoPinPingLvData"
              ref="pingLvRef"
              v-model="yiZhuData.frequCode"
              :disabled="queryParam.frequCode === frequCodeEnum.temporary"
              style="width: 120px"/>
        </div>
        <div>
          一次剂量:
          <el-input-number
              v-model="yiZhuData.dose"
              :step="jiLiangValue"
              :controls="false"
              :min="0"
              ref="doseRef"
              id="yz_dose"
              :precision="dosePrecision"
              style="width: 110px"
              @change="jiSuanLingLiang"
          />
          <CyComboGrid
              v-model="yiZhuData"
              :data="yaoPinJiLiangData"
              style="width: 80px"
              value="doseUnit"
              label="doseUnitName"
              @rowClick="xuanZheJiLiang"
          />
        </div>
        <div>
          领量:
          <template v-if="queryParam.frequCode === 'takeMedicine'">
            <el-input-number
                style="width: 60px"
                ref="drugQuanRef"
                @keydown="drugQuanChange"
                v-model="yiZhuData.drugQuan"
                :min="1"
                :controls="false"/>
            <span style="color: red">{{ yiZhuData.miniUnitName }}</span>
          </template>
          <template v-else-if="yiZhuData.serial === '00'">
            <el-input-number
                style="width: 60px"
                v-model="yiZhuData.drugQuan"
                :min="0"
                :controls="false"/>
          </template>
          <template v-else>
            {{ yiZhuData.drugQuan }}
            {{ yiZhuData.miniUnitName }}
          </template>
        </div>
      </div>
      <div class="yz_input__box">
        <div>
          给药方式:
          <select-v4
              key="supplyCode"
              :disabled="supplyDisabled"
              style="width: 120px"
              v-model="yiZhuData.supplyCode"
              :data="geiYaoFangShiData"
              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 : userStore.userInfo.name }}
        </div>
        <div>
          执行科室：
          <SystemDeptSelect
              v-model="yiZhuData"
              id="yz_execUnit"
              value="execUnit"
              label="execUnitName"
              style="width: 120px"
          />
        </div>
      </div>
      <div class="yz_input__box">
        <div class="div_center__box">
          医嘱时间:
          <div class="input__style"> {{ yiZhuData.orderTime }}</div>
        </div>
        <div>
          父医嘱：
          <CyComboGrid
              v-model="yiZhuData"
              style="width: 120px;"
              placeholder="父医嘱"
              clearable
              :disabled="supplyDisabled"
              @clear="clearDoctorSOrder"
              @focus="fuYiZhuClick"
              @rowClick="({row}) => modifyDosingMethod(row)"
              :table-header="parentOrder"
              :data="fuYiZhuData"
              value="parentNo"
              label="parentNoName"
          />
        </div>
        <div :title="yiZhuData.discription" class="div_center__box">
          描述：
          <div class="input__style" style="overflow: auto;width: 240px">
            {{ yiZhuData.discription }}
          </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
                    style="width: 220px"
                    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="supplyDisabled"
                     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="queryParam.frequCode !== 'takeMedicine'" label="出院带药"
                       value="4"/>
            <el-option label="GCP自费" value="5"/>
          </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>
    <BaoCuoXinXi v-if="errorMsg.dialog"
                 @click-error="clickError"/>
    <!--  弹窗医嘱  -->
    <YzDialog :yz-data="yiZhuData" v-if="yzDialogRef" @closed="yzDialogRef = false"/>
  </div>
</template>

<script setup lang="ts">
import {
  confirmOrders,
  copyOrder,
  enterOrders,
  FeeInfo,
  getOrderNo,
  huoQuFeiYongXinXi,
  huoQuXiangMu,
  huoQuZhiXinKeShi,
  toDeleteAnOrder,
  YaoPingJiLiang
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {listNotBlank, listToStr, stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import XcCheckbox from "@/components/xiao-chan/checkbox/XcCheckbox";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {
  queryParam,
  yiZhuData,
  yzData,
  isCydy,
  tableHeaderV2,
  frequCodeEnum,
  yaoPinPingLvData,
  geiYaoFangShiData,
  yzMitt,
  huanZheXinXi,
  frequencyConfig,
  addTempOrderNo,
  yiZhuDataInit,
  setOrderDataAndTwinkle,
  feeKey,
  YzType,
  SearchOrdersType,
  RefFillingValue,
  errorMsgFunc,
  errorMsg, yzInfoPrompt, jsQueryYzData
} 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 Dig from "@/utils/math";
import SelectV4 from "@/components/xiao-chan/select-v4/SelectV4.vue";
import {shortcutTrigger, xcEvent} from "@/utils/xckeydown";
import {xcMessage} from "@/utils/xiaochan-element-plus";
import DoctorAuthorization
  from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/DoctorAuthorization.vue";
import sleep from "@/utils/sleep";
import XEUtils from 'xe-utils'
import {
  ref,
  computed,
  nextTick,
  onDeactivated,
  onActivated,
  watch,
  onMounted
} from 'vue'
import {getServerDate} from "@/utils/moment-utils";
import {CyMessageBox} from "@/components/cy/message-box";
import setDialogToJs from "@/components/js-dialog-comp/useDialogToJs";
import CyComboGrid from "@/components/cy/combo-grid/src/CyComboGrid.vue";
import BaoCuoXinXi from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/BaoCuoXinXi.vue";
import SystemDeptSelect from "@/components/system/dept-select/SystemDeptSelect.vue";
import setPatientDoctor from "@/views/hospitalization/zhu-yuan-yi-sheng/patient-doctor/setPatientDoctor";
import {useUserStore} from "@/pinia/user-store";
import doctorStore, {YzSidebarEnum} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/useDoctorStore";

const props = withDefaults(defineProps<{
  patientInfo: {
    inpatientNo: string,
    admissTimes: number,
    zkWard: string,
    zkWardName: string
    admissDate: Date
  },
  openGroupOrderTemplate: (val: string) => void
}>(), {
  patientInfo: null,
})

const parentOrder = [
  {code: 'actOrderNo', name: "医嘱号", width: 90},
  {code: 'orderName', name: "医嘱名称", width: 160},
  {code: 'orderTime', name: "时间", width: 150}
]

const userStore = useUserStore()

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

const searchClickFunc = async (row: SearchOrdersType): Promise<void> => {
  // 这个是选择了医嘱模板医嘱，需要打开弹窗
  if (row.serial === '0000' && row.groupNo === '0000') {
    props.openGroupOrderTemplate(row.orderCode)
    return
  }

  // 在出院带药的页面中选择数据
  if (row.serial === '00' && isCydy()) {
    clearAndErrorMessage('出院带药不能开项目')
  }

  // 医嘱号是空的，或者是临时医嘱号的就需要一个新的医嘱号
  if (stringIsBlank(yiZhuData.value.actOrderNo) || yiZhuData.value.actOrderNo === addTempOrderNo) {
    setYzData('actOrderNo', parseInt(await getOrderNo()));
  }

  // 清空数据但是保留原来的医嘱号
  qingKong(false)

  // 设置医嘱的一些默认值
  const setYz = new RefFillingValue(yiZhuData, row);
  setYz.setValue('orderCode')
      .setValue('orderName')
      .setValue('serial')
      .setValue('discription')
      .setValue('groupNo')
      .setValue('groupName')
      .setValue('infusionFlag')
      .setValue('drugFlag')
      .setValue('packSize')
      .setValue('packSizeName')
      .setValue('orderClass')
      .setValue('dosage')
      .setValue('ybType')
      .setValue('execDept')
      .setValue('execDeptName')
      .setValue('drugSpecification')
      .setDefaultValueByName('newOrderFlag', 1)
      .setDefaultValueByName('statusFlag', '1');

  // 查询一下父医嘱
  fuYiZhuClick()
  // 药品
  if (row.serial !== '00') {
    await drugDefaultValue(true, row)
  } else {
    itemDefaultValue(true, row)
  }
  await defaultAll(true, row)
}

let oneMessageCount = true;
const oneMessage = () => {
  if (oneMessageCount) {
    oneMessageCount = false
    xcMessage.warning('请注意表格中切换医嘱是不会保存医嘱的，一切数据以录入的医嘱为准。')
  }
}

const rowClickFillData = async (data: YzType) => {
  if (yiZhuData.value.actOrderNo !== addTempOrderNo && yiZhuData.value.statusFlag === '1') {
    oneMessage()
  }
  // 先清空一遍
  qingKong()

  yiZhuData.value = data

  if (data.serial !== '00') {
    await drugDefaultValue(false, data)
  } else {
    await itemDefaultValue(false, data)
  }
  await defaultAll(false, data)
}

const clearAndErrorMessage = (message: string) => {
  qingKong()
  BizException(ExceptionEnum.MESSAGE_ERROR, message)
}

const drugDefaultValue = async (isSearch: boolean, data: SearchOrdersType | YzType) => {
  const queryKey = feeKey(data.orderCode, data.serial, props.patientInfo.zkWard, queryParam.value.groupNo, yiZhuData.value.superiorDoctor, yiZhuData.value.statusFlag)
  const {
    permissionPrompt,
    prompt,
    data: drugData,
    yaoPingJiLiang
  }: FeeInfo = await huoQuFeiYongXinXi(queryKey).catch(() => {
    clearAndErrorMessage('请联系管理员。')
  })

  yzInfoPrompt.value = XEUtils.isArray(prompt) ? prompt : []

  const drugKey = `${data.orderCode}_${data.serial}`;

  // 医生没有权限
  if (permissionPrompt) {
    await setDialogToJs(DoctorAuthorization, {drugCode: drugKey}).then((res) => {
      setYzData('superiorDoctor', res.code)
      yzInfoPrompt.value.push('医生授权')
    }).catch(() => {
      clearAndErrorMessage('取消授权。')
      yzInfoPrompt.value.push('取消授权')
    })
  }

  // 加载药品的计量
  yaoPinJiLiangData.value = XEUtils.eachAndReturnList(yaoPingJiLiang, (item) => {
    return {
      ...item,
      value: item.code,
      label: item.name,
      step: item.value
    }
  })

  setYzData('kjywFlag', drugData.kjywFlag)
  if (isSearch) {
    setYzData('miniUnit', drugData.packUnit)
    setYzData('miniUnitName', drugData.packUnitName)

    // 是搜索的医嘱都没有剂量这里需要默认拿到第一个剂量
    if (listNotBlank(yaoPingJiLiang) && yaoPingJiLiang.length > 0) {
      const doseOne: YaoPingJiLiang = yaoPingJiLiang[0]
      setYzData('doseUnit', doseOne.code)
      setYzData('dose', doseOne.value)
      setYzData('doseUnitName', doseOne.name)
      jiLiangValue.value = doseOne.value
    }

    // 使用默认的频率，如果有的话
    if (drugData.frequCode) {
      setYzData('frequCode', drugData.frequCode)
      yzInfoPrompt.value.push('请注意已使用【默认频率】，药剂科维护默认执行频率。')
    }
    if (drugData.supplyCode) {
      setYzData('supplyCode', drugData.supplyCode)
      yzInfoPrompt.value.push('请注意已使用【默认给药方式】，药剂科维护默认给药方式。')
    }
  }

  if (stringIsBlank(yiZhuData.value.frequCode)) {
    // 如果在临时医嘱页面的话，就变成临时的其他都是长期的
    if (queryParam.value.frequCode === frequCodeEnum.temporary) {
      setYzData('frequCode', 'ONCE')
    } else {
      setYzData('frequCode', frequencyConfig)
    }
  }

  setYzData('packSize', drugData.packSize)
  setYzData('packUnit', drugData.packUnit)
  setYzData('drugVolume', drugData.volum)
  setYzData('drugVolUnit', drugData.volUnit)

  if (stringNotBlank(yiZhuData.value.doseUnit)) {
    yaoPinJiLiangData.value.forEach(item => {
      if (item.code === yiZhuData.value.doseUnit) {
        jiLiangValue.value = item.step
      }
    })
  }
  await jiSuanLingLiang(yiZhuData.value.dose)
  openTheOrderPopUpWindow()
}

const itemDefaultValue = (isSearch: boolean, data: SearchOrdersType | YzType) => {
  setYzData('kjywFlag', 0)
  const queryKey = feeKey(data.orderCode, '00', props.patientInfo.zkWard, queryParam.value.groupNo, yiZhuData.value.superiorDoctor, yiZhuData.value.statusFlag)
  const {
    prompt
  }: FeeInfo = huoQuFeiYongXinXi(queryKey).catch(() => {
    clearAndErrorMessage('请联系管理员。')
  })

  yzInfoPrompt.value = XEUtils.isArray(prompt) ? prompt : []

  if (isSearch) {
    setYzData('dose', 1)
    setYzData('supplyCode', null)
    setYzData('drugQuan', 1)
  }

  if (yiZhuData.value.statusFlag === '1') {
    openTheOrderPopUpWindow()
  }

  if (stringIsBlank(yiZhuData.value.frequCode)) {
    // 如果在临时医嘱页面的话，就变成临时的其他都是长期的
    if (queryParam.value.frequCode === frequCodeEnum.temporary) {
      yzInfoPrompt.value.push('使用频率 【ONCE】')
      setYzData('frequCode', 'ONCE')
    } else {
      yzInfoPrompt.value.push(`使用频率 【${frequencyConfig}】`)
      setYzData('frequCode', frequencyConfig)
    }
  }

}

const defaultAll = async (isSearch: boolean, data: SearchOrdersType | YzType) => {

  if (isSearch) {

    doctorStore.setYzSidebar(YzSidebarEnum.YZ)

    let now = await getServerDate()

    setYzData('orderTime', now);
    setYzData('startTime', now);

    // 如果有默认科室的话就用项目中自带的科室，没有的话就用患者的科室
    if (data.execDept) {
      setYzData('execUnit', data.execDept)
      setYzData('execUnitName', data.execDeptName)
      yzInfoPrompt.value.push('请注意，已使用默认执行科室，如需修改请在执行科室下拉框中搜索科室。')
    }

  }

  if (stringIsBlank(yiZhuData.value.execUnit)) {
    setYzData('execUnit', huanZheXinXi.value.zkWard)
    setYzData('execUnitName', huanZheXinXi.value.zkWardName)
  }

  try {
    pingLvRef.value.focus()
  } catch {
  }

  if (isCydy()) {
    setYzData('selfBuy', '4');
    setYzData('frequCode', 'ONCE');
    setYzData('supplyCode', '007');
    yzInfoPrompt.value.push('请注意，出院带药频率默认 【ONCE】 给药方式变为【出院带药】。')
  }

  if (yiZhuData.value.statusFlag !== '1' && yiZhuData.value.parentNo) {
    fuYiZhuData.value = []
    fuYiZhuData.value.push({
      actOrderNo: yiZhuData.value.parentNo,
      orderName: yiZhuData.value.parentNoName
    })
  }

  if (queryParam.value.frequCode === frequCodeEnum.temporary) {
    setYzData('frequCode', 'ONCE')
    yzInfoPrompt.value.push('请注意，频率强制设置 【ONCE】')

  }

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

const setYzData = (name: keyof YzType, value: any): void => {
  yiZhuData.value[name] = value
}

/* 频率 */
const pingLvRef = ref()

/*计算领量*/
const jiSuanLingLiang = async (val) => {
  await nextTick()
  if (yiZhuData.value.statusFlag !== '1') {
    return
  }
  // 出院带药
  if (yiZhuData.value.selfBuy === '4') {
    return;
  }
  if (jiLiangValue.value <= 0) {
    return;
  }
  let drugQuanA = Math.ceil(Dig.division(val, jiLiangValue.value))
  if (yiZhuData.value.serial === '99') {
    drugQuanA = Math.ceil(Dig.division(drugQuanA, yiZhuData.value.packSize))
  }
  yiZhuData.value.drugQuan = drugQuanA;
}
/* 选择剂量 */
const yaoPinJiLiangData = ref<YaoPingJiLiang[]>([])
const jiLiangValue = ref(0)
const xuanZheJiLiang = ({row}) => {
  jiLiangValue.value = row.step
  yiZhuData.value.dose = row.step
  jiSuanLingLiang(yiZhuData.value.dose)
}

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

/* 父医嘱 */
const fuYiZhuData = ref<any[]>([])
const fuYiZhuClick = () => {
  fuYiZhuData.value = [];

  const eachName = queryParam.value.sort === 'asc' ? 'lastArrayEach' : 'arrayEach'
  const eachFunction = XEUtils[eachName]

  let hasParentNo = false

  // @ts-ignore
  eachFunction(yzData.value, (item) => {
    const {statusFlag, serial, parentNo, drugFlag, actOrderNo} = item
    if (statusFlag !== '1') {
      return
    }
    if (parentNo === yiZhuData.value.actOrderNo) {
      hasParentNo = true
      return;
    }
    if (serial !== '00' && stringIsBlank(parentNo) && drugFlag !== 'd') {
      if (yiZhuData.value.actOrderNo !== actOrderNo) {
        fuYiZhuData.value.push(item)
      }
    }
  })
  if (hasParentNo) {
    fuYiZhuData.value = []
  }
}

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 = ''
}

const orderCodeRef = ref()
/**
 * 设置医嘱为临时变量，可以新增医嘱，关闭医嘱错误信息的弹窗。
 */
const setTheTemporaryVariableMedicalOrder = () => {
  qingKong()
  yiZhuData.value.actOrderNo = addTempOrderNo
  try {
    orderCodeRef.value.focus()
  } catch {
  }
}

const qingKong = (clearOrderNo: boolean = true) => {
  yaoPinJiLiangData.value = [];
  jiLiangValue.value = 0;
  yzInfoPrompt.value = [];
  yiZhuDataInit(clearOrderNo);
}

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

/**
 * 保存， 录入状态的医嘱
 * @returns {Promise<boolean>}
 */
const toAddAnOrder = async () => {
  if (stringIsBlank(props.patientInfo.inpatientNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择一位患者，后点击此按钮。')
  }
  if (stringIsBlank(yiZhuData.value.actOrderNo) || yiZhuData.value.actOrderNo === addTempOrderNo) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '工作台中，没有正在编辑的医嘱，请在医嘱名称中搜索一条医嘱，后在点击此按钮。')
  }
  // 不是录入状态的医嘱，直接清空就可以了
  if (stringNotBlank(yiZhuData.value.orderCode) && yiZhuData.value.statusFlag !== '1') {
    setTheTemporaryVariableMedicalOrder()
    return true
  }
  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 && res.error) {
      errorMsgFunc.add(res.data)
      return false
    }
    // 数据完全没问题
    if (res != null && res.code && res.code === 200) {
      let orderNo = yiZhuData.value.actOrderNo
      errorMsgFunc.delByOrder(orderNo)
      await setOrderDataAndTwinkle(orderNo, res.data)
    }
    setTheTemporaryVariableMedicalOrder()
  } catch (e) {
    console.log(e)
  }
  return true
}

/**
 * 点击了确认医嘱
 */
const confirmOrdersClick = async () => {
  try {
    let errorList = []
    if (stringIsBlank(huanZheXinXi.value.referPhysician)) {
      errorList.push('管床医生为空')
    }
    if (stringIsBlank(huanZheXinXi.value.consultPhysician)) {
      errorList.push('主治医生为空')
    }
    if (stringIsBlank(huanZheXinXi.value.deptDirector)) {
      errorList.push('主任医生为空')
    }
    if (listNotBlank(errorList)) {
      const pat = unref(huanZheXinXi)
      setPatientDoctor(pat).then(res => {
        // @ts-ignore
        huanZheXinXi.value = {...huanZheXinXi.value, ...res}
      })

      sleep(200).then(() => {
        xcMessage.error("按医务部要求：" + listToStr(errorList) + "无法确认医嘱。")
      })
      return
    }
    let res = await confirmOrders(props.patientInfo)
    if (res !== null && res.error) {
      errorMsgFunc.add(res.data)
    }
  } catch (e) {

  }

}

const yzDialogRef = ref(false)
const openTheOrderPopUpWindow = () => {
  if (!isEdit.value) {
    const specialOrders = ['06286', '06054']
    if (yiZhuData.value.statusFlag !== '1') {
      return
    }
    if (specialOrders.includes(yiZhuData.value.orderCode)) {
      yzDialogRef.value = true
    } else if (yiZhuData.value.kjywFlag === 1) {
      yzDialogRef.value = true
    }
  }
}

/**
 * 点击了查看错误信息
 * @param orderNo 医嘱号
 */
const clickError = (orderNo) => {
  let index = XEUtils.findLastIndexOf(yzData.value, (item) => {
    return item.actOrderNo === orderNo
  })

  if (index > -1) {
    rowClickFillData(yzData.value[index])
  }
}

const fillData = async (data) => {
  fuYiZhuClick()
  await rowClickFillData(data)
}


// 删除医嘱
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(() => {
      jsQueryYzData()
      qingKong()
    })
  })
}

const editorMainRef = ref()

const dosePrecision = computed(() => {
  return yiZhuData.value.serial === '00' ? 2 : 3
})

const copyOrderNo = ref<{
  actOrderNo: number | null,
  frequCode: string
  deptCode: string
  inpatientNo: string
  admissTimes: number
}>({
  actOrderNo: null,
  frequCode: '',

  deptCode: '',
  inpatientNo: '',
  admissTimes: 0
})

const copy = (actOrderNo, frequCode) => {
  copyOrderNo.value.actOrderNo = actOrderNo
  copyOrderNo.value.frequCode = frequCode
  xcMessage.success('复制成功。')
}

const pasteClick = () => {
  if (queryParam.value.frequCode === frequCodeEnum.temporary && copyOrderNo.value.frequCode !== 'ONCE') {
    copyOrderNo.value.frequCode = 'ONCE'
  } else if (queryParam.value.frequCode === frequCodeEnum.longTerm && copyOrderNo.value.frequCode === 'ONCE') {
    copyOrderNo.value.frequCode = frequencyConfig
  } else if (queryParam.value.frequCode === frequCodeEnum.takeMedicine) {
    copyOrderNo.value.frequCode = 'ONCE'
  }

  copyOrderNo.value.deptCode = props.patientInfo.zkWard
  copyOrderNo.value.inpatientNo = props.patientInfo.inpatientNo
  copyOrderNo.value.admissTimes = props.patientInfo.admissTimes

  copyFuncApi()
}

const copyFuncApi = async () => {
  let {list, data} = await copyOrder(copyOrderNo.value)
  let temp = {}
  XEUtils.arrayEach(list, (item) => {
    temp[item] = true
  })
  yzData.value.push(...data)
  yzMitt.emit('scrollEndAndTwinkle', temp)
  copyOrderNo.value.actOrderNo = null
}

/**
 * 复制粘贴医嘱
 * @returns {Promise<void>}
 */
const duplicateAndPaste = () => {
  if (stringIsBlank(yiZhuData.value.actOrderNo) || yiZhuData.value.actOrderNo === addTempOrderNo) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择医嘱')
  }
  copyOrderNo.value = {
    actOrderNo: yiZhuData.value.actOrderNo,
    frequCode: yiZhuData.value.frequCode,

    deptCode: props.patientInfo.zkWard,
    inpatientNo: props.patientInfo.inpatientNo,
    admissTimes: props.patientInfo.admissTimes
  }
  copyFuncApi()
}

let shortcutKeyRegistration = {
  ctrl: {s: toAddAnOrder},
  alt: {a: toAddAnOrder, q: () => yzMitt.emit('confirmMedicalAdvice')}
}


const supplyDisabled = computed(() => {
  if (yiZhuData.value.orderCode === '06054') {
    return false
  }
  return yiZhuData.value.serial === '00';
})


onMounted(() => {
  yzMitt.on('toAddAnOrder', toAddAnOrder)
  yzMitt.on('duplicateAndPaste', duplicateAndPaste)
  yzMitt.on('openTheOrderPopUpWindow', openTheOrderPopUpWindow)
  yzMitt.on('emptyTheWorkbench', qingKong)
  yzMitt.on('copy', copy)
  yzMitt.on('paste', pasteClick)
  yzMitt.on('allowReplication', () => {
    return copyOrderNo.value.actOrderNo !== null
  })
  yzMitt.on('deleteAnOrderByOrderNo', ({actOrderNo, orderName}, clearOrNot = true) => {
    if (stringIsBlank(actOrderNo)) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择要删除的医嘱')
    }
    CyMessageBox.confirm({
      message: `确认是否要删除<span style="color: red"> ${orderName} </span>`,
      dangerouslyUseHTMLString: true,
      type: 'delete',
    }).then(() => {
      toDeleteAnOrder(actOrderNo).then(() => {
        jsQueryYzData()
        if (clearOrNot) {
          qingKong()
        }
        errorMsgFunc.delByOrder(actOrderNo)
      })
    }).catch(() => {

    })
  })
})

const drugQuanRef = ref()

const drugQuanChange = async (event) => {
  await nextTick()
  await sleep(200)
  yiZhuData.value.drugQuan = parseInt(event.target.value)
}

let keyWatch = null

onDeactivated(() => {
  if (keyWatch != null) {
    keyWatch()
  }
})

onActivated(() => {
  keyWatch = watch(() => xcEvent.value, () => {
    shortcutTrigger(xcEvent.value, shortcutKeyRegistration)
  })
})

defineExpose({
  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>
