<template>
  <div v-if="resultRawJson" class="bg-white p-4">
    <el-descriptions
      v-if="resultRawJson?.result"
      title="用户信息"
      :column="2"
      border
      class="mb-8"
    >
      <el-descriptions-item label="姓名">{{
        resultRawJson.result.userInfo.name
      }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{
        resultRawJson.result.userInfo.gender
      }}</el-descriptions-item>
      <el-descriptions-item label="体检年龄">{{
        resultRawJson.result.userInfo.examAge
      }}</el-descriptions-item>
      <el-descriptions-item label="体检日期">
        <!-- {{resultRawJson.result.assessmentDate}} -->
        {{ dayjs(resultRawJson.result.examDate * 1000).format("YYYY-MM-DD") }}
      </el-descriptions-item>
    </el-descriptions>
    <page-title>
      <template #icon>
        <img
          src="@/assets/riskAnalysis/icon-overflow.png"
          alt=""
          class="h-full"
        />
      </template>
      <span>{{ "重大疾病风险概览" }}</span>
    </page-title>
    <div v-for="(item, index) in overViewList" :key="index">
      <div class="break-inside-avoid mb-12">
        <sub-title :type="rankLabel[item.rank].label">
          <span>{{ item.title }}</span>
        </sub-title>
        <SectionText :type="rankLabel[item.rank].label">{{
          item.note
        }}</SectionText>
      </div>

      <table
        border="0"
        v-if="item.children.length"
        class="border-collapse w-full mb-4 text-sm"
      >
        <tr class="page-break-avoid-auto page-break-inside-avoid">
          <td
            v-for="(column, columnIndex) in riskTableHeader[item.rank] || [
              '疾病名称',
              '患病风险',
              '重要已知风险因素',
              '对应科室'
            ]"
            :key="columnIndex"
            class="border border-gray-200 px-2 h-[48px] whitespace-nowrap"
            :class="rankLabel[item.rank]?.thClass"
          >
            {{ column }}
          </td>
        </tr>
        <tr
          v-for="(child, childIdx) in item.children"
          :key="childIdx"
          class="page-break-inside-avoid"
        >
          <td class="border border-gray-200">
            <div class="px-2 py-3">
              {{ child.name }}
            </div>
          </td>
          <td class="border border-gray-200">
            <div class="px-2 py-3 whitespace-nowrap">
              <span :class="riskDegreeLabel[child.riskDegree]?.class">{{
                // riskDegreeLabel[child.riskDegree].label
                child.riskDesc
              }}</span>
            </div>
          </td>
          <template v-if="riskTableHeader[item.rank]">
            <td class="border border-gray-200">
              <div class="px-2 py-3">
                {{
                  Array.isArray(child.recommendItems)
                    ? child.recommendItems.join()
                    : child.recommendItems
                }}
              </div>
            </td>
          </template>
          <td v-else class="border border-gray-200">
            <div class="px-2 py-3">
              <div
                v-for="(know, knowIdx) in child.knownFactors"
                :key="knowIdx"
                class=""
              >
                <span class="align-middle">{{ know.itemName }}：</span>
                <span class="align-middle">{{
                  Array.isArray(know.value) ? know.value.join() : know.value
                }}</span>
                <el-icon
                  v-if="know.mark > 0"
                  class="inline-block align-middle w-4 h-4 text-red-600"
                  ><Top />
                </el-icon>
                <el-icon
                  v-if="know.mark < 0"
                  class="inline-block align-middle w-4 h-4 text-green-600"
                  ><Bottom />
                </el-icon>
              </div>
            </div>
          </td>
          <td class="border border-gray-200">
            <div class="px-2 py-3">
              {{
                Array.isArray(child.department)
                  ? child.department.join("/")
                  : child.department || "/"
              }}
            </div>
          </td>
        </tr>
      </table>
      <div
        v-else
        class="break-inside-avoid flex flex-col items-center justify-center py-6 mb-4 border border-solid border-gray-200 rounded-b"
      >
        <img src="@/assets/riskAnalysis/empty-img.png" class="w-40" />
        <div class="text-gray-500 text-xs text-center mt-4">暂无分析数据</div>
      </div>
    </div>
    <el-empty v-if="!overViewList?.length" description="暂无数据"></el-empty>
    <UserDataAnalysisEvaluate
      v-for="(item, index) in 3"
      :key="index"
      :classification="index + 1"
      :latest="true"
    />
    <template v-if="suggestion">
      <page-title :bg="['#1DB198', '#7DFCBC']">
        <template #icon>
          <img
            src="@/assets/riskAnalysis/icon-interpretation.png"
            alt=""
            class="h-full"
          />
        </template>
        <span>个性化健康建议</span>
      </page-title>
      <div
        v-if="suggestion"
        class="relative mb-4 rounded p-4 text-gray-800 leading-6"
      >
        <div v-html="suggestion"></div>
      </div>
      <div
        v-else
        class="break-inside-avoid flex flex-col items-center justify-center py-6 mb-4"
      >
        <img src="@/assets/riskAnalysis/empty-img.png" class="w-40" />
        <div class="text-gray-500 text-xs text-center mt-4">暂无分析数据</div>
      </div>
    </template>
    <component
      v-if="
        props.needHorizontal && route.query.archivesId && HorizontalContrast
      "
      :is="HorizontalContrast"
      :archivesId="route.query.archivesId"
      :hideCtrl="true"
    >
      <template #title1>
        <page-title>
          <template #icon>
            <img
              src="@/assets/riskAnalysis/icon-tumor.png"
              alt=""
              class="h-full"
            />
          </template>
          <span>疾病风险评估对比及趋势</span>
        </page-title>
      </template>
      <template #title2>
        <page-title class="page-break-avoid-auto">
          <template #icon>
            <img
              src="@/assets/riskAnalysis/icon-tumor.png"
              alt=""
              class="h-full"
            />
          </template>
          <span>异常项目横向对比</span>
        </page-title>
      </template>
    </component>
    <template v-if="props.needHorizontal && compareSuggestionStatus == 4">
      <page-title :bg="['#1DB198', '#7DFCBC']">
        <template #icon>
          <img
            src="@/assets/riskAnalysis/icon-interpretation.png"
            alt=""
            class="h-full"
          />
        </template>
        <span>综合个性化健康建议</span>
      </page-title>
      <div class="relative mb-4 rounded p-4 text-gray-800 leading-6">
        <div v-html="compareSuggestion"></div>
      </div>
      <!-- <div
        v-else
        class="break-inside-avoid flex flex-col items-center justify-center py-6 mb-4"
      >
        <img src="@/assets/riskAnalysis/empty-img.png" class="w-40" />
        <div class="text-gray-500 text-xs text-center mt-4">暂无分析数据</div>
      </div> -->
    </template>
  </div>
  <el-empty v-else></el-empty>
</template>
<script setup>
import {
  computed,
  shallowRef,
  watch,
  ref,
  nextTick,
  inject,
  reactive,
  onMounted,
  provide,
  defineAsyncComponent
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { deduplicateArrayByKeys } from "@/utils";
import dayjs from "dayjs";
import PageTitle from "@/components/PageTitle.vue";
import SubTitle from "@/components/SubTitle.vue";
import SectionText from "@/components/SectionText.vue";
import { Top, Bottom } from "@element-plus/icons-vue";
import UserDataAnalysisEvaluate from "./UserDataAnalysisEvaluate.vue";

const HorizontalContrast = defineAsyncComponent(() =>
  import("./HorizontalContrast.vue")
);

const [route, router] = [useRoute(), useRouter()];
const props = defineProps({
  needHorizontal: false
});
const riskDegreeToRank = {
  1: [4, 3],
  2: [2],
  3: [1],
  4: [0]
};
const riskTableHeader = {
  3: [
    "疾病名称",
    "患病风险",
    // '建议检查项目',
    // '建议就医时间',
    "建议随访项目",
    // '建议随访时间',
    "对应科室"
  ],
  4: [
    "疾病名称",
    "患病风险",
    "建议完善项目",
    // '建议完善时间',
    "对应科室"
  ]
};
const riskDegreeLabel = {
  4: {
    label: "已确诊",
    class: "font-bold text-red-500"
  },
  3: {
    label: "有明显风险",
    class: "font-bold text-red-600"
  },
  2: {
    label: "有一定风险",
    class: "font-bold text-yellow-500"
  },
  1: {
    label: "暂未发现风险",
    class: "text-green-500"
  },
  0: {
    label: "暂未发现风险",
    class: "text-gray-500"
  }
};
const rankLabel = {
  1: { label: "danger", thClass: "text-red-500 bg-red-50" },
  2: { label: "warning", thClass: "text-yellow-500 bg-yellow-50" },
  3: { label: "primary", thClass: "text-blue-500 bg-blue-50" },
  4: { label: "warning", thClass: "text-yellow-500 bg-yellow-50" }
};

const resultRawJson = inject("resultRawJson")
// const latestReport = inject("latestReport");
const suggestion = inject("suggestion");
const compareSuggestion = inject("compareSuggestion");
const compareSuggestionStatus = inject("compareSuggestionStatus");
const overViewList = ref();

const formatOverView = () => {
  overViewList.value = (
    resultRawJson.value?.result?.reportConfig.reportPreviewCfg.sectionContent ||
    []
  )
    .map(v => {
      const tempItem = { ...v, children: [] };
      const children = riskDegreeToRank[v.rank]
        .map(riskDegree => {
          return resultRawJson.value.result.majorDisease
            .filter(v2 => v2.riskDegree == riskDegree)
            .sort((a, b) => b.riskDegree - a.riskDegree);
        })
        .flat();
      tempItem.children = deduplicateArrayByKeys(children, ["nodeId"]);
      return tempItem;
    })
    .filter(v => v.children.length);
  console.log("overViewList.value", overViewList.value, resultRawJson.value);
};
watch(
  () => resultRawJson.value,
  () => {
    console.log("resultRawJson.value", resultRawJson.value);
    formatOverView();
  },
  { immediate: true }
);
</script>
<style lang="scss"></style>
