<template>
  <div>
    <div class="flex items-center">
      <div class="flex-1 space-x-2">
        <el-select
          v-model="filter.channelIds"
          placeholder="全部渠道"
          filterable
          multiple
          clearable
          collapse-tags
          @change="channelSelectChange"
        >
          <el-option label="未设置" :value="0" />
          <el-option
            v-for="(item, index) in channelList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <el-select
          v-model="filter.diseaseStatusList"
          placeholder="全部疾病评估情况"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="(item, index) in riskStatus"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="filter.riskDiseaseNames"
          placeholder="全部疾病"
          filterable
          multiple
          clearable
          collapse-tags
        >
          <el-option
            v-for="(item, index) in diseaseNames"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
        <!-- <el-select
          v-model="filter.tumorStatusList"
          placeholder="全部肿瘤风险"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="(item, index) in riskStatus"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="filter.cardiovascularStatusList"
          placeholder="全部心脑血管风险"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="(item, index) in riskStatus"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="filter.customStatusList"
          placeholder="全部肿个性化疾病风险"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="(item, index) in riskStatus"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-cascader
          v-model="filter.archivesTagIds"
          :props="selectProps"
          clearable
          placeholder="请选择标签"
          :options="state.tagCategoryList"
        /> -->
        <el-select v-model.number="filter.suggestionStatus">
          <el-option label="所有综合建议情况" :value="0" />
          <el-option
            v-for="(item, index) in userDataSuggestStatus"
            :key="index"
            :label="item"
            :value="Number(index)"
          />
        </el-select>

        <el-button type="primary" class="ml-2" @click="search">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
      <div>
        <SearchArchivesSelect
          v-model="filter.archivesId"
          placeholder="请选择档案"
          @change="
            v => {
              filter.archivesId = v;
            }
          "
        />
        <el-button type="primary" class="ml-2" @click="search">搜索</el-button>
      </div>
    </div>
    <div>
      <el-table :data="list" class="w-full mt-4" table-layout="auto">
        <el-table-column prop="archives.name" label="用户信息">
          <template #default="{ row }">
            <div>{{ row.archivesId }}</div>
            <div class="whitespace-nowrap">{{ row?.archives?.name }}</div>
            <div class="text-gray-500 text-xs whitespace-nowrap">
              {{ row.archives?.gender == 1 ? "男" : "女" }}，{{
                formatAge(row.archives?.birthday)
              }}岁
            </div>
          </template>
        </el-table-column>
        <el-table-column label="来源渠道" min-width="240">
          <template #default="{ row }">
            {{
              (row.archives?.archivesChannels?.length &&
                row.archives?.archivesChannels.map(v => v.name).join()) ||
              ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="已确诊疾病" min-width="300">
          <template #default="{ row }">
            <div class="flex flex-wrap max-w-[20vw]">
              <div
                v-for="(item, index) in row.confirmDiseaseNames"
                :key="index"
              >
                <div
                  class="bg-purple-50 text-purple-700 rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  {{ item }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有明显风险疾病" min-width="300">
          <template #default="{ row }">
            <div class="flex flex-wrap max-w-[20vw]">
              <div v-for="(item, index) in row.riskDiseaseNames" :key="index">
                <div
                  class="bg-red-50 text-red-700 rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  {{ item }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有一定风险疾病" min-width="300">
          <template #default="{ row }">
            <div class="flex flex-wrap max-w-[20vw]">
              <div
                v-for="(item, index) in row.certainRiskDiseaseNames"
                :key="index"
              >
                <div
                  class="bg-gray-100 text-yellow-600 rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  {{ item }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="缺乏评估数据疾病" min-width="300">
          <template #default="{ row }">
            <div class="flex flex-wrap max-w-[20vw]">
              <div
                v-for="(item, index) in row.lackAssessmentDiseaseNames"
                :key="index"
              >
                <div class="bg-gray-100 rounded py-1 px-2 w-fit m-1 text-sm">
                  {{ item }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="暂无风险疾病" min-width="300">
          <template #default="{ row }">
            <div class="flex flex-wrap max-w-[20vw]">
              <div v-for="(item, index) in row.noRiskDiseaseNames" :key="index">
                <div
                  class="bg-gray-100 text-green-600 rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  {{ item }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="肿瘤风险" min-width="300">
          <template #default="{ row }">
            <div class="flex flex-wrap">
              <div v-for="(item, index) in riskDegreeLabel" :key="index">
                <div
                  v-if="riskFormat(row, 'tumor', index)"
                  :class="`${item.class} ${item.bgClass}`"
                  class="rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  <span> {{ item.label }}: </span>
                  <span>{{ riskFormat(row, "tumor", index) }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="心脑血管风险" min-width="300">
          <template #default="{ row }"
            ><div class="flex flex-wrap">
              <div v-for="(item, index) in riskDegreeLabel" :key="index">
                <div
                  v-if="riskFormat(row, 'cardiovascular', index)"
                  :class="`${item.class} ${item.bgClass}`"
                  class="rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  <span> {{ item.label }}: </span>
                  <span>{{ riskFormat(row, "cardiovascular", index) }}</span>
                </div>
              </div>
            </div></template
          >
        </el-table-column>
        <el-table-column label="个性化风险" min-width="300">
          <template #default="{ row }"
            ><div class="flex flex-wrap">
              <div v-for="(item, index) in riskDegreeLabel" :key="index">
                <div
                  v-if="riskFormat(row, 'custom', index)"
                  :class="`${item.class} ${item.bgClass}`"
                  class="rounded py-1 px-2 w-fit m-1 text-sm"
                >
                  <span> {{ item.label }}: </span>
                  <span>{{ riskFormat(row, "custom", index) }}</span>
                </div>
              </div>
            </div></template
          >
        </el-table-column> -->
        <el-table-column label="操作" width="240px" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="
                router.push({
                  name: `healthRiskHealthRiskDetail`,
                  query: {
                    archivesId: row.archivesId
                  }
                })
              "
              >评估详情</el-button
            >
            <Auth value="archivesReportPdfResult">
              <el-button
                type="primary"
                link
                @click="showDownloadReportDialog(row)"
                >PDF报告</el-button
              >
            </Auth>
            <Auth value="user:medicalData:view">
              <el-button
                type="primary"
                link
                @click="showDownloadReportDialog(row)"
                >PDF报告</el-button
              >
            </Auth>
            <Auth value="archivesReportSuggestionManage">
              <el-button type="primary" link @click="handleUserData(row)"
                >健康建议</el-button
              >
            </Auth>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="justify-end mt-4"
        :current-page="filter.page"
        :page-size="filter.pageSize"
        :total="count"
        background
        layout="total, prev, pager, next, jumper"
        @current-change="
          page => {
            filter.page = page;
            getList();
          }
        "
      />
    </div>

    <el-dialog v-model="downloadReportDialog.visible" title="下载分析报告">
      <div
        v-for="(item, index) in downloadReportDialog.templateList"
        :key="index"
        class="flex flex-col py-6 border-b border-solid border-gray-100 last:border-b-0"
      >
        <div class="flex items-center justify-between mb-2">
          <div class="flex items-center">
            <el-tag v-if="item.isMember" size="small" class="mr-2"
              >用户使用</el-tag
            >
            <span>{{ item.template?.name }}</span>
          </div>
          <span class="text-xs text-gray-500"
            >最近生成时间: {{ item.result?.pdfTransferEndTime || "暂无" }}</span
          >
        </div>
        <div class="flex items-center justify-between">
          <div v-if="item.result" class="flex items-center">
            <img src="@/assets/pdf.png" />
            <span>{{ downloadReportDialog.row.archivesId }}分析报告</span>
          </div>

          <div v-else-if="item.generateState">报告生成中...</div>
          <div v-else>暂无报告</div>
          <div>
            <el-button
              v-if="!item.generateState"
              type="primary"
              class="ml-4"
              @click="generatePdf(item)"
              >{{ item.result ? "更新" : "生成" }}</el-button
            >
            <el-button
              v-else
              type="primary"
              class="ml-4"
              @click="getPdfResultList(downloadReportDialog.row)"
              >刷新</el-button
            >
            <el-button
              type="primary"
              :disabled="!item.result"
              plain
              tag="a"
              target="_blank"
              :href="item.result?.pdfTransferResultUrl"
              >在线预览</el-button
            >
            <el-button
              type="primary"
              :disabled="!item.result"
              @click="
                downloadReportRename(
                  item.result?.pdfTransferResultUrl +
                    '?response-content-type=application/octet-stream',
                  `${downloadReportDialog.row.archivesId}分析报告.pdf`
                )
              "
              >下载报告</el-button
            >
          </div>
        </div>
      </div>
      <el-empty v-if="!downloadReportDialog.templateList.length" />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed, watch, provide, shallowRef } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
  uploadDataType,
  userDataSuggestStatus,
  uploadDataAbandon,
  compareReportUpdateType
} from "@/enumerated/archives";
import SearchArchivesSelect from "@/components/Archives/SearchArchivesSelect.vue";
import { request, formatAge, downloadReportRename } from "@/utils";
import { riskDegreeLabel } from "@/enums/risk";

const [route, router] = [useRoute(), useRouter()];
const filter = ref({
  page: 1,
  pageSize: 10,
  tumorStatusList: [],
  cardiovascularStatusList: [],
  customStatusList: [],
  archivesId: "",
  suggestionStatus: 0,
  archivesTagIds: [],
  channelIds: [],
  diseaseStatusList: [],
  riskDiseaseNames: []
});
const resetFilter = () => {
  filter.value = {
    page: 1,
    pageSize: 10,
    tumorStatusList: [],
    cardiovascularStatusList: [],
    customStatusList: [],
    archivesId: "",
    suggestionStatus: 0,
    archivesTagIds: [],
    channelIds: [],
    diseaseStatusList: [],
    riskDiseaseNames: []
  };
};
const state = reactive({
  tagCategoryList: [] // 标签类别
});
const riskStatus = [
  {
    label: "缺乏评估数据",
    value: 0
  },
  {
    label: "风险较低",
    value: 1
  },
  {
    label: "有一定风险",
    value: 2
  },
  {
    label: "有明显风险",
    value: 3
  },
  {
    label: "已确诊",
    value: 4
  }
];

const list = ref([]);
const count = ref(0);
const getList = async () => {
  let tagIds;
  if (filter.value.archivesTagIds?.length) {
    tagIds = filter.value.archivesTagIds?.map(v => v[1]).join();
  }
  console.log(tagIds);
  const { data } = await request.get(
    `/idcService/mechanism/archivesReport/paginate`,
    {
      params: {
        ...filter.value,
        channelIds: filter.value.channelIds.join(),
        diseaseStatusList: filter.value.diseaseStatusList.join(),
        riskDiseaseNames: filter.value.riskDiseaseNames.join(),
        archivesTagIds: tagIds
      }
    }
  );
  list.value = data.list;
  count.value = data.total;
};

const getTagList = id => {
  if (!id) return;
  return new Promise(resolve => {
    request
      .get(`/tagService/mechanism/tag/list?categoryId=${id}&type=1`)
      .then(resp => {
        resolve(resp.data.list);
      });
  });
};
const selectProps = {
  lazy: true,
  multiple: true,
  lazyLoad: async (node, resolve) => {
    const { value } = node;
    let list = await getTagList(value);
    console.log(list);
    list = list?.map(v => {
      return {
        ...v,
        value: v.id,
        label: v.name,
        leaf: true
      };
    });
    console.log("list", list);

    // Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
    resolve(list);
  }
};
const search = async () => {
  filter.value.page = 1;
  getList();
};
search();

const riskFormat = (row, key, risk) => {
  const level = ["None", "Low", "Mid", "High", "Max"];
  const attr = key + (level[risk] || "");
  return row.riskData[attr];
};

const downloadReportDialog = reactive({
  visible: false,
  row: {},
  templateList: [],
  timer: null,
  count: 0
});

const getPDFTemplateConfig = async row => {
  const { data } = await request.get(
    `/pdfTemplateService/mechanism/pdfTemplateMechanism/list`,
    {
      params: {
        mechanismId: row.lastMedicalReport?.mechanismId
      }
    }
  );
  downloadReportDialog.templateList = (data.list || []).map(v => {
    v.result = null;
    v.generateState = false;
    v.timer = null;
    return v;
  });

  getPdfResultList(row);
};
const getPdfResultList = async row => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/pdfResult/list`,
    {
      params: {
        archivesId: downloadReportDialog.row.archivesId
      }
    }
  );
  if (data.list?.length) {
    downloadReportDialog.templateList = downloadReportDialog.templateList.map(
      v => {
        const result = data.list.find(v2 => v2.pdfTemplateId == v.template.id);
        v.result = result?.pdfTransferStatus == 3 ? result : null;
        v.generateState = result?.pdfTransferStatus == 2;
        return v;
      }
    );
    console.log(downloadReportDialog.templateList);
  }
};

const getTagCategoryList = () => {
  request.get("/tagService/mechanism/tagCategory/list").then(resp => {
    state.tagCategoryList = resp.data.list.map(v => {
      return {
        ...v,
        value: v.id,
        label: v.name
      };
    });
  });
};
// getTagCategoryList();

const showDownloadReportDialog = row => {
  downloadReportDialog.row = { ...row };
  getPDFTemplateConfig(row);
  downloadReportDialog.visible = true;
};
const handleUserData = row => {
  console.log(row);
  // return;
  router.push({
    path: "/healthRisk/interpretUserData",
    query: {
      archivesId: row.archivesId
    }
  });
};
const generatePdf = async pdfRow => {
  // console.log(pdfRow, downloadReportDialog.row)
  await request.post(
    `/idcService/mechanism/medicalData/archivesPdfResult/generate`,
    {
      sn: downloadReportDialog.row.lastMedicalReport?.sn,
      pdfTemplateId: pdfRow.template.id,
      archivesId: downloadReportDialog.row.archivesId,
      mechanismId: pdfRow.mechanismId
    }
  );
  ElMessage.info("开始生成,请耐心等待...");
  pdfRow.result = null;
  pdfRow.generateState = true;
  pdfRow.timer && clearTimeout(pdfRow.timer);
  refreshDetail(pdfRow);
};
const refreshDetail = async pdfRow => {
  if (downloadReportDialog.count > 15) {
    pdfRow.timer && clearTimeout(pdfRow.timer);
    return;
  }
  if (!pdfRow.result) {
    downloadReportDialog.count++;
    pdfRow.timer = setTimeout(() => {
      getPdfResultList(downloadReportDialog.row);
      refreshDetail(pdfRow);
    }, 3e3);
  } else {
    pdfRow.timer && clearTimeout(pdfRow.timer);
  }
};

const channelList = ref([]);
const getChannelList = async () => {
  const { data } = await request.get(
    "/archivesService/mechanism/channel/paginate",
    {
      params: {
        pageSize: 9999
      }
    }
  );
  channelList.value = data.list;
};
getChannelList();

const channelSelectChange = values => {
  if (!values.length) return;
  const newVal = values[values.length - 1];
  if (newVal) {
    filter.value.channelIds = values.filter(v => v);
  } else {
    filter.value.channelIds = [0];
  }
};
const diseaseNames = shallowRef([]);
const getDiseaseNames = async () => {
  const { data } = await request.get(
    "/idcService/mechanism/archivesReport/diseaseNames"
  );
  diseaseNames.value = data.list;
};
getDiseaseNames();
</script>

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