<template>
  <div class="layout_container">
    <header>
      <yz-query-condition :patient-info="huanZheXinXi"
                          @batchDeleteOrdersClick="batchDeleteOrdersClick"
                          :click-on-the-order-template="clickOnTheOrderTemplate"
                          :confirm-orders-click="confirmOrdersClick"/>

      <yz-editor :patient-info="huanZheXinXi"
                 ref="yzEditorRef"
                 :open-group-order-template="openGroupOrderTemplate"/>
    </header>
    <div class="layout_main">
      <div style="height: 100%;width: calc(100% - 10px)">
        <YzTableV3
            @void-orders="voidOrdersClick"
            @rowClick="rowClick"/>
      </div>
    </div>
  </div>
  <!--  获取模板的数据  -->
  <huo-qu-mu-ban
      ref="mubanRef"
      :editor="false"
      @muBanShuJu="muBanShuJu"/>

  <!-- 这个是过敏源的 -->
  <AllergenEntry v-if="allergen.dialog"
                 :pat-no="huanZheXinXi.inpatientNo"
                 @close="allergen.dialog = false"/>

  <!--  合理用药窗口  -->
  <rational-drug-use-window ref="reasonableRef" @submit="confirmOrder"/>
  <fee-table/>
</template>

<script setup lang="ts">
import {deleteMultipleOrders, insertTemplateOrder,} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {
  associateOrders,
  clickOnThePatient,
  confirmLoading,
  errorMsgFunc,
  huanZheXinXi,
  queryParam,
  setYzOrderGroup,
  youWuXuanZheHuanZhe,
  yzData,
  yzMitt,
  YzType,
  zkList
} from '../public-js/zhu-yuan-yi-sheng'
import {stringIsBlank} from '@/utils/blank-utils'
import {getTheTransferList} from '@/api/public-api'
import router from '@/router'
import sleep from "@/utils/sleep";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {ElMessageBox} from "element-plus";
import YzQueryCondition from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/yz-header/YzQueryCondition";
import YzEditor from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/yz-edit/YzEditor.vue";
import HuoQuMuBan from '@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/HuoQuMuBan.vue'
import AllergenEntry from "@/components/zhu-yuan-yi-sheng/AllergenEntry.vue";
import RationalDrugUseWindow from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/RationalDrugUseWindow.vue";
import FeeTable from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/FeeTable.vue";
import {applicationForRevocation} from "@/api/zhu-yuan-yi-sheng/qrder-quash";
import XEUtils from 'xe-utils'
import {nextTick, onActivated, onMounted, ref} from 'vue'
import {CyMessageBox} from "@/components/cy/message-box";
import YzTableV3 from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/table/YzTableV3.vue";
import doctorStore, {YzSidebarEnum} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/useDoctorStore";
import {isDev} from "@/utils/public";

const allergen = ref({
  dialog: false,
  open: () => {
    if (youWuXuanZheHuanZhe()) return
    allergen.value.dialog = true
  }
})


// 医嘱编辑
const yzEditorRef = ref(null)


const reasonableRef = ref(null)

/**
 * 确认医嘱 , 已经做过无患者的判断了
 */
const confirmOrdersClick = async () => {
  if (isDev) {
    await confirmOrder()
    return
  }

  // 如果没有问题就可以直接确认医嘱了。
  let temp = await reasonableRef.value.check(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes);
  if (temp) {
    await confirmOrder()
  }
}

// 真正的向后台确认医嘱
const confirmOrder = async () => {
  confirmLoading.value = true
  // 确认医嘱
  await yzEditorRef.value.confirmOrdersClick()
  // 查询医嘱
  await yzMitt.emit('queryYz');
  confirmLoading.value = false
}

const rowClick = (val: YzType) => {
  if (associateOrders.value.actOrderNo) {
    let index = associateOrders.value.associatedGroup.indexOf(val.actOrderNo)
    if (associateOrders.value.actOrderNo === val.actOrderNo) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联自己');
    }

    if (val.orderCode !== '06054' && val.serial === '00') {
      BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联项目');
    }
    if (val.statusFlag !== '1') {
      BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联不是录入状态的医嘱。');
    }
    if (index > -1) {
      val.associationFlag = false;
      associateOrders.value.associatedGroup.splice(index, 1);
    } else {
      val.associationFlag = true;
      associateOrders.value.associatedGroup.push(val.actOrderNo);
    }
  } else {
    yzEditorRef.value.fillData(val)
  }

}

const orderQuash = async (val) => {

  if (val.statusFlag === '2') {
    BizException(ExceptionEnum.LOGICAL_ERROR, "确认医嘱无需撤销删除即可。");
  }

  if (val.statusFlag === '1') {
    BizException(ExceptionEnum.LOGICAL_ERROR, "录入医嘱无需撤销删除即可。");
  }

  CyMessageBox.prompt({
    message: `申请撤销<span style="color: red">【${val.orderName}】</span>医嘱<br />
可在数据修改 》 医嘱撤销审核页面中查看到自己的申请信息。<br />
<span style="color:red">作废医嘱不会退费，需要在项目录入中退费，如果是药品先撤销后退费的话，会导致项目录入中无法退费，作废前可以先进行停止操作看费用会不会退掉，如果停止医嘱没有产生退费可以让护士在项目录入中退费，退费前请记得做费用接收重算，避免重复退费。</span><br />
<span style="color: #0900ff">医嘱未超过24小时，未产生任何费用，会直接撤销无需审核，其他需要医务部审核通过后才能撤销。</span>
`,
    type: 'warning',
    dangerouslyUseHTMLString: true,
    inputDefaultValue: '医嘱开错',
    selectOption: [
      {code: '医嘱开错', name: '医嘱开错'},
      {code: '未充分告知患者', name: '未充分告知患者'},
      {code: '临时出院', name: '临时出院'},
      {code: '患者拒绝用药', name: '患者拒绝用药'},
      {code: '药房缺药', name: '药房缺药'},
      {code: '药物不耐受或过敏', name: '药物不耐受或过敏'},
      {code: '药品更换厂家或规格', name: '药品更换厂家或规格'},
      {code: '转科或者转院', name: '转科或者转院'},
      {code: '病情变化', name: '病情变化'},
      {code: '患者欠费未生成药单', name: '患者欠费未生成药单'},
    ],
    inputMaxLength: 50,
  }).then(async ({value}) => {
    let res = await applicationForRevocation({
      actOrderNo: val.actOrderNo,
      reqRemark: value,
      patNo: val.inpatientNo,
      times: val.admissTimes
    });
    // res === 1的意思是这个医嘱被删除了
    if (res === 1) {
      XEUtils.remove(yzData.value, (item) => {
        return item.actOrderNo === val.actOrderNo;
      })
      setYzOrderGroup();
    }
  }).catch(() => {
  })
}

/**
 * 作废医嘱
 */
const voidOrdersClick = (val) => {
  orderQuash(val)
}


// 获取模板
const mubanRef = ref(null)
const clickOnTheOrderTemplate = () => {
  if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }
  mubanRef.value.openOrCloseDialog(true)
}
/**
 * 把模板的数据插入到患者的医嘱表
 * @param val
 */
const muBanShuJu = (val) => {
  let tempGroupNo = ['71', '73']
  if (queryParam.value.frequCode === 'takeMedicine') {
    val = val.filter((item) => {
      item.selfBuy = '4'
      if (stringIsBlank(item.instruction)) {
        item.instruction = item.frequCodeName;
      }
      item.supplyCode = '007'
      item.frequCode = 'ONCE'
      return item.serial !== '00'
    })
    if (val.length === 0) {
      BizException(ExceptionEnum.LOGICAL_ERROR, '项目无法出院带药。')
    }
  }
  val.forEach(item => {
    if (item.serial === '00') {
      item.groupNo = '00'
    } else {
      if (!tempGroupNo.includes(item.groupNo)) {
        item.groupNo = queryParam.value.groupNo;
      }
    }
  })
  let param = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    groupNo: queryParam.value.groupNo,
    list: val
  }
  insertTemplateOrder(param).then(async (list) => {
    mubanRef.value.openOrCloseDialog(false)
    yzData.value.push(...list.data)
    let temp = {}
    XEUtils.arrayEach(list.list, (item) => {
      temp[item] = true
    })
    yzMitt.emit('scrollEndAndTwinkle', temp)
  })
}

/**
 * 打开模板的对话框
 * @param code
 * @returns {Promise<void>}
 */
const openGroupOrderTemplate = async (code) => {
  mubanRef.value.openOrCloseDialog(true)
  await nextTick()
  mubanRef.value.openTemplateByCode(code)
}

/**
 * 点击批量删除数据
 */
const batchDeleteOrdersClick = () => {

  let tempData = yzMitt.emit('getSelectedData')

  if (tempData!.length === 0) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择要删除的数据");
  }

  ElMessageBox.confirm('是否要批量删除这些医嘱？', '提示', {
    type: 'warning'
  }).then(() => {
    let param = {
      inpatientNo: huanZheXinXi.value.inpatientNo,
      admissTimes: huanZheXinXi.value.admissTimes,
      list: tempData
    }
    deleteMultipleOrders(param).then((res) => {
      if (res !== null && res.error) {
        let errData = {}
        for (const key in res.data) {
          errData[key] = {
            warning: [res.data[key]],
            isDel: true
          }
        }
        errorMsgFunc.add(errData)
      } else {
        yzMitt.emit('queryYz', false)
      }
    })
  }).catch(() => {
  })
}

onMounted(async () => {
  yzMitt.on("allergen", allergen.value.open)
  yzMitt.on('clickOnTheOrderTemplate', clickOnTheOrderTemplate)
  yzMitt.on('rowClick', rowClick)
  await sleep(200)
  zkList.value = await getTheTransferList()
})

onActivated(async () => {
  if (router.currentRoute.value.params.inpatientNo) {
    await nextTick()
    await clickOnThePatient(<string>router.currentRoute.value.params.inpatientNo);
    await yzMitt.emit('queryYz')
  }
  doctorStore.setYzSidebar(YzSidebarEnum.PATIENT_LIST);
})
</script>

<style scoped lang="scss">
:deep(.el-table .children-row) {
  background: rgba(145, 247, 145, 0.93);
}

:deep(.el-table) {
  --el-table-row-hover-background-color: #85dbfd7a;
}

:deep(.el-dropdown-menu__item) {
  font-size: 14px !important;
  height: 26px;
  line-height: 26px;
  font-weight: bold;
}

</style>
