<template>
  <div :style="{width: winsize.editor + 40 + 'px'}" style="margin: 0">
    <yz-query-condition :patient-info="huanZheXinXi"
                        ref="yzQueryRef"
                        :to-delete-an-order="toDeleteAnOrder"
                        :add-yi-zhu-click="addYiZhuClick"
                        :click-on-the-order-template="clickOnTheOrderTemplate"
                        :confirm-orders-click="confirmOrdersClick"/>
    <div>
      <div style="height: 5px"/>
      <button @click="orderTemplateClick">维护模板</button>
      <button @click="clickToStopTheOrder">批量停止</button>
      <el-divider direction="vertical"></el-divider>
      <button :disabled="stringIsBlank(huanZheXinXi.inpatientNo)"
              @click="clickToModifyTheDoctorSOrderTime">
        修改医嘱时间
      </button>
      <button :disabled="stringIsBlank(huanZheXinXi.inpatientNo)"
              @click="jumpToMedicalRecord">
        病案首页
      </button>
      <button @click="confirmAssociationClick">关联</button>
      <button @click="openRationalDrugUse">合理用药</button>
      <button @click="allergen.open()">患者过敏源信息维护</button>
      <button @click="openDualScreen">双屏模式</button>
    </div>
    <div style="height: 5px"/>
    <yz-editor :patient-info="huanZheXinXi"
               ref="yzEditorRef"
               :current-page="currentPage"
               :open-group-order-template="openGroupOrderTemplate"
               :successfullyEntered="successfullyEntered"/>
    <div style="overflow-x: auto; " :style="{width: winsize.main - 20  + 'px'}">
      <yz-table :data="tempYzData"
                ref="tableRef"
                @rowClick="rowClick"
                @clickAssociate="clickAssociate"
                :void-orders="voidOrdersClick"/>
    </div>

    <doctor-s-order-fee :data="chargeDetails.data"
                        v-if="chargeDetails.dialog"
                        :sum="chargeDetails.sum"
                        @close="chargeDetails.dialog = false"/>
    <!--  获取模板的数据  -->
    <huo-qu-mu-ban
        ref="mubanRef"
        :editor="false"
        @muBanShuJu="muBanShuJu"/>

    <xc-dialog v-model="stopOrderDialog.dialog" title="停止医嘱错误信息">
      <div v-for="(value,key) in stopOrderDialog.error">
        医嘱号： {{ key }} 序号： {{ getYzIndex(key) + 1 }}
        <br>
        {{ value }}
      </div>
    </xc-dialog>

    <yao-ping-xiang-qing v-if="drugManual.dialog"
                         :code="drugManual.code"
                         @close="drugManual.dialog = false"/>

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

    <order-progress ref="orderProgressRef"/>

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

</template>

<script name="YiZhuLuRuZhuJian" setup>
import {
  associateOrdersApi,
  insertTemplateOrder,
  stopOrder, voidOrders,
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {
  huanZheXinXi,
  getYzIndex,
  winsize,
  zkList,
  selectedData,
  queryParam,
  currentPage,
  clickOnThePatient,
  drugManual,
  associateOrders,
  clearAssociate, youWuXuanZheHuanZhe, isOpenDualScreen, dualScreenSrc
} from '../public-js/zhu-yuan-yi-sheng'
import store from '@/store'
import {stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {getTheTransferList} from '@/api/public-api'
import router from '@/router'
import sleep from "@/utils/sleep";
import DoctorSOrderFee from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/DoctorSOrderFee.vue";
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 YzTable from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/table/YzTable";
import YzEditor from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/yz-edit/YzEditor.vue";
import {tempYzData} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import HuoQuMuBan from '@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/HuoQuMuBan.vue'
import {getFormatDatetime} from "@/utils/date";
import XcDialog from "@/components/xiao-chan/dialog/XcDialog";
import {xcMessage} from "@/utils/xiaochan-element-plus";
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 OrderProgress from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/OrderProgress.vue";
import {getEmrUrl} from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init";
import RationalDrugUseWindow from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/RationalDrugUseWindow.vue";

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

const user = computed(() => {
  return store.state.user.info
})

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

// 医嘱查询
const yzQueryRef = ref(null)
// 医嘱进度
const orderProgressRef = ref(null)

// 医嘱编辑
const yzEditorRef = ref(null)
const successfullyEntered = async () => {
  await yzQueryRef.value.queryYz()
  queryParam.value.displayRange = 0
  queryParam.value.frequCode = 0
  queryParam.value.zhuangTai = 0
  tableRef.value.scrollToTheEnd()
  addYiZhuClick()
}
/**
 * 下面这里是添加医嘱了
 */
const addYiZhuClick = () => {
  yzEditorRef.value.addOrderNo()
}

const reasonableRef = ref(null)

/**
 * 确认医嘱 , 已经做过无患者的判断了
 */
const confirmOrdersClick = async () => {
  // 如果没有问题就可以直接确认医嘱了。
  let temp = await reasonableRef.value.check(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes)
  if (temp) {
    await confirmOrder()
    console.log('无错误药品直接确认');
  }
}

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

/**
 * 删除医嘱
 */
const toDeleteAnOrder = () => {
  yzEditorRef.value.toDeleteAnOrderClick()
}

const openRationalDrugUse = () => {
  window.open('http://172.16.32.121:9097/index.html')
}

// 表格
let tableRef = ref(null)
const rowClick = (val) => {
  orderProgressRef.value.fillOrder(val)
  if (associateOrders.value.actOrderNo) {
    let index = associateOrders.value.associatedGroup.indexOf(val.actOrderNo)
    if (associateOrders.value.actOrderNo === val.actOrderNo) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联自己');
    }
    if (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 stopOrderDialog = ref({
  dialog: false,
  error: ''
})

/**
 * 停止医嘱
 */
const clickToStopTheOrder = () => {
  selectedData.value.forEach(item => {
    item.endTime = getFormatDatetime(item.endTimeTemp)
  })
  let param = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    list: selectedData.value
  }
  stopOrder(param).then(res => {
    if (res?.error) {
      stopOrderDialog.value.error = res.data
      stopOrderDialog.value.dialog = true
      for (let i = 0; i < selectedData.value.length; i++) {
        let item = selectedData.value[i]
        item.endTime = ''
      }
    } else {
      stopOrderDialog.value.error = {}
      yzQueryRef.value.queryYz()
    }
  })
}


/**
 * 作废医嘱
 */
const voidOrdersClick = (val) => {
  ElMessageBox.prompt(`请问是否要撤销<br><span style="color: red">【${val.orderName}】</span>医嘱<br>
                        撤销父医嘱会自动撤销子医嘱。`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (val) => {
      if (val === null || val.length < 1 || val.length > 50) {
        return false;
      }
    },
    dangerouslyUseHTMLString: true,
    inputErrorMessage: '作废原因，不能为空，最多可输入50个字符。',
    closeOnPressEscape: false,
    closeOnClickModal: false
  }).then(({value}) => {
    voidOrders(val.id, value).then(res => {
      yzQueryRef.value.queryYz()
    })
  }).catch(() => {

  })
}


/**
 * 右键点击查看医嘱产生的费用
 * @param val
 */
let doctorSOrderFee = $ref({
  data: {},
  problem: {},
  totalCost: {}
})
let chargeDetails = $ref({
  dialog: false,
  data: [],
  sum: {}
})

const clickToViewTheDoctorSOrderFee = (val) => {
  chargeDetails.data = doctorSOrderFee.data[val.actOrderNoStr]
  if (chargeDetails.data) {
    chargeDetails.sum = doctorSOrderFee.totalCost[val.actOrderNoStr]
    chargeDetails.dialog = true
  } else {
    BizException(ExceptionEnum.MESSAGE_ERROR, '该医嘱还没有产生费用')
  }
}

// 获取模板
const mubanRef = ref(null)
const muBanDuiHuaKuang = ref(false)
const clickOnTheOrderTemplate = () => {
  if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }
  mubanRef.value.openOrCloseDialog(true)
  muBanDuiHuaKuang.value = true
}
/**
 * 把模板的数据插入到患者的医嘱表
 * @param val
 */
const muBanShuJu = (val) => {
  if (currentPage.value === 'takeMedicine') {
    val = val.filter((item) => {
      item.selfBuy = '4'
      item.instruction = item.frequCodeName
      return item.serial !== '00'
    })
    if (val.length === 0) {
      BizException(ExceptionEnum.LOGICAL_ERROR, '项目无法出院带药。')
    }
  }
  let param = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    groupNo: queryParam.value.groupNo,
    list: val
  }
  insertTemplateOrder(param).then(() => {
    successfullyEntered()
    muBanDuiHuaKuang.value = false
    mubanRef.value.openOrCloseDialog(false)
  })
}

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


/**
 * 添加模板
 */
const orderTemplateClick = () => {
  router.push({
    name: 'orderTemplateMaintenance',
  })
}

onMounted(async () => {
  await sleep(200)
  zkList.value = await getTheTransferList()
})


// 点击修改医嘱时间
const clickToModifyTheDoctorSOrderTime = () => {
  router.push({
    name: 'yzActOrderModify',
    query: {
      patNo: huanZheXinXi.value.inpatientNo,
    },
  })
}

// 跳转到病案首页
const jumpToMedicalRecord = () => {
  router.push({
    name: 'fillCaseFrontSheet',
    query: {
      patNo: huanZheXinXi.value.inpatientNo,
      deptCode: huanZheXinXi.value.smallDept,
    },
  })
}

// 点击关联
const clickAssociate = async (data) => {
  if (stringNotBlank(data.parentNo)) {
    xcMessage.error('该医嘱已经有父医嘱了。');
  } else if (data.statusFlag !== '1') {
    xcMessage.error('不是录入状态的医嘱无法关联。');
  } else if (data.serial === '00') {
    xcMessage.error('项目无法关联。');
  } else {
    if (associateOrders.value.actOrderNo === null) {
      await yzQueryRef.value.queryYz()
      associateOrders.value.actOrderNo = data.actOrderNo
    } else {
      xcMessage.error('请先确认当前关联医嘱。')
    }
  }
}

// 点击确认关联
const confirmAssociationClick = () => {
  if (associateOrders.value.actOrderNo === null) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择需要关联的父医嘱')
  }
  if (associateOrders.value.associatedGroup.length === 0) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '至少选择一个子医嘱')
  }
  ElMessageBox.confirm('请确认是否要关联这些医嘱。', '提示', {
    type: 'warning'
  }).then(() => {
    associateOrdersApi(associateOrders.value).then((res) => {
      clearAssociate()
      yzQueryRef.value.queryYz()
    })
  }).catch(() => {
  })
}

const openDualScreen = () => {
  if (youWuXuanZheHuanZhe()) return
  isOpenDualScreen.value = !isOpenDualScreen.value
  dualScreenSrc.value = getEmrUrl(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes, 1)
}

watch(() => router.currentRoute.value, () => {
  currentPage.value = router.currentRoute.value.query.pattern
}, {immediate: true})

onActivated(async () => {
  if (router.currentRoute.value.params.inpatientNo) {
    await nextTick()
    clickOnThePatient(router.currentRoute.value.params.inpatientNo);
  }
})


</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>
