<template>
  <div style="margin: 0;height: 100%">
    <div ref="editSizeRef">
      <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"
                 @successfullyEntered="successfullyEntered"/>
    </div>

    <yz-table-v2 ref="tableRef"
                 :height="editSizeRef?.clientHeight"
                 @void-orders="voidOrdersClick"
                 @clickAssociate="clickAssociate"
                 @rowClick="rowClick"/>

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

    <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"/>
    <fee-table/>
  </div>
</template>

<script name="YiZhuLuRuZhuJian" setup>
import {
  associateOrdersApi, deleteMultipleOrders, getFrequency, getSupplyType, huoQuYiZhuShuJu,
  insertTemplateOrder,
  stopOrder, voidOrders,
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {
  huanZheXinXi,
  getYzIndex,
  zkList,
  queryParam,
  clickOnThePatient,
  drugManual,
  associateOrders,
  clearAssociate, youWuXuanZheHuanZhe, yzData, errorMsg, yzMitt, jsQueryYzData, geiYaoFangShiData, yaoPinPingLvData
} from '../public-js/zhu-yuan-yi-sheng'
import store from '@/store'
import {listIsBlank, stringIsBlank, stringNotBlank} 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 {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 RationalDrugUseWindow from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/RationalDrugUseWindow.vue";
import ReportOfInfectiousDiseases
  from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/report-of-infectious-diseases/ReportOfInfectiousDiseases.vue";
import YzTableV2 from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/table/YzTableV2.vue";
import {clone} from "@/utils/clone";
import BloodSugar from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/BloodSugar.vue";
import FeeTable from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/FeeTable.vue";
import {isDev} from "@/utils/public";
import {applicationForRevocation} from "@/api/zhu-yuan-yi-sheng/qrder-quash";
import YzTableV3 from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/table/YzTableV3.vue";
import Test from "@/views/settings/Test.vue";
import OrderTool from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/order/OrderTool.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 orderProgressRef = ref(null)

// 医嘱编辑
const yzEditorRef = ref(null)
const successfullyEntered = async (data) => {
  queryParam.value.displayRange = 0
  queryParam.value.zhuangTai = 0
  yzData.value = await huoQuYiZhuShuJu({
    patNo: huanZheXinXi.value.inpatientNo,
    times: huanZheXinXi.value.admissTimes
  })
  yzMitt.emit('clearSelected')
  if (data != null) {
    tableRef.value.scrollTo(data.actOrderNo.toString())
  }
  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()
  }
}

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


// 表格
const 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.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 = (val) => {
  if (val.statusFlag == '2') {
    BizException(ExceptionEnum.LOGICAL_ERROR, "确认医嘱无需撤销删除即可。");
  }
  if (val.statusFlag == '1') {
    BizException(ExceptionEnum.LOGICAL_ERROR, "录入医嘱无需撤销删除即可。");
  }

  ElMessageBox.prompt(`申请撤销<span style="color: red">【${val.orderName}】</span>医嘱，医务部通过审核后医嘱自动撤销。`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (val) => {
      val = val.trim()
      if (val === null || val.length < 1 || val.length > 50) {
        return false;
      }
    },
    dangerouslyUseHTMLString: true,
    inputErrorMessage: '作废原因，不能为空，最多可输入20个字。',
    closeOnPressEscape: false,
    closeOnClickModal: false
  }).then(({value}) => {
    applicationForRevocation({
      actOrderNo: val.actOrderNo,
      reqRemark: value,
      patNo: val.inpatientNo,
      times: val.admissTimes
    }).then(res => {
      if (res === 1) {
        yzMitt.emit('queryYz')
      }
    })
  })
}

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

  ElMessageBox.prompt(`请问是否要撤销<br><span style="color: red">【${val.orderName}】</span>医嘱<br>
                        撤销父医嘱会自动撤销子医嘱。`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (val) => {
      val = val.trim()
      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 => {
      yzMitt.emit('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 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)
    await successfullyEntered()
    let data = {}
    list.forEach(item => {
      data[item] = true
    })
    tableRef.value.callTemplate(data)
  })
}

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

// 点击关联
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 yzMitt.emit('queryYz')
      associateOrders.value.actOrderNo = data.actOrderNo
    } else {
      xcMessage.error('请先确认当前关联医嘱。')
    }
  }
}

/**
 * 点击批量删除数据
 */
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) {
          let index = getYzIndex(key)
          let tempYzData = yzData.value[index]
          yzData.value[index].error = true
          errData.push({
            actOrderNo: key,
            orderName: tempYzData.orderName,
            errorMessage: res.data[key]
          })
        }
        errorMsg.value.dialog = true
        errorMsg.value.type = 2
        errorMsg.value.data = errData
      } else {
        yzMitt.emit('queryYz', false)
      }
    })
  }).catch(() => {
  })
}

const editSizeRef = ref(null)

onMounted(async () => {

  yzMitt.on("allergen", allergen.open)

  yzMitt.on('clickOnTheOrderTemplate', clickOnTheOrderTemplate)

  getSupplyType().then(res => {
    geiYaoFangShiData.value = res
  })
  getFrequency().then(res => {
    yaoPinPingLvData.value = res
  })
  await sleep(200)
  zkList.value = await getTheTransferList()

})


onActivated(async () => {
  if (router.currentRoute.value.params.inpatientNo) {
    await nextTick()
    await clickOnThePatient(router.currentRoute.value.params.inpatientNo);
    await yzMitt.emit('queryYz')
  }
  jsQueryYzData()
})


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