<template>
  <div class="prompt" v-if="tiShiBiaoTi?.length > 0">
    <div style="margin-right: 5px">
      提示信息:
    </div>
    <div v-for="(item, index) in tiShiBiaoTi" :key="index" class="item">
      <div>
        {{ item }}
      </div>
    </div>
  </div>
  <el-button icon="ArrowLeft" style="font-size: 14px" text type="primary" @click="cloneWindow">返回</el-button>
  <el-button type="primary" @click="muBanDuiHuaKuang = true"> 获取模板</el-button>
  <el-button :disabled="yiZhuList.length === 0" type="primary" @click="baoCunMuBanClick">保存模板</el-button>
  {{ count }}
  <el-divider direction="vertical"/>
  <el-button :disabled="yiZhuData.serial === '00' || stringIsBlank(yiZhuData.serial)"
             icon="View"
             type="success"
             @click="synopsis({
             orderCode: yiZhuData.orderCode,
             serial: yiZhuData.serial
             })"> 药品用法
  </el-button>
  <el-divider direction="vertical"></el-divider>
  <el-select v-model="groupNo" style="width: 90px">
    <el-option value="73" label="住院"/>
    <el-option value="71" label="门诊"/>
  </el-select>
  <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">
        <el-form-item class="bi_tian" label="医嘱名称:" prop="orderName">
          <xc-combo-grid
              ref="searchRef"
              v-model="yiZhuData.orderName"
              :table-header="tableHeader"
              :query-data-func="searchOrders"
              :current-key="yiZhuData.orderCode + yiZhuData.orderName"
              @rowClick="xuanZhongFeiYong">
          </xc-combo-grid>
        </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">
          <xc-table-v3 style="width: 120px"
                       v-model="yiZhuData"
                       :data="yaoPinPingLvData"
                       code="frequCode"
                       name="frequCodeName"
                       :remote-method="pinLvRemoteMethod"
                       id="yz_frequCode"
                       ref="pingLv"/>
        </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"
                           ref="doseRef"
                           id="yz_dose"
                           :precision="yiZhuData.doseUnitName === yiZhuData.miniUnitName ? 0 : 2"
                           style="width: 110px"
                           @change="jiSuanLingLiang"/>
          <XcSelect v-model="yiZhuData"
                    id="yz_doseUnit"
                    :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 }}
          &nbsp;&nbsp;&nbsp;
          {{ yiZhuData.miniUnitName }}
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item class="bi_tian" label="给药方式:" prop="supplyCode">
          <xc-table-v3
              style="width: 120px"
              v-model="yiZhuData"
              :data="geiYaoFangShiData"
              id="yz_supplyCode"
              code="supplyCode"
              name="supplyCodeName"
              :remote-method="geiYaoFangShiRemoteMethod"
              clearable/>
        </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"
              id="yz_startTime"
              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"
              id="yz_endTime"
              :disabled="yiZhuData.frequCode === 'ONCE'"
              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">
          <xc-table-v3
              style="width: 120px"
              v-model="yiZhuData"
              :data="zhiXingKeShiData"
              id="yz_execUnit"
              code="execUnit"
              name="execUnitName"
              :remote-method="metZhiXingKeShi"/>
        </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'"
                     id="yz_parentNo"
                     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"
                    id="yz_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"
                     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>
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <el-form-item label="费用标志:">
          <el-select v-model="yiZhuData.selfBuy"
                     id="yz_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"
                     id="yz_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"
                     id="yz_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" filterable id="yz_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-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"
      @expand-change="expandChange"
  >
    <el-table-column type="expand">
      <template #default="props">
        <div v-if="feeInformation.get(props.row.id)" style="min-height: 40px;margin: 10px">
          <el-tag v-for="item in feeInformation.get(props.row.id)">
            {{ item }}
          </el-tag>
        </div>
      </template>
    </el-table-column>
    <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="220">
      <template #default="scope">
        <el-button circle icon="Edit" type="warning" @click="xiuGaiYiZhu(scope.row,scope.$index)"></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>
        <el-button circle icon="View" type="warning" @click="synopsis(scope.row)"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <yao-ping-xiang-qing v-if="synopsisDialog.dialog"
                       :code="synopsisDialog.code"
                       @close="synopsisDialog.dialog = false"/>
  <!-- 这里是获取模板的 -->
  <huo-qu-mu-ban v-if="muBanDuiHuaKuang"
                 :dialog="true"
                 @edit-template="editTemplate"
                 @close="muBanDuiHuaKuang = false"
                 @muBanShuJu="muBanShuJu"/>
  <!-- 保存模板用 -->
  <bao-cun-mu-ban v-if="baoCunMuBanRef" v-model="baoCunMuBanRef" :list="yiZhuList"/>

</template>

<script name="TianJiaYiZhu" setup="props,context">
import {
  huoQuFeiYongXinXi,
  huoQuGeiYaoFangShi,
  huoQuZhiXinKeShi,
  huoQuZhuYuanPinLv,
  singleDataCheck,
  huoQuXiangMu
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {
  fuZhiYiZhu,
  getSelfBuy,
  zkList,
  tableHeader
} 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 {ElMessage, ElMessageBox, ElNotification} 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, getTheTransferList} from '@/api/public-api'
import router from '@/router'
import YaoPingXiangQing from '@/components/zhu-yuan-yi-sheng/he-li-yong-yao/YaoPingXiangQing.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";
import XcTableV3 from "@/components/xiao-chan/select-v3/XcSelectV3.vue"
import {xcMessage} from "@/utils/xiaochan-element-plus";
import XcComboGrid from "@/components/xiao-chan/combo-grid/XcComboGrid";
import XcSelect from "@/components/xiao-chan/select/XcSelect";
import XcOption from "@/components/xiao-chan/select/XcOption";
import XcCode from "@/components/xiao-chan/code/XcCode";

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


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 groupNo = ref('73')

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

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)
    }
)

// 搜索医嘱
const xuanZhongFeiYong = async (row, newData = true) => {
  fuYiZhuClick()
  qingKong()
  await Sleep(200)
  yiZhuData.value = row
  if (row.serial !== '00') {
    let key = row.orderCode + '_' + row.serial + '_' + '' + '_' + groupNo.value
    huoQuFeiYongXinXi(key)
        .then((res) => {
          yiZhuData.value.drugFlag = row.drugFlag ? row.drugFlag : row.orderType
          // 判断是否 是皮试的药 如果是就只能有这些 给药方式
          geiYaoFangShiData.value = res.piShi
          // 是否是 抗菌药物
          yiZhuData.value.kjywFlag = res.data.kjywFlag
          // 提示信息
          tiShiBiaoTi.value = res.prompt
          // 最小单位名称
          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(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
            }
          }


        })
        .catch(async () => {
          await Sleep(500)
          qingKong()
        })
  } else {
    yiZhuData.value.kjywFlag = 0
    let key = row.orderCode + '_' + '00' + '_' + '' + '_' + groupNo.value
    huoQuFeiYongXinXi(key)
        .then((res) => {
          yiZhuData.value.drugFlag = row.drugFlag ? row.drugFlag : row.orderType
          if (stringNotBlank(res.prompt)) {
            tiShiBiaoTi.value = res.prompt
          }
          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)) {
    yiZhuData.value.execUnit = store.state.user.info.deptCode
    yiZhuData.value.execUnitName = store.state.user.info.deptName
  }

  if (newData) {
    yiZhuData.value.id = Number(uuid(8, 10));
  }

  if (!yiZhuData.value.frequCode) {
    yiZhuData.value.frequCode = 'ONCE'
    yiZhuData.value.frequCodeName = '一次'
  }

  try {
    pingLv.focus()
  } catch (e) {
    console.log(e)
  }
}

/* 频率 */
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
  jiSuanLingLiang(yiZhuData.value.dose)
}
/*计算领量*/
const jiSuanLingLiang = (val) => {
  if (jiLiangValue.value <= 0) return
  yiZhuData.value.drugQuan = Math.ceil(val / jiLiangValue.value);
}


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

/* 父医嘱 */
const fuYiZhuData = ref([])
const fuYiZhuClick = () => {
  fuYiZhuData.value = []
  for (let i = 0, len = yiZhuList.value.length; i < len; i++) {
    let data = yiZhuList.value[i]
    if (data.serial !== '00' && !data.parentNo) {
      fuYiZhuData.value.push({
        code: Number(data.id),
        name: data.orderName
      })
    }
  }
}

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

/* 这里是添加信息 */
const yiZhuList = ref([])
const tianJiaYiZhuWeiYiBiaoShi = ref([])
let errorElNotification = null
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('请选择转科科室.')
    }
  }
  let data = {
    list: [yiZhuData.value],
  }
  singleDataCheck(data).then((res) => {
    if (res.warning) {
      tiShiBiaoTi.value = res.warning
    }
    if (res.error) {
      if (errorElNotification !== null) {
        errorElNotification.close()
      }
      errorElNotification = ElNotification({
        title: '错误信息提示',
        message: res.error,
        type: 'error',
        duration: 0,
        showClose: false
      })
    } else {
      if (errorElNotification !== null) {
        errorElNotification.close()
      }
      let index = yiZhuList.value.findIndex(item => item.id === yiZhuData.value.id)
      if (index > -1) {
        yiZhuList.value.splice(index, 1)
        ElMessage.error('重复添加，老记录已删除。')
      }
      // 在这里要删除指定的 错误信息 key
      delete errorMessageData[yiZhuData.value.id]
      yiZhuList.value.push(res.data)
      qingKong()
      openSearch()
    }
  })
}

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

/* 这个是点击单个修改的 */
const xiuGaiYiZhu = (val, index) => {
  if (yiZhuData.value.orderCode) {
    xcMessage.warning('请先保存正在编辑的内容')
    return
  }
  xuanZhongFeiYong(val, false)
  xcMessage.success('你点击了修改')
  yiZhuList.value.splice(index, 1)
  tianJiaYiZhuWeiYiBiaoShi.value.splice(index, 1)
  whetherToResetTheDataSubscript()
}

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

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

// 展开table
let feeInformation = $ref(new Map())
const expandChange = (row, expandedRows) => {
  if (feeInformation.has(row.id)) {
    return
  }
  let key = row.orderCode + '_' + row.serial + '_' + '' + '_' + groupNo.value
  huoQuFeiYongXinXi(key).then((res) => {
    if (res.prompt) {
      feeInformation.set(row.id, res.prompt)
    }
  }).catch((e) => {
    feeInformation.set(row.id, [e])
  })
}


let synopsisDialog = $ref({
  dialog: false,
  code: ''
})

// 查看药品的使用信息
const synopsis = (val) => {
  synopsisDialog.dialog = true
  synopsisDialog.code = val.orderCode + '_' + val.serial
}

/* 医嘱错误信息 */
let errorMessageData = $ref({})


const clickError = (value) => {
  if (yiZhuData.value.orderCode) {
    ElMessage.warning({
      message: '请先保存正在编辑的内容',
      duration: 3000,
      showClose: true,
      grouping: true,
    })
  } else {
    xuanZhongFeiYong(value.data, false)
  }
}

// 模板数据
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)
    }
  }

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

const editTemplate = (data) => {
  muBanDuiHuaKuang = false
  yiZhuList.value = data
}

// 保存模板
const baoCunMuBanRef = ref(false)
const baoCunMuBanClick = () => {
  if (listIsBlank(yiZhuList.value)) {
    return ElMessage.error('请先选择数据')
  }
  baoCunMuBanRef.value = true
}


const xuanZhongShuJu = ref([])

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

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

const qingKong = () => {
  yaoPinJiLiangData.value = []
  jiLiangValue.value = 0
  tiShiBiaoTi.value = []
  yiZhuData.value = {
    id: null,
    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 = 1800
  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: '',
})

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

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

/// 这里是 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], dataIndex)
}

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

const searchRef = ref()
const openSearch = () => {
  searchRef.value.focus()
}

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

onMounted(async () => {
  xcHotKey(shortcutKeyRegistration)
  yiZhuList.value = clone(fuZhiYiZhu.value)
  let serverTime = await getServerDateApi();
  for (let i = 0; i < yiZhuList.value.length; i++) {
    yiZhuList.value[i].id = yiZhuList.value[i].actOrderNo
    yiZhuList.value[i].orderTime = serverTime
    yiZhuList.value[i].startTime = serverTime
    yiZhuList.value[i].endTime = serverTime
    yiZhuList.value[i].frequCodeName = '一次'
    yiZhuList.value[i].frequCode = 'ONCE'
  }
  document.title = '医嘱模板编辑'
  fuZhiYiZhu.value = []
  if (listIsBlank(zkList.value)) {
    zkList.value = await getTheTransferList()
  }

})


const cloneWindow = () => {
  router.push('/inpatient/zhuYuanYiSheng/yiZhuLuRu')
}

</script>

<style scoped lang="scss">

.prompt {
  display: flex;
  justify-content: start;
  background-color: #909399;
  color: white;
  align-items: center;
  border-radius: 5px;
  padding: 5px;
  margin: 5px;

  .item {
    display: flex;
    margin-right: 3px;

    div {
      background-color: #f56c6c;
      border-radius: 5px;
      padding: 3px;
    }
  }

}

.el-popover {
  height: 240px;
  overflow: auto;
}

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


</style>

<style lang="scss">

</style>
