<template>
  <div>
    <div style="display: flex;align-items: center">
      <el-button @click="queryYz" v-title="'重新查询患者的医嘱'">重置</el-button>
      <el-divider direction="vertical"/>
      <label>
        显示范围：
        <select v-model="queryParam.displayRange" v-title="'显示范围'">
          <option :value="0" title="全部的医嘱">全部</option>
          <option :value="1" title="已经停止的医嘱">停止</option>
          <option :value="2" title="正在执行的长期医嘱">当前</option>
          <option :value="3" title="今天开的医嘱">今天</option>
        </select>
      </label>

      <label>
        状态：
        <select v-model.number="queryParam.zhuangTai" title="医嘱的状态">
          <option :value="0">全部</option>
          <option :value="1">录入</option>
          <option :value="2">确认</option>
          <option :value="3">执行</option>
          <option :value="5">停止</option>
        </select>
      </label>
      <label>
        药房：
        <select v-model="queryParam.groupNo" v-title="'在新增医嘱的时候，去指定的药房查询药品。'">
          <option value="73">住院</option>
          <option value="71">门诊</option>
        </select>
      </label>

      <el-divider direction="vertical"/>

      <el-button-group>
        <el-button type="primary"
                   @click="addYiZhuClick"
                   v-title="'添加医嘱，快捷键 ALT+A'">
          添加
        </el-button>

        <el-button type="success"
                   :loading="confirmLoading"
                   @click="currentConfirmOrdersClick"
                   v-title="'把录入状态的医嘱，变为确认状态。'"
                   v-if="!isCydy()">
          确认
        </el-button>

        <el-button type="success"
                   @click="confirmTheDoctorSOrderWithMedicineClick"
                   v-else
                   v-title="'把录入状态的医嘱，变为确认状态。'">
          确认带药
        </el-button>


      </el-button-group>
      <el-divider direction="vertical"/>
      <el-dropdown split-button
                   type="danger"
                   @click="deleteAnOrderByOrderNo"
                   v-title="'在表格中选中了一条医嘱后这个方法才能有效果，（这个医嘱需要在工作台显示），也可以在点击表格后面的删按钮<br /><span style=\'color:#fffe00\'>限制：</span>只能删除自己开的，只能删除(录入、确认)状态的医嘱。'">
        删除
        <template #dropdown>
          <el-dropdown-menu>
            <div
                v-title="'在表格中，点击前面的选择框，选中医嘱（多条或单挑），才能点击此按钮，限制：只能删除自己开的，只能删除(录入、确认)状态的医嘱。'">
              <el-dropdown-item @click="batchDeleteOrdersClick">
                批量删除
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-divider direction="vertical"/>

      <el-dropdown split-button
                   @click="yzMitt.emit('clickOnTheOrderTemplate')"
                   v-title="'获取医嘱的模板'">
        模板
        <template #dropdown>
          <el-dropdown-menu>
            <div v-title="'维护自己创建的模板'">
              <el-dropdown-item @click="orderTemplateClick">
                维护模板
              </el-dropdown-item>
            </div>
            <div v-title="'选中表格中的医嘱作为模板'">
              <el-dropdown-item @click="orderTemplateClickCopy">
                选中医嘱做模板
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div style="border-top: 1px solid #000; margin: 5px 0"/>
    <div>
      <el-dropdown split-button
                   @click="clickToStopTheOrder"
                   v-title="'批量停止医嘱，需要结束时间一栏的日期数据框变成红色则代表，是要停止这条医嘱。<br />' +
                    '双击日期输入框，默认填充停止到当前时间，并选中医嘱，可点击输入框中的日历，去选择其他时间。<br />' +
                     '鼠标右键数据框，可以取消停止。'">
        批量停止
        <template #dropdown>
          <el-dropdown-menu>
            <div v-title="'跳转到这个患者，修改医嘱时间的申请页面。'">
              <el-dropdown-item @click="clickToModifyTheDoctorSOrderTime">
                修改医嘱时间
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown split-button v-title="'跳转到指定患者的数据页面'">
        页面跳转
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="jumpToMedicalRecord">
              病案首页
            </el-dropdown-item>

            <el-dropdown-item @click="openRationalDrugUse">
              合理用药
            </el-dropdown-item>
            <el-dropdown-item @click="routerBloodSugarClick">
              血糖
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown split-button
                   v-title="'设置选中医嘱成组。'"
                   @click="confirmAssociationClick">
        关联
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="clearAssociate()">取消关联</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown
          v-title="'患者数据维护，包含传染病、过敏源。'"
          split-button>
        数据维护
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
                @click="yzMitt.emit('allergen')">
              过敏源维护
            </el-dropdown-item>
            <el-dropdown-item @click="crbOpen">
              传染病上报
            </el-dropdown-item>
            <el-dropdown-item
                @click="router.push(`/outpatient/chronicDisease/chronicDiseaseRegister/${props.patientInfo.inpatientNo}`)">
              慢病登记
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown v-title="'工作台操作，录入、清空、医嘱弹窗、复制粘贴'"
                   @click="yzMitt.emit('toAddAnOrder')"
                   split-button>
        录入医嘱
        <template #dropdown>
          <el-dropdown-menu>
            <div v-title="'清空，正在编辑的医嘱或者选中的医嘱。'">
              <el-dropdown-item
                  @click="yzMitt.emit('emptyTheWorkbench')">
                清空工作台
              </el-dropdown-item>
            </div>
            <div v-title="'打开医嘱弹窗，目前只有转科、抗菌药物信息、处置医嘱可以打开弹窗。'">
              <el-dropdown-item @click="yzMitt.emit('openTheOrderPopUpWindow')">
                医嘱弹窗
              </el-dropdown-item>
            </div>
            <div v-title="'复制并粘贴医嘱，如果想要分开，请在表格中鼠标右键一个医嘱，选择复制，然后在到表格中，选择粘贴医嘱。<br /><br />' +
             '<span style=\'color:#fffe00\'>注意：</span>如果你是在临时医嘱页面，那么长期医嘱会改为 ONCE 频率，如果在长期医嘱页面那么临时医嘱会改为 QD 频率，如果是成组的医嘱' +
              '复制父医嘱即可子医嘱会自动复制，目前不会提供批量复制医嘱的功能。'">
              <el-dropdown-item
                  @click="yzMitt.emit('duplicateAndPaste')">
                复制并粘贴
              </el-dropdown-item>
            </div>

            <div v-title="'<span style=\'color:#fffe00\'>带有实验性质的功能，如果此方法出错频率高，后期可能会删除。</span>' +
             '<br />复制选中的医嘱并粘贴。'">
              <el-dropdown-item @click="openCopyDialog">
                复制选中的医嘱
              </el-dropdown-item>
            </div>

          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown title="其他操作"
                   split-button>
        其他
        <template #dropdown>
          <el-dropdown-menu>
            <div v-title="'为即将出院的患者预约门诊，如果患者没有门诊号的话，需要先创建一个门诊号。'">
              <el-dropdown-item
                  @click="outPatientDialogOpen()">
                门诊预约
              </el-dropdown-item>
            </div>
            <div v-title="'一键停止正在执行的医嘱，会生成一条医嘱，此医嘱是口头医嘱，有没任何效果。'">
              <el-dropdown-item
                  @click="oneClickStopOpen">
                一键停止
              </el-dropdown-item>
            </div>
            <el-dropdown-item @click="clickTimeLimitReminder">
              时限提示
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-button type="success" icon="RefreshRight" @click="rcvrcalcost"
                 v-title="'如果患者费用存在问题或者有些费用看不到，<br />可以执行此操作。'"> 费用接收重算
      </el-button>

    </div>
  </div>

  <!--  门诊预约 -->
  <outpatient-appointments v-if="outPatientDialog"
                           @closed="outPatientDialog  = false"/>

  <one-click-stop v-if="oneClickStopDialog"
                  @closed="oneClickStopDialog  = false"/>

  <CopyTableDataOrder v-model="copyTableDialog"
                      v-if="copyTableDialog"/>
</template>

<script setup>
import {
  associateOrdersApi,
  confirmTheDoctorSOrderWithMedicine,
  huoQuYiZhuShuJu, stopOrder
} from "@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru";
import {
  associateOrders,
  clearAssociate,
  confirmLoading,
  errorMsg,
  huanZheXinXi,
  isCydy,
  queryParam,
  setOrderDataAndTwinkle,
  yiZhuData,
  yiZhuDataInit,
  youWuXuanZheHuanZhe,
  yzData,
  yzMitt,
  clickTimeLimitReminder
} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import router from "@/router";
import {clone} from "@/utils/clone";
import {listIsBlank, stringIsBlank} from "@/utils/blank-utils";
import {xcMessage} from "@/utils/xiaochan-element-plus";
import {getFormatDatetime} from "@/utils/date";
import {ElMessageBox} from "element-plus";
import ReportOfInfectiousDiseases
  from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/report-of-infectious-diseases/ReportOfInfectiousDiseases.vue";
import OutpatientAppointments
  from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/OutpatientAppointments.vue";
import OneClickStop from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/OneClickStop.vue";
import {getPatientInfo, receiveAndRecalculateCost} from "@/api/inpatient/patient";
import CopyTableDataOrder
  from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/table/CopyTableDataOrder.vue";
import setDialogToJs from "@/components/js-dialog-comp/useDialogToJs";

const props = defineProps({
  patientInfo: {
    type: Object
  },
  returnData: {
    type: Function
  },
  frequCodeChange: Function,
  confirmOrdersClick: Function,
  clickOnTheOrderTemplate: Function
})

const emits = defineEmits(['batchDeleteOrdersClick'])

const copyTableDialog = ref(false)
const openCopyDialog = () => {
  if (youWuXuanZheHuanZhe()) return
  copyTableDialog.value = true
}

const queryYz = async (tableScrollTop = true) => {
  if (!props.patientInfo.inpatientNo) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }

  try {
    yiZhuDataInit()
    yzMitt.emit('clearSelected')
    if (tableScrollTop) {
      yzMitt.emit('tableScroll', 0);
    }
    yzData.value = await huoQuYiZhuShuJu({
      patNo: props.patientInfo.inpatientNo,
      times: props.patientInfo.admissTimes
    })
  } catch (e) {
    yzData.value = []
  }

}

const addYiZhuClick = () => {
  yzMitt.emit('toAddAnOrder')
}

const currentConfirmOrdersClick = () => {
  if (!props.patientInfo.inpatientNo) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }
  props.confirmOrdersClick()
}

/**
 * 确认医嘱
 */
const confirmTheDoctorSOrderWithMedicineClick = () => {
  if (!props.patientInfo.inpatientNo) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
  }
  confirmLoading.value = true
  confirmTheDoctorSOrderWithMedicine(props.patientInfo.inpatientNo, props.patientInfo.admissTimes).then((res) => {
    if (res?.error) {
      errorMsg.value.type = YzErrTypeEnum.确认错误
      errorMsg.value.dialog = true
      errorMsg.value.data = res.data
    } else {
      queryYz()
      confirmLoading.value = false
    }
  })
}

const deleteAnOrderByOrderNo = () => {
  yzMitt.emit('deleteAnOrderByOrderNo', yiZhuData.value)
}

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

/**
 * 跳转到模板页面
 */
const orderTemplateClick = () => {
  router.push({
    name: 'orderTemplateMaintenance',
  })
}

/**
 * 选中复制的医嘱
 */
const orderTemplateClickCopy = () => {
  let temp = clone(yzMitt.emit('getSelectedData'))
  if (listIsBlank(temp)) {
    xcMessage.error('请先选中医嘱。')
    return
  }
  let dept = {
    code: huanZheXinXi.value.zkWard,
    name: huanZheXinXi.value.zkWardName
  }
  router.push({
    name: 'orderTemplateMaintenance',
    params: {
      data: JSON.stringify(temp),
      dept: JSON.stringify(dept)
    }
  })
}

/**
 * 批量停止时间
 */
const clickToStopTheOrder = () => {
  let tempData = yzMitt.emit('getSelectedData')
  tempData.forEach(item => {
    // 因为前端用的是浏览器自带的 所以要删除 T
    item.endTime = getFormatDatetime(item.endTimeTemp)
  })
  let param = {
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    list: tempData
  }
  stopOrder(param).then(res => {
    yzMitt.emit('queryYz')
  })

}

// 点击修改医嘱时间
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 openRationalDrugUse = () => {
  window.open('http://172.16.32.121:9097/index.html')
}

/**
 * 血糖
 */
const routerBloodSugarClick = () => {
  router.push({
    name: 'bloodSugarQuery',
    params: {
      patNo: huanZheXinXi.value.inpatientNo,
      times: huanZheXinXi.value.admissTimes,
    }
  })
}

// 点击确认关联
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(async (res) => {
      clearAssociate()
      await setOrderDataAndTwinkle(res[0].actOrderNo, res)
    })
  }).catch(() => {
  })
}

const crbOpen = () => {
  if (youWuXuanZheHuanZhe()) return
  setDialogToJs(ReportOfInfectiousDiseases, {
    patNo: huanZheXinXi.value.inpatientNo,
    times: huanZheXinXi.value.admissTimes,
  }).catch(() => {

  })
}

const outPatientDialog = ref(false)
const outPatientDialogOpen = () => {
  if (stringIsBlank(huanZheXinXi.value.zkWard)) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择患者。");
  }
  if (stringIsBlank(huanZheXinXi.value.mzNo)) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "没有查询到患者门诊号，请先建档。");
  }
  outPatientDialog.value = true
}

const oneClickStopDialog = ref(false)
const oneClickStopOpen = () => {
  if (youWuXuanZheHuanZhe()) return
  oneClickStopDialog.value = true
}

const rcvrcalcost = async () => {
  if (youWuXuanZheHuanZhe()) return
  let {inpatientNo, admissTimes, ledgerSn, admissDate} = huanZheXinXi.value
  await receiveAndRecalculateCost({inpatientNo, admissTimes, ledgerSn, admissDate})
  huanZheXinXi.value = await getPatientInfo(inpatientNo)
}

onMounted(async () => {

  yzMitt.on('queryYz', (val) => {
    return queryYz(val)
  })

  yzMitt.on('confirmMedicalAdvice', () => {
    if (isCydy()) {
      confirmTheDoctorSOrderWithMedicineClick()
    } else {
      currentConfirmOrdersClick()
    }
  })

})

</script>

<style scoped lang="scss">
.status_color {
  width: 10px;
  height: 10px;
}

</style>
