<template>
  <div class="page-plan-detail h-full flex">
    <div
      class="w-1/5 min-w-[320px] p-4 space-y-2 text-sm h-full overflow-y-auto flex flex-nowrap flex-col"
    >
      <div class="shadow-sm bg-white p-4">
        <div class="flex items-start">
          <div class="w-12 h-12">
            <img
              :src="archivesInfo?.gender == 1 ? man : woman"
              round
              class="w-12 h-12 rounded-full mr-4"
            />
          </div>
          <div class="flex-1 pl-4 space-y-2">
            <p>{{ archivesInfo.name }}</p>
            <div class="flex items-center my-1">
              <div class="flex items-center mr-4">
                <img src="@/assets/icon-gender.png" alt="" class="w-5 h-5" />
                <span class="text-sm text-gray-700">{{
                  archivesInfo.gender == 1 ? "男" : "女"
                }}</span>
              </div>
              <div class="flex items-center my-1">
                <img src="@/assets/icon-birthday.png" alt="" class="w-5 h-5" />
                <span class="text-sm text-gray-700"
                  >{{ formatAge(archivesInfo.birthday) }}岁</span
                >
              </div>
            </div>
            <div class="flex items-center">
              <span>档案号：</span>
              <span>{{ archivesInfo.id }}</span>
              <CopyDocument
                v-if="archivesInfo.id"
                class="w-4 text-blue-500 cursor-copy ml-1"
                v-copy="archivesInfo.id"
              />
            </div>
            <div class="flex items-center">
              <span
                >联系方式：{{
                  archivesInfo.accounts.find(v => v.type === 1)?.account
                }}</span
              >

              <CopyDocument
                v-if="archivesInfo?.accounts?.find(v => v.type === 1)?.account"
                class="w-4 text-blue-500 cursor-copy ml-1"
                v-copy="archivesInfo.accounts.find(v => v.type === 1)?.account"
              />
            </div>
          </div>
        </div>

        <div class="flex items-center mt-4">
          <Auth value="healthManage">
            <el-button type="primary" @click="uploadDialogVisible = true"
              >上传数据</el-button
            >
          </Auth>
          <el-button type="primary" @click="visibleBacklog = true"
            >待办事件管理</el-button
          >
        </div>
      </div>
      <div class="shadow-sm bg-white">
        <div
          class="border-0 border-b border-solid border-gray-100 p-2 flex items-center justify-between"
        >
          用户标签
          <Auth value="healthManage:userTag">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="visibleTags = true"
              >编辑</el-button
            >
          </Auth>
        </div>
        <div class="p-2">
          <el-tag
            v-for="(item, index) in archivesTags"
            :key="index"
            class="m-1"
            >{{ item.name }}</el-tag
          >
          <span
            v-if="!archivesInfo?.tags?.length"
            class="text-xs m-1 text-gray-400"
            >暂无数据</span
          >
        </div>
      </div>
      <div class="shadow-sm bg-white">
        <div class="border-0 border-b border-solid border-gray-100 p-2">
          已确诊疾病
        </div>
        <div class="p-2">
          <el-tag
            v-for="(item, index) in recommendValues.medicalHistory"
            :key="index"
            class="m-1"
            type="danger"
            >{{ item.name }}</el-tag
          >
          <span
            v-if="!recommendValues.medicalHistory.length"
            class="text-xs m-1 text-gray-400"
            >暂无数据</span
          >
        </div>
      </div>
      <div class="shadow-sm bg-white">
        <div class="border-0 border-b border-solid border-gray-100 p-2">
          高风险疾病
        </div>
        <div class="p-2">
          <el-tag
            v-for="(item, index) in highRiskDiseaseList"
            :key="index"
            type="danger"
            class="m-1"
            >{{ item.name }}</el-tag
          >
          <span
            v-if="!highRiskDiseaseList.length"
            class="text-xs m-1 text-gray-400"
            >暂无数据</span
          >
        </div>
      </div>
      <div class="shadow-sm bg-white">
        <div class="border-0 border-b border-solid border-gray-100 p-2">
          易感疾病基因携带
        </div>
        <div class="p-2">
          <el-tag
            v-for="(item, index) in recommendValues.susceptibilityGene"
            :key="index"
            class="m-1"
            type="warning"
            >{{ item.name }}</el-tag
          >
          <span
            v-if="!recommendValues.susceptibilityGene.length"
            class="text-xs m-1 text-gray-400"
            >暂无数据</span
          >
        </div>
      </div>
      <div class="shadow-sm bg-white">
        <div class="border-0 border-b border-solid border-gray-100 p-2">
          正在用药
        </div>
        <div class="p-2">
          <el-tag
            v-for="(item, index) in recommendValues.medicationStatus"
            :key="index"
            class="m-1"
            >{{ item.name }}</el-tag
          >
          <span
            v-if="!recommendValues.medicationStatus.length"
            class="text-xs m-1 text-gray-400"
            >暂无数据</span
          >
        </div>
      </div>
      <div class="shadow-sm bg-white flex-1">
        <div
          v-for="(menu, menuIdx) in menus"
          :key="menuIdx"
          class="flex items-center justify-between py-3 px-4 border-0 border-b border-solid border-gray-100 cursor-pointer text-sm hover:bg-gray-50"
          :class="{ 'bg-gray-50 text-blue-500': curMenu === menu.key }"
          @click="curMenu = menu.key"
        >
          <span>{{ menu.label }}</span>
          <ArrowRight class="w-4" />
        </div>
      </div>
    </div>
    <div class="flex-1 overflow-y-auto relative m-4 ml-0 bg-white shadow-sm">
      <component
        v-if="menus.find(v => v.key === curMenu)"
        :is="menus.find(v => v.key === curMenu)?.component"
        :needHorizontal="true"
        :nodeId="'4:b8fbfa26-3437-4bbb-8349-96abd14851ea:635'"
        :list="evaluateDetail"
      />
      <!-- <component :is="ManagementPlan"></component> -->
      <!-- <ManagementPlan v-else></ManagementPlan> -->
    </div>
    <UploadDataDialog v-model:visible="uploadDialogVisible" />
    <ComponentDialogBacklog v-model:show="visibleBacklog" />
    <ComponentDialogEditTags
      v-model:show="visibleTags"
      :id="archivesInfo.id"
      @success="getArchiveTags"
    />
  </div>
</template>
<script setup>
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  computed,
  watch,
  markRaw,
  ref,
  reactive,
  onMounted,
  provide,
  defineAsyncComponent
} from "vue";
import { useRoute, useRouter } from "vue-router";
// import ManagementPlan from "./components/ManagementPlan.vue";
import {
  CopyDocument,
  Fold,
  ArrowLeft,
  ArrowRight
} from "@element-plus/icons-vue";
import man from "@/assets/icon-man.png";
import woman from "@/assets/icon-woman.png";
import {
  formatAge,
  parseJsonData,
  request,
  transformDataExpand
} from "@/utils";

import UploadDataDialog from "@/views/dataCenter/components/UploadDataDialog.vue";
import ComponentDialogBacklog from "./components/DialogBacklog.vue";
import ComponentDialogEditTags from "./components/DialogEditTags.vue";
import FollowUpData from "./components/FollowUpData.vue";
const uploadDialogVisible = ref(false);
const visibleBacklog = ref(false);

const RiskWarningReport = defineAsyncComponent(() =>
  import("./components/RiskWarningReport.vue")
);
const archives = defineAsyncComponent(() =>
  import("./components/PlanArchives.vue")
);
const checkData = defineAsyncComponent(() =>
  import("./components/PlanCheckData.vue")
);
const HealthManagementPlan = defineAsyncComponent(() =>
  import("./components/HealthManagementPlan.vue")
);
const planManage = defineAsyncComponent(() =>
  import("./components/ManagementPlan.vue")
);
const AssessmentHistory = defineAsyncComponent(() =>
  import("./components/AssessmentHistory.vue")
);
const LastTimeContent = defineAsyncComponent(() =>
  import("./components/LastTimeContent.vue")
);
const IndicatorTrends = defineAsyncComponent(() =>
  import("./components/IndicatorTrends.vue")
);
const DiseaseVisit = defineAsyncComponent(() =>
  import("./components/DiseaseVisit.vue")
);
// const FollowUpData = defineAsyncComponent(() => {
//   import("./components/FollowUpData.vue");
// });
const route = useRoute();
const router = useRouter();
const evaluateDetail = ref([]);
const commonMenu = [
  {
    label: "重大疾病风险预警报告",
    key: "RiskWarningReport",
    component: RiskWarningReport
  },
  {
    label: "档案信息",
    key: "archives",
    component: archives
  },
  {
    label: "检查数据",
    key: "checkData",
    component: checkData
  },
  {
    label: "回访数据",
    key: "DiseaseVisit",
    component: DiseaseVisit
  },

  {
    label: "随访数据",
    key: "FollowUpData",
    component: FollowUpData
  }
];
const menus = markRaw([
  ...[
    route.query.type == "health"
      ? {
          label: "健康管理",
          key: "HealthManagementPlan",
          component: HealthManagementPlan
        }
      : {
          label: "管理计划",
          key: "planManage",
          component: planManage
        }
  ],
  ...commonMenu
  // {
  //   label: "评估历史记录",
  //   key: "AssessmentHistory",
  //   component: AssessmentHistory
  // },
  // {
  //   label: "上次设定的管理内容",
  //   key: "LastTimeContent",
  //   component: LastTimeContent
  // },
  // {
  //   label: "关键指标趋势",
  //   key: "IndicatorTrends",
  //   component: IndicatorTrends
  // },
]);
const visibleTags = ref(false);
const archivesInfo = ref({
  id: "",
  name: "",
  avatar: "",
  gender: 0,
  birthday: "",
  mainArchivesId: "",
  accounts: [],
  tags: []
});
const archivesTags = ref([]);
const defaultArchivesId = ref(route.query?.archivesId);
provide("defaultArchivesId", defaultArchivesId);
const highRiskDiseaseList = ref([]);
const recommendValues = ref({
  medicalHistory: [],
  medicationStatus: [],
  susceptibilityGene: []
});

const getArchiveTags = () => {
  request
    .get(
      `dataService/schemeManage/tag/archive?archiveId=${defaultArchivesId.value}`
    )
    .then(resp => {
      archivesTags.value = resp.data || [];
    });
};
const getArchivesDetail = async () => {
  const { data } = await request.get(
    "/archivesService/mechanism/archives/detail",
    {
      params: {
        archivesId: route.query?.archivesId
      }
    }
  );
  archivesInfo.value = data.detail;
  highRiskDiseaseList.value = data.highRiskDiseaseList;
  recommendValues.value = data.recommendValues;
  // if (data.recommendValues) {
  //   ["medicalHistory", "medicationStatus", "susceptibilityGene"].forEach(
  //     key => {
  //       if (data.recommendValues[key]) {
  //         const { returnAnswer } = data.recommendValues[key];
  //         if (returnAnswer) {
  //           if (returnAnswer.groupAnswers) {

  //           } else {

  //           }
  //         }
  //       }
  //     }
  //   );
  // }
};
getArchivesDetail();
getArchiveTags();
provide("refreshArchives", getArchivesDetail);

const getArchivesReport = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/compareReport/detail`,
    {
      params: {
        archivesId: route.query?.archivesId
      }
    }
  );
  compareReportDetail.value = data.detail;
  compareSuggestion.value = data.detail.suggestion;
  if (data.detail?.data) {
    horizontalData.value = data.detail.data;
  }
  if (data.latestMedicalDataReport) {
    resultRawJson.value = parseJsonData(
      data.latestMedicalDataReport.resultRawJson
    );
  }
};
const getEvaluateDetail = () => {
  request
    .get("/platformApi/dataService/diseaseManage/detail", {
      params: {
        archiveId: route.query?.archivesId
      }
    })
    .then(resp => {
      const response = resp.data;

      evaluateDetail.value = transformDataExpand(response, "histories");
    });
};
const resultRawJson = ref();
const horizontalData = ref();
const compareReportDetail = ref();
const compareSuggestion = ref();
provide("resultRawJson", resultRawJson);
provide("latestResultRawJson", resultRawJson);
provide("horizontalData", horizontalData);
provide("compareReportDetail", compareReportDetail);
provide("compareSuggestion", compareSuggestion);
const curMenu = ref();
const initData = () => {
  getArchivesReport();
  getEvaluateDetail();
  curMenu.value =
    route.query.type || route.query.type == "health"
      ? "HealthManagementPlan"
      : "planManage";
};
initData();
</script>

<style lang="scss">
.el-scrollbar__view {
  height: 100%;
  .main-content.page-plan-detail {
    margin: 0;
  }
}
.page-plan-detail {
  overflow: hidden;
  .data-container {
    height: calc(100% - 48px);
    width: 100%;
  }
}
</style>
