<template>
  <CyFlex>
    <template #header>
      <el-date-picker
        v-model="dateRange"
        :shortcuts="shortcuts"
        end-placeholder="申请结束"
        placeholder="选择日期"
        range-separator="至"
        size="small"
        start-placeholder="申请开始"
        style="width: 220px"
        type="daterange"
      />
      <el-button-group>
        <el-button
          icon="Search"
          type="primary"
          @click="dianJiChaXunHuanZheJianCha"
          >查询
        </el-button>
        <el-button type="primary" @click="imageClick">影像</el-button>
      </el-button-group>
      <el-divider direction="vertical"></el-divider>
      <el-button icon="Check" type="success" @click="saveData">保存</el-button>
      <el-button type="primary" @click="batchPrint">批量打印</el-button>
      <el-button
        icon="Check"
        type="primary"
        @click="saveTemplate"
        :disabled="jcProxy.isEmpty()"
      >
        存为模板
      </el-button>
      <el-button @click="medicalTechnologyAppointment">医技预约</el-button>
    </template>

    <div style="display: flex; height: 100%; width: 100%">
      <CyTabs v-model="asideTabs" type="idea" width="100%" height="100%">
        <CyTabPane :name="0" label="新增">
          <NewApplication />
        </CyTabPane>
        <CyTabPane :name="1" label="历史记录">
          <template #default="{ height }">
            <CheckApplicationHistory
              ref="historyTableRef"
              @print="
                value => {
                  printListRef.print([value]);
                }
              "
              :data="jianChaShuJu"
              :height="height"
            />
          </template>
        </CyTabPane>
        <CyTabPane :name="2" label="结果V2">
          <JianChaJieGuoV2
            :pat-no="huanZheXinXi.inpatientNo"
            ref="jieGuoRefV2"
          />
        </CyTabPane>
      </CyTabs>
    </div>
  </CyFlex>
  <save-template-inspection ref="saveTemplateRef" />
  <PrintCheckList ref="printListRef" />
</template>

<script setup>
import {
  cuoWuXinXi,
  huanZheXinXi,
  youWuXuanZheHuanZhe,
  jsQueryYzData,
  jcExtraInformation,
  onChangePatient,
  openPatientImage,
  jcProxy,
  jcList,
} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import { ref } from "vue";
import {
  baoCunJianYanJianCha,
  huoQuJianChaShenQing,
} from "@/api/zhu-yuan-yi-sheng/jian-yan-jian-cha-shen-qing";
import { getDateRangeFormatDate } from "@/utils/date";
import { shortcuts } from "@/data/shortcuts";
import CheckApplicationHistory from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/aside/CheckApplicationHistory";
import NewApplication from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/aside/NewApplication";
import SaveTemplateInspection from "@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/SaveTemplateInspection";
import { BizException, ExceptionEnum } from "@/utils/BizException";
import { yaoPinXiangMuPiPeiYiBao } from "@/api/public-api";
import { stringIsBlank, stringNotBlank } from "@/utils/blank-utils";
import JianChaJieGuoV2 from "@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/components/jiancha/JianChaJieGuoV2.vue";
import CyFlex from "@/components/cy/flex/src/CyFlex.vue";
import CyTabs from "@/components/cy/tabs/src/CyTabs";
import CyTabPane from "@/components/cy/tabs/src/CyTabPane.vue";
import { CyMessageBox } from "@/utils/cy-message-box";
import XEUtils from "xe-utils";
import PrintCheckList from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/da-ying/PrintCheckList.vue";
import { ElMessageBox } from "element-plus";
import { useCompShallowRef } from "@/utils/useCompRef";

const orderName = ref("");
const dateRange = ref(null);
const jianChaShuJu = ref([]);
const asideTabs = ref(0);
const printListRef = useCompShallowRef(PrintCheckList);

// 检查结果
const jieGuoRefV2 = ref();

/**
 * 点击查询患者检查
 * @param total
 */
const dianJiChaXunHuanZheJianCha = () => {
  let { startTime, endTime } = getDateRangeFormatDate(dateRange.value);
  let param = {
    patNo: huanZheXinXi.value.inpatientNo,
    times: huanZheXinXi.value.admissTimes,
    orderName: orderName.value,
    startTime: startTime,
    endTime: endTime,
  };
  huoQuJianChaShenQing(param).then(res => {
    jianChaShuJu.value = res;
  });
  jieGuoRefV2.value.queryData();
};

// 保存模板
const saveTemplateRef = ref();
const saveTemplate = () => {
  saveTemplateRef.value.openOrClose();
};

// 保存数据
const saveData = async () => {
  if (youWuXuanZheHuanZhe()) return;

  function error() {
    if (stringNotBlank(huanZheXinXi.value.inpatientNo)) {
      BizException(
        ExceptionEnum.LOGICAL_ERROR,
        "病史摘要、体征信息、相关辅检结果、临床诊断，不能为空。"
      );
    }
  }

  if (stringIsBlank(jcExtraInformation.value.reqComment)) {
    error();
  }
  if (stringIsBlank(jcExtraInformation.value.reqTzComment)) {
    error();
  }
  if (stringIsBlank(jcExtraInformation.value.reqOtherResult)) {
    error();
  }
  if (stringIsBlank(jcExtraInformation.value.diagCode)) {
    error();
  }

  jcProxy.emptyError();

  const listCode = [];

  jcProxy.forEach(item => {
    item.reqComment = jcExtraInformation.value.reqComment;
    item.reqTzComment = jcExtraInformation.value.reqTzComment;
    item.reqOtherResult = jcExtraInformation.value.reqOtherResult;
    item.diagCode = jcExtraInformation.value.diagCode;
    item.diagText = jcExtraInformation.value.diagText;
    listCode.push(item.orderCode + "-00");
  });

  const 未匹配医保码 = await yaoPinXiangMuPiPeiYiBao(listCode).catch(() => {
    return "";
  });

  cuoWuXinXi.value = 未匹配医保码;

  if (stringNotBlank(未匹配医保码)) {
    await CyMessageBox.confirm({
      message: 未匹配医保码,
      title: "提示",
      type: "warning",
      dangerouslyUseHTMLString: true,
      confirmButtonText: "继续录入",
    });
  }
  baoCunShuJu();
};

async function baoCunShuJu() {
  await CyMessageBox.confirm({
    message: "确定要保存这些数据吗？",
    title: "提示",
    type: "warning",
  });

  let data = XEUtils.clone(huanZheXinXi.value, true);
  data.list = jcList.value;
  data.list.forEach(item => {
    item.reqType = 3;
  });
  const reqs = await baoCunJianYanJianCha(data);
  ElMessageBox.confirm("是否打印申请单", "提示", {
    type: "success",
  })
    .then(() => {
      printListRef.value.print(reqs);
    })
    .catch(XEUtils.noop);

  jcProxy.clear();
  dianJiChaXunHuanZheJianCha();
  asideTabs.value = 1;
  // 查询医嘱
  jsQueryYzData().then(() => {});
}

function imageClick() {
  if (youWuXuanZheHuanZhe()) return;
  openPatientImage(huanZheXinXi.value.inpatientNo);
}

const historyTableRef = ref();

function batchPrint() {
  const data = historyTableRef.value.getSelectData();
  printListRef.value.print(
    data.map(i => {
      return i.reqNo;
    })
  );
}

onChangePatient(dianJiChaXunHuanZheJianCha);

function medicalTechnologyAppointment() {
  window.open(
    `http://172.16.32.208:8010/Third/Clinical/IClinicalRegister.html?ZYH=${huanZheXinXi.value.inpatientNo}`,
    "_blank"
  );
}
</script>

<style scoped lang="scss">
:deep(.el-table .success-row) {
  background: rgba(71, 123, 220, 0.69);
}
</style>
