<template>
  <div>
    <AutoCompleteStep
      v-if="isVisibleAnalyze && !stepInit"
      class="bg-white rounded"
      @confirm="stepConfirm"
    />
    <template v-if="stepInit">
      <template v-if="needQA">
        <DiseaseQA
          :userId="route.query.archivesId"
          :diseaseId="route.query.illnessId"
          @confirm="diseaseQAConfirm"
        />
      </template>
      <div v-show="!needQA">
        <div class="grid grid-cols-2 gap-2">
          <div class="bg-white border border-gray-100">
            <div
              class="flex items-center justify-between p-3 shadow-sm bg-white mb-3"
            >
              <div>
                <h3 class="" v-if="illName">当前评估疾病： {{ illName }}</h3>
              </div>
              <div>
                <!-- @click="" -->
                <el-button
                  v-if="isVisibleAnalyze"
                  type="primary"
                  plain
                  @click="
                    stepInit = false;
                    getDiseaseAnalysis();
                  "
                  >智能分析</el-button
                >
                <el-button
                  type="primary"
                  plain
                  @click="handleSave"
                  v-if="!state.detail.status || !pageType || isEvaluateTime"
                  >保存</el-button
                >
                <el-button type="danger" plain @click="handleQuit"
                  >退出</el-button
                >

                <el-button type="primary" plain @click="handleBacklog"
                  >待办事项管理</el-button
                >
              </div>
            </div>
            <div v-if="!state.detail.status">
              <div v-if="isEvaluateTime || pageType !== 'evaluate'">
                <el-scrollbar style="height: calc(100vh - 220px)">
                  <div class="p-3">
                    <div v-if="pageType != 'edit'">
                      <el-card class="mb-2">
                        <template #header>
                          <h3>评估时间范围</h3>
                        </template>
                        <div v-if="isEvaluate">
                          {{ state?.detail?.createdAt?.split(" ")[0] }} 至
                          {{
                            state?.detail?.nextTime?.split(" ")[0] ||
                            moment().format("YYYY-MM-DD")
                          }}
                        </div>
                        <div v-else>
                          <el-text
                            >-- 至
                            {{ moment().format("YYYY-MM-DD") }} 期间</el-text
                          >
                        </div>
                      </el-card>
                      <el-card v-if="isEvaluate" class="mb-2">
                        <template #header>
                          <div class="flex items-center justify-between">
                            <el-row class="flex items-center">
                              <el-tag class="mr-2" v-if="state.lastLevelName">
                                {{ formatLevel(state.lastLevelName) }}
                              </el-tag>
                              <el-tag class="mr-2" v-else>{{
                                manageLevel[state.lastLevel]?.anotherName
                              }}</el-tag>
                              <h3>设定的管理目标</h3>
                            </el-row>
                            <div class="text-right">
                              <el-button
                                type="primary"
                                link
                                @click="handleWatchSuggest"
                                >查看健康建议</el-button
                              >
                            </div>
                          </div>
                        </template>
                        <div>
                          {{ state.detail?.target }}
                        </div>
                      </el-card>
                      <el-card v-if="isEvaluate" class="mb-2">
                        <template #header>
                          <div class="flex items-center justify-between">
                            <el-row class="flex items-center">
                              <h3>期间该用户待办事项完成情况</h3>
                            </el-row>
                            <div class="text-right">
                              <el-text>
                                统计日期：
                                {{ state?.detail?.createdAt?.split(" ")[0] }} 至
                                {{ moment().format("YYYY-MM-DD") }}
                              </el-text>
                            </div>
                          </div>
                        </template>
                        <div>
                          <div
                            v-for="(backlog, index) in state.backlogItemList"
                            :key="index"
                          >
                            <div v-for="it in backlog.checkItems" :key="it.id">
                              <el-text :tag="it.done ? 'del' : 'span'">
                                <el-text>{{ backlog.date }}</el-text>
                                <el-text class="ml-2">{{ it.content }}</el-text>
                              </el-text>
                            </div>
                          </div>
                        </div>
                      </el-card>
                      <evaluate-card shadow="always">
                        <template #header>
                          <div class="flex justify-between">
                            <h3>健康状况评估:</h3>
                            <el-button
                              v-if="
                                (state.analyzeDetail?.tools || []).find(
                                  v => !v.toolType
                                )
                              "
                              type="primary"
                              plain
                              @click="changeQAView"
                              >{{
                                Array.isArray(state.analyzeDetail?.tools)
                                  ? `${
                                      state.analyzeDetail?.tools.find(
                                        v => !v.toolType
                                      )?.toolName
                                    }`
                                  : "评估"
                              }}</el-button
                            >
                          </div>
                        </template>
                        <div>
                          <el-text bold size="large" tag="b"
                            >现存主要问题:</el-text
                          >
                          <div class="flex mt-4">
                            <el-input
                              v-model="state.problem"
                              placeholder="（选填）请输入现存主要问题，如：xx指标异常，吸烟等"
                              clearable
                            />
                            <el-button
                              type="primary"
                              class="ml-2"
                              @click="handleSaveIllness"
                              >确认</el-button
                            >
                          </div>
                          <div>
                            <el-tag
                              class="mr-2 mt-4"
                              closable
                              @close="handleCloseTag(index)"
                              v-for="(item, index) in tagList"
                              :key="index"
                              >{{ item }}</el-tag
                            >
                          </div>
                          <ComponentDiseaseAnalysis
                            v-if="state.analyzeDetail?.mainProblem"
                            :list="state.analyzeDetail?.mainProblem"
                          />
                        </div>
                        <template #footer>
                          <div>
                            <el-form-item label="12" required>
                              <template #label> 目前健康状况评价: </template>
                              <el-select
                                v-model="state.result"
                                placeholder="请选择评价"
                                filterable
                              >
                                <el-option
                                  v-for="item in state.resultList"
                                  :key="item.id"
                                  :label="item.properties.name"
                                  :value="item.id"
                                />
                              </el-select>
                            </el-form-item>
                            <ComponentDiseaseAnalysis
                              v-if="state.analyzeDetail?.managEffect"
                              :list="state.analyzeDetail?.managEffect"
                            />
                          </div>
                        </template>
                      </evaluate-card>
                      <div
                        class="bg-white mt-2 mb-2"
                        style="width: 100%; border: 1px solid #fff"
                      >
                        <el-divider> 下个阶段管理设置 </el-divider>
                      </div>
                    </div>
                    <!-- 下次评估时间 -->
                    <div class="mt-2">
                      <el-card>
                        <template #header>
                          <h3>下次评估时间:</h3>
                        </template>
                        <el-form-item label="下次评估间隔天数" required>
                          <el-input
                            type="number"
                            placeholder="请输入天数"
                            style="width: 100px"
                            class="ml-2 mr-2"
                            v-model="state.interval"
                          />天，系统将在<span
                            style="color: #f56c6c; font-weight: bold"
                            >{{ formatTime(state.interval)?.label }}</span
                          >
                          提醒您对该用户进行下一次评估
                        </el-form-item>
                        <ComponentDiseaseAnalysis
                          v-if="state.analyzeDetail?.nextAssessmentTime"
                          :list="state.analyzeDetail?.nextAssessmentTime"
                        />
                        <div class="flex items-center flex-wrap" />
                      </el-card>
                    </div>
                    <!-- 下次评估时间 -->
                    <div class="mt-2">
                      <el-card>
                        <template #header>
                          <el-form-item>
                            <template #label>
                              <h3 style="color: #333">
                                下次评估前的预防/管理分组：
                              </h3>
                            </template>
                          </el-form-item>
                        </template>
                        <div>
                          <el-form-item label="预防/管理分组：" required>
                            <el-select
                              v-model="state.group"
                              filterable
                              placeholder="请选择"
                            >
                              <el-option
                                v-for="item in state.groupList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                              />
                            </el-select>
                          </el-form-item>
                        </div>

                        <ComponentDiseaseAnalysis
                          v-if="state.analyzeDetail?.manageLevel"
                          :list="state.analyzeDetail?.manageLevel"
                        />
                      </el-card>
                    </div>
                    <div class="mt-2">
                      <el-card>
                        <template #header>
                          <el-form-item label="" required>
                            <template #label>
                              <h3>下次评估前的管理目标：</h3>
                            </template>
                          </el-form-item>
                        </template>
                        <div>
                          <el-input
                            v-model="state.target"
                            :rows="4"
                            type="textarea"
                            placeholder="请输入管理目标"
                          />
                        </div>
                        <ComponentDiseaseAnalysis
                          v-if="state.analyzeDetail?.manageTargets"
                          :list="state.analyzeDetail?.manageTargets"
                        />
                      </el-card>
                    </div>
                    <div class="mt-2">
                      <el-card>
                        <template #header>
                          <div class="flex justify-between">
                            <h3>下次评估前对该用户的个性化健康建议</h3>
                            <div>
                              <Auth value="healthManage:suggestion:view">
                                <el-button
                                  type="primary"
                                  @click="visibleHealthAdviceLibrary = true"
                                  >健康建议库</el-button
                                >
                              </Auth>
                            </div>
                          </div>
                        </template>
                        <div>
                          <Editor v-model:value="state.advise" />
                        </div>
                      </el-card>
                      <ComponentDiseaseAnalysis
                        v-if="state.analyzeDetail?.personalHealthAdvice"
                        :list="state.analyzeDetail?.personalHealthAdvice"
                      />

                      <el-card class="mt-2">
                        <template #header>
                          <div class="flex justify-between">
                            <h3>下次评估前对该用户关键指标追踪</h3>
                          </div>
                        </template>
                        <div class="flex flex-wrap">
                          <div class="mr-2 mb-2">
                            <el-tag
                              closable
                              size="large"
                              v-for="(item, index) in metricInfo.list"
                              :key="item.id"
                              class="mr-2"
                              @close="handleDeleteMetric(item, index)"
                            >
                              <div class="flex items-center">
                                <div>{{ item.name }}</div>
                                <el-divider direction="vertical" />
                                <div>
                                  <span
                                    v-for="(value, key) in item.list"
                                    :key="value.id"
                                    >{{ value.name }}、</span
                                  >
                                </div>
                              </div>
                            </el-tag>
                          </div>
                          <div class="mb-2">
                            <el-select
                              v-model="metricInfo.projectId"
                              filterable
                              clearable
                              collapse-tags
                              placeholder="请选择检查项目"
                              @change="searchRelateNodes"
                            >
                              <el-option
                                v-for="(item, index) in metricInfo.projectList"
                                :key="index"
                                :label="item.name"
                                :value="item.id"
                              />
                            </el-select>

                            <el-select
                              v-model="metricInfo.nodes"
                              multiple
                              filterable
                              clearable
                              collapse-tags
                              :disabled="!metricInfo.projectId"
                              placeholder="请选择内容"
                            >
                              <el-option
                                v-for="(item, index) in metricInfo.nodeList"
                                :key="index"
                                :label="item.name"
                                :value="item.id"
                              />
                            </el-select>
                            <el-button
                              type="primary"
                              class="ml-2"
                              @click="handleAddMetric"
                              >添加</el-button
                            >
                          </div>
                        </div>
                      </el-card>
                    </div>
                  </div>
                </el-scrollbar>
              </div>

              <div v-else>
                <el-card shadow="never">
                  <div class="text-center">
                    <div style="font-size: 50px">
                      <el-icon style="color: var(--el-color-primary)"
                        ><Calendar
                      /></el-icon>
                    </div>
                    <h2>未到设定的评估日期，无法评估</h2>
                    <div class="flex items-center justify-center">
                      <h2 class="mt-4 mb-4 mr-4">
                        设置的评估日期：{{ evaluateDate }}
                      </h2>
                      <el-button type="primary"
                        >还剩
                        {{ timeDiffer(state.detail?.nextTime) }} 天</el-button
                      >
                    </div>
                    <el-button
                      type="primary"
                      plain
                      style="width: 300px; height: 40px"
                      @click="handleSet"
                      >修改设置</el-button
                    >
                  </div>
                </el-card>
              </div>
            </div>
            <div v-else>
              <el-card>
                <div class="text-center">
                  <div style="font-size: 50px">
                    <el-icon style="color: var(--el-color-primary)"
                      ><VideoPause
                    /></el-icon>
                  </div>
                  <h2 class="mb-3">该管理已暂停，无法评估</h2>
                  <el-button
                    type="primary"
                    plain
                    style="width: 300px; height: 40px"
                    @click="handleRecover"
                    >恢复管理</el-button
                  >
                </div>
              </el-card>
            </div>
          </div>
          <div class="">
            <el-tabs
              type="border-card"
              v-model="state.currentTab"
              @tab-click="handleChangeTab"
            >
              <el-tab-pane
                :label="item.name"
                :name="item.key"
                v-for="item in menuList"
                :key="item.key"
                ref="historyRef"
                lazy
              >
                <el-scrollbar style="height: calc(100vh - 204px)">
                  <component
                    v-if="item?.component"
                    :is="item?.component"
                    :list="state.historyData"
                    :nodeId="route.query.illnessId"
                  />
                </el-scrollbar>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </template>
    <ComponentDialogBacklog v-model:show="state.visibleBacklog" />
    <ComponentDialogPreviewSuggest
      v-model:show="state.visiblePreview"
      :data="state.detail"
    />

    <DialogHealthAdviceLibrary
      v-model:show="visibleHealthAdviceLibrary"
      @onAdd="handleAddHealthAdviceLibrary"
    />

    <el-dialog v-model="QAHistoryDialogVisible">
      <div class="bg-gray-50 rounded">
        <div class="p-4">
          <div class="mb-4">
            <div class="text-gray-700 text-sm mb-2">分析结果：</div>
            <div>{{ diseaseAnalysisResult.result }}</div>
          </div>
          <div v-if="diseaseAnalysisResult.reasons">
            <div class="text-gray-700 text-sm mb-2">分析依据：</div>
            <div
              v-for="(item, index) in diseaseAnalysisResult.reasons"
              :key="index"
            >
              {{ item }}
            </div>
          </div>
          <div class="flex justify-end">
            <el-button
              type="warning"
              plain
              @click="
                QAHistoryDialogVisible = false;
                needQA = true;
              "
              >重新分析</el-button
            >
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { computed, reactive, ref, defineAsyncComponent, nextTick } from "vue";
import { Tools, Calendar, VideoPause } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import moment from "moment";
const [route, router] = [useRoute(), useRouter()];
import { useManageProjectStoreHook } from "@/store/modules/manageProject";

import EvaluateCard from "./components/EvaluateCard.vue";
import ComponentDialogBacklog from "./components/DialogBacklog.vue";
import ComponentDialogPreviewSuggest from "./components/DialogPreviewSuggest.vue";
import DialogHealthAdviceLibrary from "@/views/healthRisk/components/DialogHealthAdviceLibrary.vue";
import ComponentDiseaseAnalysis from "./components/DiseaseAnalysis.vue";
import DiseaseQA from "./components/DiseaseQA.vue";
import AutoCompleteStep from "./components/AutoCompleteStep.vue";
import Editor from "@/components/Editor.vue";

import { request, transformDataExpand, timeDiffer } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { manageLevel, formatLevel } from "@/enums/managementPlan";

const currentArchiveId = computed(() => {
  return useManageProjectStoreHook()?.currentArchiveId;
});

const stepInit = ref(false);
const stepConfirm = () => {
  stepInit.value = true;
};

const state = reactive({
  problem: "",
  level: "",
  target: "",
  advise: "",
  visibleSet: false,
  setItemList: [],
  visibleBacklog: false,
  visiblePreview: false, // 查看健康建议
  interval: 30,
  resultList: [],
  result: "",
  detail: {},
  historyData: [],
  currentTab: "indicator",
  backlogItemList: [],
  lastLevel: 0,
  lastLevelName: "",
  analyzeDetail: {}, // 智能评估详情
  diseaseModels: [],
  groupList: [], // 预防管理分组数据
  group: undefined // 预防管理分组数据选中的分组
});
const metricInfo = reactive({
  list: [],
  projectList: [],
  projectId: "",
  nodeList: [],
  nodes: []
});
const itemId = computed(() => {
  return route.query.id;
});
const historyRef = ref([]);
const isEvaluateTime = computed(() => {
  if (!itemId.value) return;
  return timeDiffer(state.detail?.nextTime?.split(" ")[0]) < 1;
});
const isEvaluate = computed(() => {
  return route.query?.type == "evaluate";
});
const isCreate = computed(() => {
  return !router.query?.type;
});
const isVisibleAnalyze = computed(() => {
  if (!state.diseaseModels?.length) return false;
  if (
    state.diseaseModels.findIndex(v => v.diseaseId == route.query?.illnessId) >
    -1
  )
    return true;
});
const isToday = () => {
  return (
    state?.detail?.createdAt?.split(" ")[0] == moment().format("YYYY-MM-DD")
  );
};
const pageType = computed(() => {
  return route.query?.type;
});
const evaluateDate = computed(() => {
  // if(state?.detail?.createdAt?.split(" ")[0] == state)
  return state?.detail?.nextTime?.split(" ")[0];
});
const IndicatorTrends = defineAsyncComponent(() =>
  import("./components/IndicatorTrends.vue")
);
const CheckData = defineAsyncComponent(() =>
  import("./components/PlanCheckData.vue")
);
const Archives = defineAsyncComponent(() =>
  import("./components/PlanArchives.vue")
);
const AssessmentHistory = defineAsyncComponent(() =>
  import("./components/AssessmentHistory.vue")
);
const DiseaseVisit = defineAsyncComponent(() =>
  import("./components/DiseaseVisit.vue")
);
const DataCalcTool = defineAsyncComponent(() =>
  import("./components/DataCalcTool.vue")
);
const menuList = [
  {
    name: "关键指标趋势",
    key: "indicator",
    component: IndicatorTrends
  },
  {
    name: "检查数据汇总与对比",
    key: "checkDataCollect",
    component: CheckData
  },
  {
    name: "评估历史记录",
    key: "evaluationHistory",
    component: AssessmentHistory
  },
  {
    name: "疾病回访数据",
    key: "visitIllness",
    component: DiseaseVisit
  },
  {
    name: "档案信息",
    key: "archivalInformation",
    component: Archives
  },
  {
    name: "数据达标计算工具",
    key: "DataCalcTool",
    component: DataCalcTool
  }
];
const illName = computed(() => {
  return route.query.name;
});
const level = computed(() => Number(route.query.level) || "");
const tagList = ref([]);
const visibleHealthAdviceLibrary = ref(false);

const handleCloseTag = index => {
  tagList.value.splice(index, 1);
};
const handleGetSetItem = data => {
  state.setItemList = data;
  console.log("拿到的数据", data);
};
const handleBacklog = () => {
  state.visibleBacklog = true;
};
const handleQuit = () => {
  router.back();
};
const handleSaveIllness = () => {
  tagList.value.push(state.problem);
  state.problem = "";
};
const handleWatchSuggest = () => {
  state.visiblePreview = true;
};
const handleChangeTab = value => {};
const handleSet = () => {
  // state.visibleSet = true;
  router.replace(
    `/healthManagement/evaluate?illnessId=${route.query.illnessId}&name=${illName.value}&id=${route.query?.id}&type=edit&archivesId=${currentArchiveId.value}&level=${level.value}`
  );
};
const handleRecover = () => {
  ElMessageBox.confirm("确定继续这个疾病的管理吗？", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(async () => {
      request
        .post("/platformApi/dataService/diseaseManage/update/status", {
          id: state.detail?.id,
          status: 0
        })
        .then(resp => {
          ElMessage.success(resp.message);
          getDetail();
        });
    })
    .catch(err => {});
};
const getResultList = () => {
  request
    .get("/platformApi/graphService/open/node/paginate", {
      params: {
        pageSize: 9999,
        tag: "管理效果"
      }
    })
    .then(resp => {
      state.resultList = resp.data.list;
    });
};
const getDiseaseModels = () => {
  request
    .get("/platformApi/dataService/diseaseManage/diseaseModels")
    .then(resp => {
      state.diseaseModels = resp.data;
      nextTick(() => {
        if (!isVisibleAnalyze.value) {
          stepInit.value = true;
        }
      });
      getDiseaseAnalysis();
    });
};
const getDetail = () => {
  // request
  //   .get("/dataService/diseaseManage", {
  //     params: {
  //       id: itemId.value
  //     }
  //   })
  //   .then(resp => {
  //     state.detail = resp.data;
  //     let { focus, effect, target, level, advise } = resp.data;
  //     tagList.value = focus || [];
  //     state.result = effect.id;
  //     state.target = target;
  //     state.level = level;
  //     state.advise = advise;
  //     getBacklogItemList();
  //   });
  request
    .get("/dataService/diseaseManage/detail", {
      params: {
        archiveId: currentArchiveId.value
      }
    })
    .then(resp => {
      if (itemId.value) {
        const current = resp.data.find(v => v.id == itemId.value);
        state.detail = current;
        state.historyData = transformDataExpand([current], "histories");

        const {
          focus,
          effect,
          target,
          advise,
          nextTime,
          indicator,
          group,
          levelName
        } = current;
        if (pageType.value == "edit") {
          tagList.value = state.detail.histories.length ? [] : focus; // 第二次评估不会显示上次存在的问题
          state.result = effect.id;
          state.target = target;
          // state.level = level.value;
          state.advise = advise;
          metricInfo.list = indicator;
          state.group = group;
          state.interval = timeDiffer(moment(nextTime.split(" ")[0]));
        } else {
          state.interval = 30;
        }

        // state.interval = timeDiffer(moment(nextTime.split(" ")[0]));
        state.lastLevel = level;
        state.lastLevelName = levelName;
      } else {
        // state.historyData = transformDataExpand(resp?.data, "histories");
        state.historyData = [];
      }

      getBacklogItemList();
    });
};

const getBacklogItemList = () => {
  if (!isEvaluate.value) return;
  request
    .get("dataService/schedule/todoList/duration", {
      params: {
        archiveId: currentArchiveId.value,
        startDate: state?.detail?.createdAt?.split(" ")[0],
        endDate: moment().format("YYYY-MM-DD"),
        filter: 1
      }
    })
    .then(resp => {
      state.backlogItemList = resp.data;
    });
};
const isNonZero = value => {
  // 检验值是否为空（null, undefined, "" 或者 false）
  if (value == null || value === "" || value === false) {
    return false;
  }
  // 对于对象，检验是否有属性
  if (typeof value === "object" && Object.keys(value).length === 0) {
    return false;
  }
  // 其他情况视为非空
  return true;
};
const handleSave = () => {
  if (!state.result) {
    return ElMessage.error("请选择目前健康状况评价");
  }
  if (!level.value) {
    return ElMessage.error("请选择预防/管理级别");
  }
  if (!state.group) {
    return ElMessage.error("请选择预防/管理分组");
  }
  if (!state.target) {
    return ElMessage.error("请输入管理目标");
  }
  const params = {
    archiveId: currentArchiveId.value,
    disease: illName.value,
    diseaseId: route.query?.illnessId,
    focus: tagList.value,
    effectId: state.result,
    target: state.target,
    level: level.value,
    group: state.group,
    nextTime: formatTime(state.interval)?.value,
    advise: state.advise,
    source: state.detail[0]?.source,
    indicator: metricInfo.list
  };
  if (state.detail?.source) {
    params.source = state.detail?.source;
  }
  if (pageType.value == "edit") {
    params.id = Number(itemId.value);
  }

  request
    .post(
      pageType.value == "edit"
        ? "/dataService/diseaseManage/update"
        : "/dataService/diseaseManage/create",
      params
    )
    .then(resp => {
      ElMessage.success(resp.message);
      router.back();
    });
};
const formatTime = time => {
  const count = Number(time);
  const { years, months, date } = moment().toObject();
  if (!count)
    return {
      label: `${years}年${months + 1}月${date}日`,
      value: moment().format("YYYY-MM-DD")
    };
  const convertDate = moment()
    .day(moment().day() + count)
    .toObject();
  return {
    label: `${convertDate.years}年${convertDate.months + 1}月${
      convertDate.date
    }日`,
    value: moment()
      .day(moment().day() + count)
      .format("YYYY-MM-DD")
  };
};
const getDiseaseAnalysis = () => {
  if (!isVisibleAnalyze.value) return;
  request
    .post("/dataService/diseaseManage/diseaseAnalysis", {
      diseaseId: route.query?.illnessId,
      archiveId: currentArchiveId.value
    })
    .then(resp => {
      state.analyzeDetail = resp.data?.result;
      needQA.value = state.analyzeDetail.needQA;
    });
};

const needQA = ref(false);
const QAHistoryDialogVisible = ref(false);
const diseaseAnalysisResult = ref({
  result: "",
  reasons: []
});
const changeQAView = () => {
  getDiseaseAnalysisResult();
  QAHistoryDialogVisible.value = true;
};
const getDiseaseAnalysisResult = async () => {
  const { data } = await request.get(
    `/dataService/diseaseManage/diseaseAnalysis/result`,
    {
      params: {
        diseaseId: route.query?.illnessId,
        archiveId: currentArchiveId.value
      }
    }
  );
  diseaseAnalysisResult.value = data;
};
const diseaseQAConfirm = async assessmentInfo => {
  await request.post("/dataService/diseaseManage/diseaseAnalysis/result", {
    diseaseId: route.query?.illnessId,
    archiveId: currentArchiveId.value,
    result: assessmentInfo.result,
    reasons: assessmentInfo.accordance,
    errInfos: assessmentInfo.errInfo,
    otherData: assessmentInfo.otherData
  });
  getDiseaseModels();
  needQA.value = false;
};

const handleAddHealthAdviceLibrary = content => {
  state.advise = content;
};
const searchNodes = async (type = 0, name = "") => {
  const { data } = await request.post(
    "/idcService/mechanism/medicalData/transferItem/query",
    {
      archivesId: route.query.archivesId,
      itemIds: [],
      nodeIds: [],
      date: []
    }
  );
  metricInfo.projectList = data.list || [];
};

const searchRelateNodes = async () => {
  metricInfo.nodes = [];
  metricInfo.nodeList =
    metricInfo.projectList.find(v => {
      return v.id == metricInfo.projectId;
    })?.list || [];
};
const handleAddMetric = async () => {
  if (!metricInfo.projectId) {
    return ElMessage.error("请选择检查项目");
  }
  if (!metricInfo.nodes?.length) {
    return ElMessage.error("请选择检查内容");
  }
  const currentProject = metricInfo.projectList.find(v => {
    return v.id == metricInfo.projectId;
  });
  const hasExistIndex = metricInfo.list.findIndex(
    v => v.id == metricInfo.projectId
  );
  if (hasExistIndex > -1) {
    metricInfo.list.splice(hasExistIndex, 1);
  } else {
    currentProject.list = currentProject.list.filter(v =>
      metricInfo?.nodes?.includes(v.id)
    );
    metricInfo.list.push(currentProject);
  }

  metricInfo.projectId = "";
  metricInfo.nodes = [];
  metricInfo.nodeList = [];
};
const handleDeleteMetric = (item, index) => {
  metricInfo.list.splice(index, 1);
};
const getGroupList = () => {
  if (!level.value) return;
  request
    .get(
      `dataService/schemeManage/diseaseManageGroup/paginate?levelId=${level.value}`
    )
    .then(resp => {
      state.groupList = resp.data.list;
    });
};
const initData = async () => {
  await getDiseaseModels();
  searchNodes();
  getGroupList();
  getResultList();
  getDetail();
};
initData();
</script>
<style scoped lang="scss">
.el-scrollbar {
}
.el-form-item {
  color: #333;
  margin-bottom: 0;
}
</style>
