<template>
  <div class="layout_container">
    <header class="round-header">
      <el-select
        v-model="reportCategory"
        @change="onCategoryChange"
        style="width: 100px"
      >
        <el-option-group
          v-for="group in reportTypes"
          :key="group.label"
          :label="group.label"
        >
          <el-option
            v-for="item in group.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-option-group>
      </el-select>
      <el-select v-model="patType" style="width: 80px">
        <el-option
          v-for="item in patientTypes"
          :key="item.code"
          :value="item.code"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-input
        v-model="patNo"
        clearable
        :placeholder="placeHolder"
        style="width: 120px"
      ></el-input>
      <el-date-picker
        v-model="datePeriod"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="shortcuts"
        style="width: 260px"
      ></el-date-picker>
      <el-button
        type="primary"
        icon="Search"
        @click="queryIndex"
        :disabled="inPrintProcess"
        style="margin-left: 20px"
      >
        查询
      </el-button>
      <el-button
        type="primary"
        icon="Printer"
        :disabled="inPrintProcess"
        @click="beforePrint"
      >
        打印
      </el-button>
    </header>
    <div class="layout_main layout_container layout-horizontal">
      <aside class="layout_el-table">
        <el-table
          ref="tableRef"
          :data="inspectionIndex"
          stripe
          highlight-current-row
          @row-click="beforeQueryDetail"
        >
          <el-table-column
            v-if="reportCategory === 'JY'"
            type="selection"
            width="30"
          ></el-table-column>
          <el-table-column
            prop="trscDate"
            label="报告时间"
            width="130"
          ></el-table-column>
          <el-table-column
            prop="examPurpose"
            label="检验名称"
            width="170"
          ></el-table-column>
          <el-table-column
            v-if="reportCategory === 'JY'"
            prop="reportType"
            label="报告类别"
            width="70"
          ></el-table-column>
        </el-table>
      </aside>
      <div
        id="reportDetail"
        class="layout_main"
        style="
          position: relative;
          width: 90%;
          min-height: 96%;
          padding: 0 30px;
          background-color: white;
          overflow-y: auto;
        "
      >
        <div v-if="reportCategory === 'JY'" style="height: 98%">
          <div
            v-for="(jyData, index) in jyDataList"
            :id="'jyData' + index"
            style="height: 100%"
          >
            <JyResult :data="jyData" />
          </div>
        </div>
        <div v-if="reportCategory === 'JC'">
          <div v-if="jcbg.reportUrl">
            <el-image :src="jcbg.reportUrl"></el-image>
          </div>
          <div v-else>
            <h3
              style="
                width: 100%;
                text-align: center;
                font-weight: bold;
                height: 30px;
                line-height: 30px;
              "
            >
              {{ env.VITE_HOSPITAL_NAME }}检查报告单
            </h3>
            <div style="display: flex">
              <div style="width: 32%">姓名：{{ jcbg.patientName }}</div>
              <div style="width: 32%">
                {{ ptntType }}：
                {{ jcbg.patNo }}
              </div>
              <div style="width: 32%">
                <div>申请项目：{{ jcbg.examPurpose.substring(0, 13) }}</div>
                <div>{{ jcbg.examPurpose.substring(13) }}</div>
              </div>
            </div>
            <div style="display: flex">
              <div style="width: 32%">医生姓名：{{ jcbg.doctorName }}</div>
              <div style="width: 32%">检查时间：{{ jcbg.reportTime }}</div>
              <div style="width: 32%">报告时间：{{ jcbg.trscDate }}</div>
            </div>
            <el-divider content-position="left">检查所见</el-divider>
            <div v-html="jcbg.examinationSee"></div>
            <el-divider content-position="left">检查结论</el-divider>
            <div v-html="jcbg.examinationreSult"></div>
            <div v-if="jcbg.reportUrl" style="margin-top: 30px">
              <el-button type="primary" size="large" link @click="showJcImage"
                >查看图像</el-button
              >
            </div>
          </div>
        </div>
        <div v-if="reportCategory === 'BL' || reportCategory === 'XD'">
          <el-image :src="blxdUrl" style="width: 100%" fit="contain" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onActivated, ref, onMounted } from "vue";
import { shortcuts } from "@/data/shortcuts";
import {
  checkExamDetail,
  checkIndexByCategory,
  checkTestDetail,
} from "@/api/inspections";
import router from "@/router";
import { ElMessage } from "element-plus";
import { initLodop, getLodop } from "@/utils/c-lodop";
import { getDateRangeFormatDate } from "@/utils/date";
import Sleep from "@/utils/sleep";
import JyResult from "@/views/examination/component/JyResult.vue";
import env from "../../utils/setting.js";

const props = defineProps({
  patNo: {
    type: String,
    default: null,
  },
  start: {
    type: String,
  },
  end: {
    type: String,
  },
});
const tableRef = ref(null);
const patType = ref("InPatient");
const reportCategory = ref("JY");
const patNo = ref(null);
const datePeriod = ref([]);
const placeHolder = computed(() => {
  return "请输入" + ptntType.value;
});
const ptntType = computed(() => {
  if (patType.value === "InPatient") {
    return "住院号";
  } else if (patType.value === "OutPatient") {
    return "门诊号";
  }
  return "";
});

const jyDataList = ref([]);

const inspectionIndex = ref([]);

function onCategoryChange(val) {
  inspectionIndex.value = [];
}

const queryIndex = () => {
  if (!patNo.value) {
    ElMessage({
      message: "请输入患者" + ptntType.value + "。",
      type: "warning",
      duration: 2000,
      showClose: true,
    });
    return;
  }
  if (!datePeriod.value || datePeriod.value.length < 2) {
    ElMessage({
      message: "请选择日期范围。",
      type: "warning",
      duration: 2000,
      showClose: true,
    });
    return;
  }
  let { startTime, endTime } = getDateRangeFormatDate(datePeriod.value);
  const params = {
    patType: patType.value,
    reportCategory: reportCategory.value,
    patNo: patNo.value,
    reqStartTime: startTime,
    reqEndTime: endTime,
  };
  checkIndexByCategory(params).then(res => {
    inspectionIndex.value = res;
  });
};

const blxdUrl = ref("");

function beforeQueryDetail(row) {
  if (reportCategory.value === "JY") {
    queryJyDetail(row, true);
  } else if (reportCategory.value === "JC") {
    queryJcDetail(row);
  } else {
    blxdUrl.value = row.reportUrl;
  }
}

const jcbg = ref({
  examPurpose: "",
});

function queryJcDetail(row) {
  checkTestDetail({
    reportId: row.patientUid,
  }).then(res => {
    jcbg.value = res;
  });
}

const queryJyDetail = (row, clear) => {
  if (clear) {
    jyDataList.value = [];
  }
  return new Promise((resolve, reject) => {
    checkExamDetail({
      reportId: row.reportId,
    }).then(res => {
      const bacterias = [];
      if (res.bacterias && res.bacterias.length > 0) {
        res.bacterias.forEach(bac => {
          const bacSize = bac.antiList ? Math.ceil(bac.antiList.length / 2) : 1;
          const tempBacResult = {
            halfBacSize: bacSize,
            germName: bac.bacNameCn,
            antiList: bac.antiList,
            type: bac.itmName,
          };
          bacterias.push(tempBacResult);
        });
      }
      const tempJyData = {
        inspectionDetail: {
          order: res.order,
          items: res.items,
        },
        bacterias: bacterias,
        halfSize: Math.ceil(res.items.length / 2),
        ptntType: ptntType.value,
        reportType: row.reportType,
      };
      jyDataList.value.push(tempJyData);
      resolve();
    });
  });
};

const inPrintProcess = ref(false);
const beforePrint = async () => {
  inPrintProcess.value = true;
  const selection = tableRef.value.getSelectionRows();
  if (selection && selection.length > 0) {
    jyDataList.value = [];
    for (let i = 0; i < selection.length; i++) {
      await queryJyDetail(selection[i], false);
      await Sleep(1000);
    }
    await doPrint();
    inPrintProcess.value = false;
  } else {
    await doPrint();
    inPrintProcess.value = false;
  }
};

onMounted(() => {
  initLodop();
  const vueName = router.currentRoute.value.name;
  if (vueName === "inspectionReportV2") {
    checkPathParams();
  } else {
    checkPropsParams();
  }
});

onActivated(() => {
  checkPathParams();
});

function checkPropsParams() {
  if (props.patNo && props.start && props.end) {
    patType.value = "InPatient";
    patNo.value = props.patNo;
    datePeriod.value[0] = props.start;
    datePeriod.value[1] = props.end;
    queryIndex();
  }
}

function checkPathParams() {
  const params = router.currentRoute.value.params;
  if (params.patNo && params.start && params.end) {
    patType.value =
      params.patNo.indexOf("-") === -1 ? "InPatient" : "OutPatient";
    patNo.value = params.patNo;
    datePeriod.value[0] = params.start;
    datePeriod.value[1] = params.end;
    queryIndex();
  }
}

function doPrint() {
  return new Promise(resolve => {
    const LODOP = getLodop();
    LODOP.PRINT_INIT("jyjc");
    LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true); //宽度溢出缩放
    if (reportCategory.value === "JY") {
      LODOP.SET_PRINT_PAGESIZE(2, 0, 0, "A5");
      for (let i = 0; i < jyDataList.value.length; i++) {
        const printarea = document.getElementById("jyData" + i).innerHTML;
        LODOP.ADD_PRINT_HTM(0, 0, "208mm", "146mm", printarea);
        LODOP.NEWPAGE();
      }
    } else {
      const ori = reportCategory.value === "XD" ? 2 : 1;
      LODOP.SET_PRINT_PAGESIZE(ori, "210mm", "267mm", "CreateCustomPage");
      const imgUrl =
        reportCategory.value === "JC" ? jcbg.value.reportUrl : blxdUrl.value;
      LODOP.ADD_PRINT_IMAGE(0, 0, "210mm", "267mm", imgUrl);
      LODOP.SET_PRINT_STYLEA(0, "Horient", 3);
      LODOP.SET_PRINT_STYLEA(0, "Vorient", 3);
      LODOP.SET_PRINT_STYLEA(0, "Stretch", 1);
    }
    LODOP.PREVIEW();
    resolve();
  });
}

const patientTypes = [
  { code: "InPatient", name: "住院号" },
  { code: "OutPatient", name: "门诊号" },
];

const reportTypes = [
  {
    label: "检验",
    options: [
      {
        label: "检验报告",
        value: "JY",
      },
    ],
  },
  {
    label: "检查",
    options: [
      {
        label: "检查报告",
        value: "JC",
      },
      {
        label: "病理报告",
        value: "BL",
      },

      {
        label: "心电报告",
        value: "XD",
      },
    ],
  },
];
</script>
