<template>
  <!-- 这里是获取模板的 -->
  <huo-qu-mu-ban v-if="muBanDuiHuaKuang" @close="muBanDuiHuaKuang = false" @muBanShuJu="muBanShuJu"></huo-qu-mu-ban>
  <bao-cun-mu-ban ref="baoCunMuBanRef"></bao-cun-mu-ban>
  <template v-for="(item, index) in tiShiBiaoTi" :key="index">
    <el-alert :title="item.title" :type="item.type" effect="dark"></el-alert>
  </template>
  <el-button icon="ArrowLeft" style="font-size: 14px" text type="primary" @click="router.go(-1)">返回</el-button>
  <el-button type="primary" @click="muBanDuiHuaKuang = true">获取模板</el-button>
  <el-button :disabled="yiZhuList.length === 0" type="primary" @click="baoCunMuBanClick">保存模板</el-button>
  <el-button icon="Check" type="success" @click="baoCunYiZhuClick">保存</el-button>
  {{ count }}
  <cuo-wu-xin-xi/>
  <el-divider direction="vertical"></el-divider>
  <el-button :disabled="yiZhuData.serial === '00' || stringIsBlank(yiZhuData.serial)" icon="View" type="success"
             @click="HeLiYongYao.dialog = true"> 药品用法
  </el-button>
  <el-divider direction="vertical"></el-divider>
  <el-button @click="tiaoZhuanZhiHeLiYongYao">合理用药</el-button>
  <el-button @click="allergenDialog = true">患者过敏信息</el-button>
  <yao-ping-xiang-qing v-if="HeLiYongYao.dialog" :code="HeLiYongYao.code"
                       @close="HeLiYongYao.dialog = false"></yao-ping-xiang-qing>
  <el-form ref="yiZhuRef" v-model="yiZhuData" label-width="90px" size="small">
    <el-row>
      <el-col :span="span" @click="yiZhuMingDialog = true">
        <el-form-item class="bi_tian" label="医嘱名称:" prop="orderName">
          <div style="border-bottom: 1px solid #000; height: 29px">
            {{ yiZhuData.orderName }}
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="规格:" prop="orderName">
          <div style="border-bottom: 1px solid #000; height: 29px">
            {{ yiZhuData.drugSpecification }}
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="频率:" prop="frequCode">
          <XcSelect v-model="yiZhuData" :data="yaoPinPingLvData" :name="['frequCode', 'frequCodeName']" clearable remote
                    @method="pinLvRemoteMethod" ref="pingLv"></XcSelect>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="一次剂量:" prop="dose">
          <el-input-number v-model="yiZhuData.dose" :min="0" :precision="2" style="width: 110px"
                           @change="jiSuanLingLiang"></el-input-number>
          <XcSelect v-model="yiZhuData" :data="yaoPinJiLiangData" :name="['doseUnit', 'doseUnitName']" :width="80"
                    @change="xuanZheJiLiang">
            <XcOption label="value"></XcOption>
            <XcOption label="name"></XcOption>
          </XcSelect>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="领量:"> {{ yiZhuData.drugQuan }} {{ yiZhuData.miniUnitName }}</el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="给药方式:" prop="supplyCode">
          <XcSelect v-model="yiZhuData" :data="geiYaoFangShiData" :name="['supplyCode', 'supplyCodeName']" clearable
                    remote @method="geiYaoFangShiRemoteMethod"></XcSelect>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="医嘱时间:" prop="orderName">
          {{ yiZhuData.orderTime }}
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="开始时间:" prop="startTime">
          <el-date-picker
              v-model="yiZhuData.startTime"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="停止时间:" prop="endTime">
          <el-date-picker
              v-model="yiZhuData.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>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="医生:" prop="orderName">
          {{ store.state.user.info.name }}
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="执行科室:" prop="execUnit">
          <XcSelect v-model="yiZhuData" :data="zhiXingKeShiData" :name="['execUnit', 'execUnitName']" remote
                    @method="metZhiXingKeShi"></XcSelect>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="父医嘱:" prop="orderName">
          <el-select v-model="yiZhuData.parentNo" :disabled="yiZhuData.serial === '00'" clearable
                     @clear="yiZhuData.parentNo = null" @focus="fuYiZhuClick">
            <el-option v-for="item in fuYiZhuData" :key="item.code" :label="item.name" :value="item.code">
              <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="span" :title="yiZhuData.discription">
        <el-form-item label="医嘱描述:" prop="orderName">
          <el-input v-model="yiZhuData.discription" disabled type="textarea"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="医生嘱托:">
          <el-input v-model="yiZhuData.instruction" clearable maxlength="50" show-word-limit type="textarea"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="服用时间">
          <el-select v-model="yiZhuData.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>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="费用标志:">
          <el-select v-model="yiZhuData.selfBuy" clearable style="width: 120px" @clear="yiZhuData.selfBuy = null">
            <el-option key="1" label="自备" value="1"></el-option>
            <el-option key="2" label="嘱托" value="2"></el-option>
            <el-option key="3" label="基数药" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="医保自费:">
          <el-switch v-model="yiZhuData.ybSelfFlag" active-color="#13ce66" active-text="自费" active-value="1"
                     inactive-color="#ff4949" inactive-text="记账" inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="是否紧急:">
          <el-switch v-model="yiZhuData.emergencyFlag" active-color="#13ce66" active-text="是" active-value="1"
                     inactive-color="#ff4949" inactive-text="否" inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-col>
      <el-col v-if="yiZhuData.orderCode === zkCode" :span="span">
        <el-form-item label="转科:" class="bi_tian">
          <el-select v-model="yiZhuData.zkObj">
            <el-option v-for="(item, index) in zkList" :key="item.value" :label="item.wardName + '|' + item.smallName"
                       :value="item.value">
              <span>{{ item.wardName }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.smallName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="yiZhuData.kjywFlag !== 0" :span="span">
        <el-form-item label="用药方式:">
          <el-select v-model="yiZhuData.yyfs" style="width: 120px" @change="kangJunYaoYongYaoFangShiGaiBian">
            <el-option v-for="item in kangJunYaoWuYongYaoFangShi" :key="item.code" :label="item.name"
                       :value="item.code">
              <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item v-if="yiZhuData.kjywFlag !== 0" label="切口等级:">
          <el-select
              v-model="yiZhuData.ssqk"
              :disabled="yiZhuData.yyfs !== 1 && yiZhuData.yyfs !== 2 && yiZhuData.yyfs !== null"
              clearable
              style="width: 120px"
              @clear="yiZhuData.ssqk = null"
          >
            <el-option v-for="item in kangJunYaoWuQieKou" :key="item.code" :label="item.name" :value="item.code">
              <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span></el-option
            >
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item v-if="yiZhuData.kjywFlag !== 0" label="用药时间:">
          <el-select
              v-model="yiZhuData.yysj"
              :disabled="yiZhuData.yyfs !== 1 && yiZhuData.yyfs !== 2 && yiZhuData.yyfs !== null"
              clearable
              style="width: 120px"
              @clear="yiZhuData.yysj = null"
          >
            <el-option v-for="item in kangJunYaoWuYongYaoShiJian" :key="item.code" :label="item.name"
                       :value="item.code">
              <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span></el-option
            >
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-button icon="Plus" type="primary" @click="tianJiaYiZhu">添加</el-button>
  <xc-code code="Ctrl + S" description="键盘添加"/>
  <xc-code code="Ctrl + F" description="打开搜索框"/>
  <xc-code code="Ctrl + 1" description="回到第一个输入框(数字1)"/>
  <xc-code code="Alt + PgUp / PgDn" description="医嘱上下"/>
  <xc-code code="Alt + ← / →" description="编辑(←) / 复制 (→)"/>
  <xc-code code="Alt + D " description="删除选中的医嘱"/>
  <el-button @click="dianJiXiuGaiZhiXingKeShi">修改执行科室</el-button>
  <el-table
      :data="yiZhuList"
      ref="elTableRef"
      :height="windowSize.h / 2.4"
      @selection-change="dianJiXuanZhongShuJu"
      :row-class-name="doctorSOrderForm"
      @row-click="whenClickingOnTheForm"
  >
    <el-table-column type="selection"></el-table-column>
    <el-table-column label="排序" type="index"></el-table-column>
    <el-table-column label="uuid" prop="id"></el-table-column>
    <el-table-column label="医嘱编码" prop="orderCode"></el-table-column>
    <el-table-column label="医嘱名称" prop="orderName" show-overflow-tooltip></el-table-column>
    <el-table-column label="医嘱时间" prop="orderTime" width="70"></el-table-column>
    <el-table-column label="开始时间" prop="startTime" width="70"></el-table-column>
    <el-table-column label="结束时间" prop="endTime" width="70"></el-table-column>
    <el-table-column label="规格" prop="drugSpecification"></el-table-column>
    <el-table-column label="频率" prop="frequCodeName"></el-table-column>
    <el-table-column label="一次剂量" prop="dose">
      <template #default="scope"> {{ scope.row.dose }} {{ scope.row.doseUnitName }}</template>
    </el-table-column>
    <el-table-column label="领量" prop="drugQuan">
      <template #default="scope"> {{ scope.row.drugQuan }} {{ scope.row.miniUnitName }}</template>
    </el-table-column>
    <el-table-column label="给药方式" prop="supplyCodeName"></el-table-column>
    <el-table-column label="执行科室" prop="execUnitName"></el-table-column>
    <el-table-column label="父医嘱" prop="parentNo"></el-table-column>
    <el-table-column label="类型" prop="drugFlag"></el-table-column>
    <el-table-column label="费用标志" prop="selfBuy">
      <template #default="scope">
        {{ getSelfBuy(scope.row.selfBuy) }}
      </template>
    </el-table-column>
    <el-table-column label="医保自费">
      <template #default="scope">
        <el-tag v-if="scope.row.ybSelfFlag === '1'">是</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="是否紧急">
      <template #default="scope">
        <el-tag v-if="scope.row.emergencyFlag === '1'">是</el-tag>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-button circle icon="Edit" type="warning" @click="xiuGaiYiZhu(scope.row)"></el-button>
        <el-button circle icon="Delete" type="danger" @click="shanChuBiaoGeYiZhu(scope.$index)"></el-button>
        <el-button circle class="iconfont icon-fuzhi" type="info" @click="dianJiFuZhiYiZhu(scope.row)"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 这里是搜索医嘱的 -->
  <sou-suo-yi-zhu v-if="yiZhuMingDialog" @close="closeTheDoctorSOrderSearchBox()"
                  @xuanZhongFeiYong="xuanZhongFeiYong"></sou-suo-yi-zhu>
  <AllergenEntry v-if="allergenDialog" :pat-no="huanZheXinXi.inpatientNo"
                 @close="allergenDialog = false"></AllergenEntry>
</template>

<script name="TianJiaYiZhu" setup>
import {
  huoQuFeiYongXinXi,
  huoQuGeiYaoFangShi,
  huoQuZhiXinKeShi,
  huoQuZhuYuanPinLv,
  jiaoYan,
  shangChuanYiZhu
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {
  cuoWuXinXi,
  fuZhiYiZhu,
  getSelfBuy,
  huanZheXinXi,
  youWuXuanZheHuanZhe,
  zkList
} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import store from '../../../../store'
import {listIsBlank, listNotBlank, stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {kangJunYaoWuQieKou, kangJunYaoWuYongYaoFangShi, kangJunYaoWuYongYaoShiJian} from '@/data'
import {ElMessage, ElMessageBox} from 'element-plus'
import {clone} from '@/utils/clone'
import HuoQuMuBan from '../../../../components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/HuoQuMuBan.vue'
import {uuid} from '@/utils/getUuid'
import BaoCunMuBan from '../../../../components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/BaoCunMuBan.vue'
import {getServerDateApi, whetherThePatientHasAllergens, yaoPinXiangMuPiPeiYiBao} from '@/api/public-api'
import router from '@/router'
import SouSuoYiZhu from '@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/SouSuoYiZhu.vue'
import CuoWuXinXi from '@/components/zhu-yuan-yi-sheng/CuoWuXinXi.vue'
import YaoPingXiangQing from '@/components/zhu-yuan-yi-sheng/he-li-yong-yao/YaoPingXiangQing.vue'
import AllergenEntry from '@/components/zhu-yuan-yi-sheng/AllergenEntry.vue'
import Sleep from '@/utils/sleep'
import {logoutShortcut, xcHotKey} from '@/utils/xckeydown'
import {BizException, ExceptionEnum} from '@/utils/BizException'
import {setScrollTop} from "@/utils/el-table-scroll";

const windowSize = computed(() => {
  return store.state.app.windowSize
})

// 设置倒计时
const seconds = ref(600)
// 倒计时提示
const count = ref('')
// 转科医嘱 编码
const zkCode = '06286'
// 当前的下标
let dataIndex = $ref(-1)
// 表格的 ref
let elTableRef = $ref(null)

const yiZhuData = ref({
  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: '',
})
/*提示信息*/
const tiShiBiaoTi = ref([])

const span = ref(6)
const spanSize = (val) => {
  if (val > 1200) {
    span.value = 6
  } else if (930 < val || val > 1200) {
    span.value = 8
  } else if (val < 930) {
    span.value = 12
  }
}
spanSize(windowSize.value.w)
watch(
    () => windowSize.value,
    () => {
      spanSize(windowSize.value.w)
    }
)

// 搜索医嘱
let yiZhuMingDialog = $ref(false)
const xuanZhongFeiYong = async (row) => {
  qingKong()
  await Sleep(600)
  closeTheDoctorSOrderSearchBox()
  yiZhuData.value = row
  if (row.serial !== '00') {
    huoQuFeiYongXinXi(row.orderCode, row.serial)
        .then((res) => {
          yiZhuData.value.drugFlag = row.orderType
          // 判断是否 是皮试的药 如果是就只能有这些 给药方式
          if (res.data.psFlag === 1) {
            geiYaoFangShiData.value = res.piShi
            tiShiBiaoTi.value.push({title: '该药品为皮试药品给药方式只能是皮试类型', type: 'warning'})
            yiZhuData.value.psFlag = true
          } else {
            yiZhuData.value.psFlag = false
          }
          yiZhuData.value.kjywFlag = res.data.kjywFlag
          if (yiZhuData.value.kjywFlag === 1) {
            tiShiBiaoTi.value.push({title: '该药品为抗菌药物，请填写抗菌药物医嘱附注信息录入。', type: 'error'})
          }
          if (res.data.selfFlagYb === 1) {
            tiShiBiaoTi.value.push({title: '该药品医保自费药品，如符合条件请填写记账，不是请填写自费。'})
          }
          yiZhuData.value.miniUnitName = res.data.miniUnitName
          yaoPinJiLiangData.value = res.yaoPingJiLiang
          // 加载 剂量单位
          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(yaoPinJiLiangData.value[0].value)
          }
          // 加载默认频率 如果已经填写了 就用有的
          if (stringIsBlank(row.frequCode)) {
            if (stringNotBlank(res.data.frequCode)) {
              yiZhuData.value.frequCode = res.data.frequCode
            } else {
              yiZhuData.value.frequCode = 'ONCE'
            }
          }
          // 加载给药方式
          if (stringIsBlank(yiZhuData.value.supplyCode)) {
            if (stringNotBlank(res.data.supplyCode)) {
              yiZhuData.value.supplyCode = res.data.supplyCode
            }
          }
        })
        .catch(async () => {
          await Sleep(500)
          qingKong()
        })
  } else {
    yiZhuData.value.kjywFlag = 0
    huoQuFeiYongXinXi(row.orderCode, '00')
        .then((res) => {
          yiZhuData.value.drugFlag = row.orderType
          yiZhuData.value.frequCode = 'ONCE'
          if (stringNotBlank(res.paiChiYiZhu)) {
            tiShiBiaoTi.value.push({title: res.paiChiYiZhu, type: 'error'})
          }
          if (!res.dose) {
            yiZhuData.value.dose = 1
          }
        })
        .catch(async () => {
          await Sleep(500)
          qingKong()
        })
  }
  // 判断这个是不是 新添加的数据 如果是空的就是 新数据
  getServerDateApi().then((res) => {
    if (!yiZhuData.value.orderTime) {
      yiZhuData.value.orderTime = res
    }
    if (!yiZhuData.value.startTime) {
      yiZhuData.value.startTime = res
    }
  })
  // 用来加载默认的执行科室
  if (stringIsBlank(row.execUnit)) {
    if (stringNotBlank(huanZheXinXi.value.smallDept)) {
      yiZhuData.value.execUnit = huanZheXinXi.value.smallDept
    }
  }
  if (stringIsBlank(row.id)) {
    yiZhuData.value.id = uuid(8, 10)
  }
  try {
    pingLv.focus()
  } catch (e) {
    console.log(e)
  }
}

const closeTheDoctorSOrderSearchBox = () => {
  yiZhuMingDialog = false
  xcHotKey(shortcutKeyRegistration)
}

/* 频率 */
let pingLv = $ref(null)
const yaoPinPingLvData = ref([])
const pinLvRemoteMethod = (val) => {
  huoQuZhuYuanPinLv(val).then((res) => {
    yaoPinPingLvData.value = res
  })
}
/* 选择剂量 */
const yaoPinJiLiangData = ref([])
const jiLiangValue = ref(0)
const xuanZheJiLiang = (val) => {
  jiLiangValue.value = val.value
  yiZhuData.value.dose = val.value
  yiZhuData.value.drugQuan = 1
}
/*计算领量*/
const jiSuanLingLiang = (val) => {
  if (jiLiangValue.value > 0) {
    yiZhuData.value.drugQuan = Math.ceil(val / jiLiangValue.value)
  }
}

/* 给药方式 */
const geiYaoFangShiData = ref([])
const geiYaoFangShiRemoteMethod = (val) => {
  /*如果是皮试的那么就不可以用别的给药方式*/
  if (yiZhuData.value.psFlag) return
  huoQuGeiYaoFangShi(val).then((res) => {
    geiYaoFangShiData.value = res
  })
}

/* 父医嘱 */
const fuYiZhuData = ref([])
const fuYiZhuClick = () => {
  fuYiZhuData.value = yiZhuList.value.filter(item => {
    return stringNotBlank(item.drugFlag) && item.drugFlag === 'i' && item.id !== yiZhuData.value.id && stringIsBlank(item.parentNo)
  })
}

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

/* 这里是添加信息 */
const yiZhuList = ref([])
const tianJiaYiZhuWeiYiBiaoShi = ref([])
const tianJiaYiZhu = () => {
  if (stringIsBlank(yiZhuData.value.orderCode)) {
    return ElMessage.error('请先选择数据')
  }
  if (stringNotBlank(yiZhuData.value.parentNo)) {
    yiZhuData.value.supplyCode = '044'
    yiZhuData.value.supplyCodeName = '副药'
  }
  if (yiZhuData.value.orderCode === zkCode) {
    if (yiZhuData.value.zkObj) {
      let zk = JSON.parse(yiZhuData.value.zkObj)
      yiZhuData.value.zkWardCode = zk.wardCode
      yiZhuData.value.zkDeptCode = zk.smallCode
      yiZhuData.value.orderName = `转科医嘱转至${zk.wardName}(小科室:${zk.smallName})`
    } else {
      return ElMessage.error('请选择转科科室.')
    }
  }

  const list = []
  list.push(yiZhuData.value)
  let data = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    list: list,
  }
  shangChuanYiZhu(data)
      .then((res) => {
        let index = tianJiaYiZhuWeiYiBiaoShi.value.indexOf(yiZhuData.value.id)
        if (index > -1) {
          yiZhuList.value.splice(index, 1)
          tianJiaYiZhuWeiYiBiaoShi.value.splice(index, 1)
          ElMessage.error('重复添加，老记录已删除。')
        }
        tianJiaYiZhuWeiYiBiaoShi.value.push(yiZhuData.value.id)
        yiZhuList.value.push(clone(yiZhuData.value))
        qingKong()
      })
      .catch((e) => {
        cuoWuXinXi.value = e
      })
}

/**
 * 是否重置数据下标,这个是用来判断需不需要 回到默认值
 */
const whetherToResetTheDataSubscript = () => {
  if (dataIndex >= yiZhuList.value.length) {
    dataIndex--
  }
}

/* 这个是点击单个修改的 */
const xiuGaiYiZhu = (val) => {
  xuanZhongFeiYong(val)
  ElMessage.success('你点击了修改')
  yiZhuList.value.splice(val, 1)
  tianJiaYiZhuWeiYiBiaoShi.value.splice(val, 1)
  whetherToResetTheDataSubscript()
}

/* 删除表格医嘱 */
const shanChuBiaoGeYiZhu = (val) => {
  yiZhuList.value.splice(val, 1)
  tianJiaYiZhuWeiYiBiaoShi.value.splice(val, 1)
  ElMessage.success('删除成功')
  whetherToResetTheDataSubscript()
}

/* 复制医嘱 */
const dianJiFuZhiYiZhu = (val) => {
  yiZhuData.value = clone(val)
  yiZhuData.value.id = uuid(8, 10)
  ElMessage.success('复制成功')
}

/* 保存信息 */
const baoCunYiZhuClick = () => {
  if (listIsBlank(yiZhuList.value)) {
    return ElMessage.error('请先选择数据')
  }
  if (youWuXuanZheHuanZhe()) return
  let yiBaoBianMaTiShi = []
  yiZhuList.value.forEach((item) => {
    yiBaoBianMaTiShi.push(item.orderCode + '-' + item.serial)
  })
  yaoPinXiangMuPiPeiYiBao(yiBaoBianMaTiShi).then((res) => {
    if (stringNotBlank(res)) {
      cuoWuXinXi.value = res
      ElMessageBox.confirm(res, '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '继续录入',
      })
          .then(() => {
            baoCunYiZhu()
          })
          .catch(() => {
          })
    } else {
      baoCunYiZhu()
    }
  })
}

function baoCunYiZhu() {
  let list = yiZhuList.value.filter((item) => {
    return item.serial !== '00'
  })
  let data = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    chaRuYiZhu: true,
    cfType: '1',
    list: yiZhuList.value,
  }
  // if (listNotBlank(list)) {
  //   // 合理用药校验
  //   jiaoYan(data).then((res) => {
  //     console.log(res)
  //   })
  // }
  ElMessageBox.confirm('您确定要保存这些数据吗？请仔细检查数据。', '提示', {
    type: 'warning',
    closeOnClickModal: false,
  })
      .then(() => {
        shangChuanYiZhu(data)
            .then((res) => {
              fuZhiYiZhu.value = []
              router.go(-1)
            })
            .catch((e) => {
              cuoWuXinXi.value = e
            })
      })
      .catch(() => {
      })
}

/*  这里是抗菌药物，选择了除了 1和 2 的其他都可以不用填写 */
const kangJunYaoYongYaoFangShiGaiBian = (val) => {
  if (val !== 1 || val !== 2) {
    yiZhuData.value.ssqk = null
    yiZhuData.value.yysj = null
  }
}

// 模板数据
let muBanDuiHuaKuang = $ref(false)
// 这里是返回的模板数据
const muBanShuJu = (val) => {
  let tongZhiCiShu = 0
  val.forEach((item) => {
    let index = tianJiaYiZhuWeiYiBiaoShi.value.indexOf(item.id)
    if (index > -1) {
      yiZhuList.value.splice(index, 1)
      tianJiaYiZhuWeiYiBiaoShi.value.splice(index, 1)
      tongZhi(tongZhiCiShu)
      tongZhiCiShu++
    }
    tianJiaYiZhuWeiYiBiaoShi.value.push(item.id)
    yiZhuList.value.push(item)
  })

  function tongZhi(val) {
    if (val === 0) {
      setTimeout(() => {
        ElMessage.error('重复添加，老记录已删除。')
      }, 200)
    }
  }

  ElMessage.success('添加成功。')
}

// 保存模板
const baoCunMuBanRef = ref(null)
const baoCunMuBanClick = () => {
  if (listIsBlank(yiZhuList.value)) {
    return ElMessage.error('请先选择数据')
  }
  let data = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    list: yiZhuList.value,
  }
  shangChuanYiZhu(data)
      .then((res) => {
        baoCunMuBanRef.value.daKaiBaoCunMuBan(yiZhuList.value)
        cuoWuXinXi.value = ''
      })
      .catch((e) => {
        cuoWuXinXi.value = e
      })
}
// 医嘱限制时间不能在之前
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const xuanZhongShuJu = ref([])

const dianJiXuanZhongShuJu = (selection) => {
  xuanZhongShuJu.value = selection
}

const dianJiXiuGaiZhiXingKeShi = () => {
  if (listIsBlank(xuanZhongShuJu.value)) {
    return ElMessage.error('请先选择数据。')
  } else {
    zhiXingKeShiData.value.forEach((item) => {
      if (item.code === yiZhuData.value.execUnit) {
        yiZhuData.value.execUnitName = item.name
      }
    })
    xuanZhongShuJu.value.forEach((item) => {
      item.execUnit = yiZhuData.value.execUnit
      item.execUnitName = yiZhuData.value.execUnitName
    })
  }
}

const qingKong = () => {
  cuoWuXinXi.value = ''
  yaoPinJiLiangData.value = []
  jiLiangValue.value = 0
  tiShiBiaoTi.value = []
  yiZhuData.value = {
    index: '',
    actOrderNo: null,
    orderName: '',
    orderCode: '',
    // 频率
    frequCode: '',
    frequCodeName: '',
    drugSpecification: '',
    dose: 0,
    // 领量
    doseUnit: '',
    doseUnitName: '',
    supplyCode: '',
    supplyCodeName: '',
    startTime: '',
    endTime: '',
    orderTime: '',
    doctorName: '',
    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,
    zkWardCode: '',
    zkDeptCode: '',
  }
}

let daoJiShi = null

onUnmounted(() => {
  ElMessageBox.close()
  clearInterval(daoJiShi)
  logoutShortcut()
})

// 倒计时功能
const kaiQiDaoJiShi = () => {
  seconds.value = 600
  clearInterval(daoJiShi)
  daoJiShi = setInterval(() => {
    seconds.value--
    countDown()
  }, 1000)
}

const countDown = () => {
  let m = parseInt(((seconds.value / 60) % 60).toString())
  m = m < 10 ? '0' + m : m
  let s = parseInt((seconds.value % 60).toString())
  s = s < 10 ? '0' + s : s
  count.value = '剩余操作时间 ' + m + '分' + s + '秒'
  if (seconds.value === 300) {
    ElMessageBox.alert('您的操作时间过半', '提示', {
      type: 'warning',
    }).then((res) => {
    })
  } else if (seconds.value === 60 || seconds.value === 30 || seconds.value === 20) {
    ElMessage({
      message: '剩余操作时间' + seconds.value + '秒',
      showClose: true,
      type: 'error',
      title: '成功',
      duration: 4500,
    })
  } else if (seconds.value === 0) {
    clearInterval(daoJiShi)
    router.go(-1)
  }
}

let HeLiYongYao = $ref({
  dialog: false,
  code: '',
})
const tiaoZhuanZhiHeLiYongYao = () => {
  window.open('http://172.16.32.121:9097/index.html')
}

//// 下面都是过敏源信息
let allergenDialog = $ref(false)
/////  过敏源结束

/// 这里是 ctrl 快捷键
/**
 * 保存或添加医嘱
 */
const saveOrAddADoctorSOrder = () => {
  if (yiZhuData.value.orderCode) {
    tianJiaYiZhu()
  } else {
    baoCunYiZhuClick()
  }
}

/**
 * 打开医嘱搜索框
 */
const openSearchBox = () => {
  yiZhuMingDialog = true
}

/// 这里是 ctrl 快捷键 结束

const regainFocus = () => {
  pingLv.focus()
}

// 这里是表格事件
/**
 * 表格样式
 * @param row 行
 * @param rowIndex 下标
 * @returns {string} 样式
 */
const doctorSOrderForm = ({row, rowIndex}) => {
  row.tableIndex = rowIndex
  if (dataIndex === rowIndex) {
    return 'input_and_table_to_be_selected'
  }
}

/**
 * 点击表格时触发的事件
 * @param row 当前表格数据
 * @param column 当前行
 * @param event 事件
 */
const whenClickingOnTheForm = (row, column, event) => {
  dataIndex = row.tableIndex
}

// 这里是表格事件 结束

// 这里是 alt 快捷键

/**
 * 检查是否存在医嘱数据
 * @param checkJudgment 判断是否检查选中数据
 */
const dataJudgmentIsEmpty = (checkJudgment) => {
  let pageDataLength = yiZhuList.value.length
  if (pageDataLength <= 0) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请选选择数据')
  }
  if (checkJudgment) {
    if (dataIndex === -1) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '请选选择数据')
    }
  }
}

const scrollBarSynchronization = () => {
  setScrollTop(elTableRef, dataIndex)
}

const upData = () => {
  dataJudgmentIsEmpty(false)
  let pageDataLength = yiZhuList.value.length
  dataIndex <= 0 ? (dataIndex = pageDataLength - 1) : dataIndex--
  scrollBarSynchronization()
}

const downData = () => {
  dataJudgmentIsEmpty(false)
  let pageDataLength = yiZhuList.value.length
  dataIndex === pageDataLength - 1 ? (dataIndex = 0) : dataIndex++
  scrollBarSynchronization()
}

const copyData = () => {
  dataJudgmentIsEmpty(true)
  dianJiFuZhiYiZhu(yiZhuList.value[dataIndex])
}

const editData = () => {
  dataJudgmentIsEmpty(true)
  xiuGaiYiZhu(yiZhuList.value[dataIndex])
}

const deleteSelectedOrders = () => {
  dataJudgmentIsEmpty(true)
  shanChuBiaoGeYiZhu(yiZhuList.value[dataIndex])
}

// alt 快捷键结束

// 注册快捷键的 list
let shortcutKeyRegistration = {
  ctrl: {s: saveOrAddADoctorSOrder, f: openSearchBox, 1: regainFocus},
  alt: {
    PageUp: upData,
    PageDown: downData,
    ArrowRight: copyData,
    ArrowLeft: editData,
    d: deleteSelectedOrders,
  },
}

onMounted(() => {
  xcHotKey(shortcutKeyRegistration)
  yiZhuList.value = clone(fuZhiYiZhu.value)
  for (let i = 0; i < yiZhuList.value.length; i++) {
    yiZhuList.value[i].id = yiZhuList.value[i].actOrderNo
  }
  if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
    ElMessage.warning('您现在进入的是医嘱模板编辑')
  } else {
    ElMessage.warning('您现在进入的是医嘱编辑模块，' + '您的编辑时间有 10 分钟,你准备好了吗？Are ya ready kids?')
    kaiQiDaoJiShi()
    whetherThePatientHasAllergens(huanZheXinXi.value.inpatientNo).then((res) => {
      allergenDialog = res
    })
  }
  if (stringNotBlank(huanZheXinXi.value.inpatientNo)) {
    zhiXingKeShiData.value = [
      {
        code: huanZheXinXi.value.smallDept,
        name: huanZheXinXi.value.smallDeptName,
      },
    ]
  }
  fuZhiYiZhu.value = []
})
</script>

<style scoped>
.el-popover {
  height: 240px;
  overflow: auto;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #0a84fd;
}
</style>
