<template>
  <div 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 class="px-4 py-8 mb-8">
      <!-- 标题 -->
      <!-- <h2 class="text-xl font-bold mb-4 text-center">健康风险评估</h2> -->

      <!-- 图表容器，使用背景渐变和 Grid 布局 -->
      <div class="relative w-full p-4 chart-background">
        <!-- Y轴线条 -->
        <div class="absolute -left-4 top-4 h-full flex items-center">
          <!-- Y轴线条 -->
          <div class="w-[1px] bg-gray-400 h-full"></div>
          <!-- Y轴箭头头部 -->
          <div class="arrow-y-head"></div>
        </div>

        <!-- X轴线条 -->
        <div
          class="absolute -bottom-4 -left-4 w-full flex items-center justify-end"
        >
          <!-- X轴线条 -->
          <div class="h-[1px] bg-gray-400 w-full"></div>
          <!-- X轴箭头头部 -->
          <div class="arrow-x-head"></div>
        </div>
        <!-- Y轴注释 -->
        <div
          class="flex flex-col absolute top-1/2 -left-4 transform -translate-x-1/2 -translate-y-1/2 text-sm text-gray-600"
        >
          <div class="bg-white py-2">
            <div
              class="flex flex-col items-center justify-center gap-1"
              v-html="
                '健康威胁程度'
                  .split('')
                  .map(s => `<span>${s}</span>`)
                  .join('')
              "
            ></div>
          </div>
        </div>

        <!-- X轴注释 -->
        <div
          class="absolute z-10 bottom-0 left-1/2 transform -translate-x-1/2 translate-y-6 text-center text-gray-600 text-sm"
        >
          <div class="flex-1 bg-white px-2">健康干预优先级</div>
        </div>
        <!-- 分区布局，根据风险等级和干预优先度沿对角线排列 -->
        <table class="w-full min-h-[400px] table-fixed">
          <tr v-for="(row, rowIdx) in zones" :key="rowIdx">
            <td v-for="(col, colIdx) in row" :key="colIdx">
              <div
                v-for="(condition, cIndex) in col.conditions"
                :key="cIndex"
                class="inline-flex items-center text-xs px-2 py-1 m-1"
              >
                <span
                  class="inline-block align-middle rounded-full bg-blue-700 p-1 border-2 border-solid border-blue-200 mr-1"
                ></span>
                <span class="align-middle whitespace-pre-wrap break-all">{{
                  condition.name
                }}</span>
              </div>
              <div v-if="!col.conditions?.length" class="h-10"></div>
            </td>
          </tr>
        </table>
      </div>
    </div>
    <div v-if="compareSuggestion && compareSuggestion != '<p><br></p>'" class="mb-8">
      <sub-title :custom-bg="['#3824ed', 'rgba(56, 36, 237, .1)']">
        <span>健康建议要点</span>
      </sub-title>
      <div
        class="bg-gray-50 rounded-b p-4"
        v-html="compareSuggestion"
      ></div>
    </div>
    <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="!item.rank">
            <td class="border border-gray-200">
              <div class="px-2 py-3">遵医嘱治疗</div>
            </td>
          </template>
          <template v-else-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>

    <component
      v-if="
         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>
    <UserDataAnalysisEvaluate
      v-for="(item, index) in 3"
      :key="index"
      :classification="index + 1"
    />
    <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>
    <!-- <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>
    </template> -->
  </div>
</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 = {
  0: [4],
  1: [3],
  2: [2],
  3: [1],
  4: [0]
};
const riskTableHeader = {
  0: ["疾病名称", "患病风险", "建议", "对应科室"],
  3: [
    "疾病名称",
    "患病风险",
    // '建议检查项目',
    // '建议就医时间',
    "建议随访项目",
    // '建议随访时间',
    "对应科室"
  ],
  4: [
    "疾病名称",
    "患病风险",
    "建议完善项目",
    // '建议完善时间',
    "对应科室"
  ]
};
const riskDegreeLabel = {
  4: {
    label: "已确诊",
    class: "font-bold text-violet-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 = {
  0: { label: "diagnosis", thClass: "text-violet-800 bg-violet-200" },
  1: { label: "danger", thClass: "text-red-500 bg-red-50" },
  2: { label: "warning", thClass: "text-yellow-600 bg-yellow-100" },
  3: { label: "success", thClass: "text-green-800 bg-green-200" },
  4: { label: "primary", thClass: "text-blue-800 bg-blue-200" }
};

const resultRawJson = inject("resultRawJson");
// const latestReport = inject("latestReport");
const compareReportDetail = inject("compareReportDetail");
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);
  setupZones(resultRawJson.value?.result?.majorDisease || []);
};

const zones = ref([]);
const riskDegreeMap = [4, 3, 2, 0, 1];
const notificationTimeMap = [365, 30, 1, 0];

const setupZones = healthConditions => {
  // 创建5x5的分区，表示不同的优先度和风险等级
  zones.value = [];

  // 初始化分区数据
  for (const risk of riskDegreeMap) {
    zones.value.push([]);
    for (const notificationTime of notificationTimeMap) {
      zones.value.at(-1).push({
        riskDegree: risk,
        notificationTime: notificationTime,
        conditions: [], // 初始为空，将在后续填充
        style: {
          // backgroundColor,
          // textColor,
        }
      });
    }
  }

  // 将健康条件分配到对应的分区
  healthConditions.forEach(condition => {
    zones.value.forEach((row, rowIdx) => {
      const zone = row.find(
        z =>
          z.riskDegree == condition.riskDegree &&
          z.notificationTime == condition.notificationTime
      );
      if (zone) {
        zone.conditions.push(condition);
      }
    });
  });
  console.log(zones);
};
watch(
  () => resultRawJson.value,
  v => {
    console.log("resultRawJson.value", resultRawJson.value, v);
    formatOverView();
  },
  { immediate: true }
);
</script>
<style lang="scss">
.chart-background {
  background: linear-gradient(to top right, #4fc46b, #c2d85f, #f3b475, #f06a5f);

  border-top-right-radius: 10px;
  position: relative;
}

/* X轴和Y轴箭头头部的样式 */
.arrow-y-head {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 10px solid #333;
  position: absolute;
  top: -10px;
  left: -5px;
}

.arrow-x-head {
  width: 0;
  height: 0;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  border-left: 10px solid #333;
  position: absolute;
  top: -5px;
  right: -10px;
}
</style>
