<template>
  <div
    v-if="!props.hideCtrl"
    class="flex items-center justify-end p-4 space-x-4"
  >
    <el-button type="warning" plain @click="clearCompareReport"
      >清空并保存</el-button
    >
    <div class="flex-1 flex items-center justify-end">
      <el-button type="success" plain @click="getData">更新对比数据</el-button>
      <el-button type="primary" @click="saveCompareReport">保存</el-button>
    </div>
  </div>
  <div class="p-4 w-full overflow-x-auto">
    <slot name="title1">
      <p class="font-bold text-lg mb-2">疾病风险评估对比及趋势</p>
    </slot>
    <!-- {{state}} -->
    <!-- <table class=" border-collapse bg-white w-full mb-4">

      <tr
          class="">
        <td class="border border-gray-200 px-2 h-[64px] whitespace-nowrap">
          <div>
            <span>疾病</span>
            <span>时间</span>
          </div>
        </td>
        <td
          v-for="(col, colIdx) in state.tableHeaderColumns" :key="colIdx"
          class="border border-gray-200 px-2 h-[64px] whitespace-nowrap">{{ col }}</td>

        <td class="border border-gray-200 px-2 h-[64px] whitespace-nowrap">趋势</td>
      </tr>
      <tr v-for="(item, index) in state.diseaseList" :key="index">
        <td class="border border-gray-200 p-2">{{ item.name }}</td>
        <td
          v-for="(col, colIdx) in state.tableHeaderColumns" :key="colIdx"
          class="border border-gray-200 text-sm text-center  p-2"
        >
          <span
            :class="['text-gray-500', 'text-green-500', 'text-yellow-500', 'text-red-600', 'text-red-500'][item.list[colIdx]?.riskDegree]"
          >{{ item.list[colIdx]?.riskDesc || '缺乏数据' }}</span>
        </td>
        <td class="border border-gray-200">
          <div class="w-40">
            <div :ref="r => chartRefs[index] = r" class="h-24 w-auto"></div>
          </div>
        </td>
      </tr>
    </table> -->
    <div v-for="(item, index) in diseaseList" :key="index" class="mb-4">
      <SubTitle :type="degreeLabel[item.list.at(-1).riskDegree]?.label">
        <span>{{ item.name }}</span>
      </SubTitle>
      <table class="border-collapse bg-white w-full table-fixed">
        <tr class="page-break-inside-avoid bg-gray-200">
          <td
            :colspan="state.tableHeaderColumns?.length + 1"
            class="font-bold border-x border-gray-200 p-2 text-gray-700 bg-gray-50 whitespace-nowrap"
          >
            疾病风险趋势对比
          </td>
        </tr>
        <tr class="page-break-inside-avoid">
          <td
            class="border border-gray-200 p-2 text-gray-700 whitespace-nowrap"
          >
            <div>
              <span>风险趋势</span>
              <!-- <span>时间</span> -->
            </div>
          </td>
          <td
            v-for="(col, colIdx) in state.tableHeaderColumns"
            :key="colIdx"
            class="border border-gray-200 p-2 text-gray-700 whitespace-nowrap"
          >
            {{ col }}
          </td>
        </tr>
        <tr class="page-break-inside-avoid">
          <td class="border border-gray-200 p-2" :class="item.riskTip?.class">
            {{ item.riskTip?.label }}
          </td>
          <td
            v-for="(col, colIdx) in state.tableHeaderColumns"
            :key="colIdx"
            class="border border-gray-200 text-sm text-left p-2"
          >
            <span
              :class="
                [
                  'text-gray-500',
                  'text-green-500',
                  'text-yellow-500',
                  'text-red-600',
                  'text-violet-700'
                ][item.list[colIdx]?.riskDegree]
              "
              >{{ item.list[colIdx]?.riskDesc || "缺乏数据" }}</span
            >
          </td>
        </tr>
        <div
          v-if="!diseaseList.length"
          class="break-inside-avoid page-break-auto 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>
      </table>
      <table
        v-if="item.medList?.length"
        class="border-collapse bg-white w-full table-fixed"
      >
        <tr class="page-break-inside-avoid bg-gray-200">
          <td
            :colspan="state.tableHeaderColumns?.length + 1"
            class="font-bold border-x border-gray-200 p-2 text-gray-700 bg-gray-50 whitespace-nowrap"
          >
            主要异常结果对比
          </td>
        </tr>
        <tr class="page-break-inside-avoid">
          <td
            class="border border-gray-200 p-2 text-gray-700 whitespace-nowrap"
          >
            <div>
              <span>项目</span>
            </div>
          </td>
          <td
            v-for="(col, colIdx) in state.tableHeaderColumns"
            :key="colIdx"
            class="border border-gray-200 p-2 text-gray-700 whitespace-nowrap"
          >
            {{ col }}
          </td>
        </tr>
        <tr
          v-for="(child, childIdx) in item.medList"
          :key="childIdx"
          class="page-break-inside-avoid"
        >
          <td class="border border-gray-200 p-2">{{ child.name }}</td>
          <td
            v-for="(col, colIdx) in state.tableHeaderColumns"
            :key="colIdx"
            class="border border-gray-200 text-sm text-left p-2"
          >
            <div v-for="(med, medIdx) in child.list[colIdx]" :key="medIdx">
              <span class="text-sm">{{
                med?.value === 0 || med?.value ? med?.value : "-"
              }}</span>
              <span
                v-if="med?.value || med?.value === 0"
                class="text-xs text-gray-500"
                >{{ med?.unit }}</span
              >
            </div>
            <span v-if="!child.list[colIdx]?.length">-</span>
          </td>
        </tr>
      </table>
    </div>

    <!-- <el-table :data="state.diseaseList" table-layout="auto">
      <el-table-column label="疾病" prop="name" fixed="left"></el-table-column>
      <el-table-column :label="col" v-for="(col, colIdx) in state.tableHeaderColumns" :key="colIdx">
        <template #header>
          <span class="whitespace-nowrap">{{col}}</span>
        </template>
        <template #default="{ row, $index }">
          <span
            :class="['text-gray-500', 'text-green-500', 'text-yellow-500', 'text-red-600', 'text-red-700'][row.list[colIdx]?.riskDegree]"
          >{{ row.list[colIdx]?.riskDesc || '缺乏分析数据' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="趋势" width="200px">
        <template #default="{row, $index}">
          <div class="w-40">
            <div :ref="r => chartRefs[$index] = r" class="h-24 w-[160px]"></div>
          </div>
        </template>
      </el-table-column>
    </el-table> -->
    <!-- <slot name="title2">
      <p class="font-bold text-lg mb-2 mt-6">异常项目横向对比</p>
    </slot>
    <div v-for="(item, index) in state.medDataList" :key="index" class="rounded mb-4 last:mb-0">

        <div
          class=" py-2 px-4 flex items-center justify-between bg-[#f9fafb] border border-b-0 border-solid border-gray-200"
        >
          <span>{{ item.name }}</span>
        </div>
        <div class="w-full overflow-x-auto">
          <div class="flex flex-wrap">
            <div
              v-for="(col, colIdx) in item.list"
              :key="colIdx"
              class="flex-1 border-t border-b border-l last:border-r border-solid border-gray-200"
            >
              <div
                class="p-2 text-sm border-solid border-b border-gray-200"
              >
                {{ col.date }}
              </div>
              <div>
                <div class="p-2 text-sm">
                  <div>
                    <span class="align-middle"
                      >{{ col.value
                      }}{{ col.unit && col.unit != "-" ? col.unit : "" }}
                    </span>
                    <template v-if="col.reference">
                      <el-tooltip>
                        <QuestionFilled
                          class="w-4 h-4 inline align-middle ml-1 cursor-pointer opacity-50"
                        />
                        <template #content>
                          <div class="text-sm">
                            参考范围：{{ col.reference }}
                          </div>
                        </template>
                      </el-tooltip>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div> -->
  </div>
</template>

<script setup>
import {
  computed,
  shallowRef,
  watch,
  ref,
  nextTick,
  reactive,
  inject,
  onMounted,
  provide,
  defineAsyncComponent
} from "vue";
import { request } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
// import echarts from "@/plugins/echarts";
import PageTitle from "@/components/PageTitle.vue";
import SubTitle from "@/components/SubTitle.vue";
import SectionText from "@/components/SectionText.vue";
import { useRoute, useRouter } from "vue-router";
const [route, router] = [useRoute(), useRouter()];
const props = defineProps({
  data: {
    type: Array,
    default: undefined
  },
  archivesId: {
    type: String,
    default: undefined
  },
  hideCtrl: false
});
const degreeLabel = {
  4: { label: "diagnosis", thClass: "text-violet-800 bg-violet-200" },
  3: { label: "danger", thClass: "text-red-500 bg-red-50" },
  2: { label: "warning", thClass: "text-yellow-600 bg-yellow-100" },
  0: { label: "success", thClass: "text-green-800 bg-green-200" },
  1: { label: "primary", thClass: "text-blue-800 bg-blue-200" }
};
// const chartRefs = ref([])
// const renderChart = (el, data) => {
//   // 基于准备好的dom，初始化echarts实例
//   const myChart = echarts.init(el);
//   const riskDegree2Val = {
//     0: 0,
//     1: 0,
//     2: 1,
//     3: 2,
//     4: 3,
//   }
//   let values = data.list.map(v => v.riskDegree)

//   values = values.map((v, i) => {
//     if (!v) {
//       v = values[i - 1] || 0
//     }
//     return riskDegree2Val[v] ? (riskDegree2Val[v] || 3) : riskDegree2Val[v]
//   })
//   const option = {
//     grid: {
//       left: "5%",
//       right: "5%",
//       top: "8%",
//       bottom: "0%",
//       containLabel: true
//     },
//     xAxis: {
//       show: false,
//       type: "category",
//       boundaryGap: false,
//     },
//     yAxis: {
//       show: false,
//       type: "value",
//       max: 4
//     },
//     series: [
//       {
//         name: "trend",
//         type: "line",
//         areaStyle: {
//           color: {
//             type: "linear",
//             x: 0,
//             x2: 0,
//             y: 0,
//             y2: 1,
//             colorStops: [
//               { offset: 0, color: "rgba(0, 55, 255, 0.9)" }, // 深色靠近数据点
//               { offset: .6, color: "rgba(0, 55, 255, 0.3)" }, // 深色靠近数据点
//               { offset: 1, color: "rgba(0, 0, 255, 0.0)" } // 透明靠近X轴
//             ]
//           }
//         },
//         // symbolSize: 4,
//         data: values
//       }
//     ]
//   };
//   // 绘制图表
//   myChart.setOption(option);
// };
const state = ref({
  diseaseList: [],
  medDataList: [],
  tableHeaderColumns: []
});
const compareReportData = inject("compareReportData");
const getData = async () => {
  let temp;
  if (compareReportData?.value) {
    temp = compareReportData.value;
  } else {
    const { data } = await request.get(
      `/idcService/mechanism/medicalData/compareReport/data/v2`,
      {
        params: {
          sn: route.query.sn,
          archivesId: props.archivesId
        }
      }
    );
    temp = data.data;
  }
  state.value = {
    ...state.value,
    ...(temp.compareDataForYear || {}),
    medDataList: temp.compareData.medDatas
  };
  // nextTick(() => {
  //   temp && nextTick(() => {
  //     chartRefs.value.length && chartRefs.value.forEach((chartRef, index) => {
  //       renderChart(chartRef, state.value.diseaseList[index])
  //     })
  //   })
  // })
  // saveCompareReport()
};
const clearCompareReport = async () => {
  const { data } = await request.post(
    `/idcService/mechanism/medicalData/compareReport/delete`,
    {
      archivesId: props.archivesId
    }
  );
  // getData()
  ElMessage.success("操作成功");
};
const saveCompareReport = async () => {
  const { data } = await request.post(
    `/idcService/mechanism/medicalData/compareReport/save`,
    {
      archivesId: props.archivesId,
      data: state.value
    }
  );
  ElMessage.success("操作成功");
};

const diseaseList = computed(() =>
  (state.value?.diseaseList || [])
    .map(v => {
      let riskTip = "";

      if (v.list.length > 1) {
        const last = v.list.at(-1).riskDegree;
        const prev = v.list.at(-2).riskDegree;
        if (last == 4) {
          riskTip = { label: "已确诊", class: "text-violet-800" };
        } else if (last > prev && last > 1) {
          riskTip = { label: "风险在增加↑", class: "text-red-500" };
        } else if (last > prev && last == 1) {
          riskTip = { label: "暂无风险", class: "text-green-500" };
        } else if (last < prev && last > 0) {
          riskTip = { label: "风险在降低↓", class: "text-green-500" };
        } else if (last < prev && last == 0) {
          riskTip = { label: "风险变化情况未知 -", class: "text-yellow-500" };
        } else if (last == prev && last && prev) {
          riskTip = { label: "风险暂无变化 -", class: "text-yellow-500" };
        } else if (last == prev && !last && !prev) {
          riskTip = { label: "风险变化情况未知 -", class: "text-yellow-500" };
        } else {
          riskTip = { label: "风险暂无变化 -", class: "text-yellow-500" };
        }
      }
      return {
        ...v,
        riskTip,
        list: v.list
      };
    })
    .sort((a, b) => b.list.at(-1).riskDegree - a.list.at(-1).riskDegree)
);
onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped></style>
