<template>
  <div>
    <div class="flex items-center flex-wrap">
      <div class="flex flex-wrap flex-1 items-center justify-end space-x-2">
        <el-select v-model.number="filter.suggestionStatus">
          <el-option label="所有综合建议情况" :value="0"></el-option>
          <el-option
            v-for="(item, index) in userDataSuggestStatus"
            :key="index"
            :label="item"
            :value="Number(index)"
          ></el-option>
        </el-select>
        <el-select
          v-model="filterSnType"
          @change="
            filter.medicalDataSn = '';
            filter.archivesId = '';
          "
        >
          <el-option label="数据批次号" value="medicalDataSn"></el-option>
          <el-option label="档案编号" value="archivesId"></el-option>
        </el-select>
        <el-input
          v-model="filter[filterSnType]"
          class="w-40"
          placeholder="请输入查询内容"
        ></el-input>

        <el-button @click="resetFilter">重置</el-button>
        <el-button
          type="primary"
          @click="
            filter.page = 1;
            getList();
          "
          >搜索</el-button
        >
      </div>
    </div>
    <div>
      <el-table
        :data="list"
        class="w-full mt-4"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="archivesId" label="档案号"></el-table-column>
        <el-table-column prop="sn" label="待处理数据">
          <template #default="{ row }">
            <div v-for="(item, index) in row.totalCharts" :key="index">
              <span v-if="item.awaitTotal"
                >{{ uploadDataType[item.type] }}：{{ item.awaitTotal }}份</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="处理中数据">
          <template #default="{ row }">
            <div v-for="(item, index) in row.totalCharts" :key="index">
              <span v-if="item.processTotal"
                >{{ uploadDataType[item.type] }}：{{
                  item.processTotal
                }}份</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="待确认数据">
          <template #default="{ row }">
            <div v-for="(item, index) in row.totalCharts" :key="index">
              <span v-if="item.doneTotal"
                >{{ uploadDataType[item.type] }}：{{ item.doneTotal }}份</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="已确认数据">
          <template #default="{ row }">
            <div v-for="(item, index) in row.totalCharts" :key="index">
              <span v-if="item.confirmTotal"
                >{{ uploadDataType[item.type] }}：{{
                  item.confirmTotal
                }}份</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lastTime" label="用户数据分析截止日期">
          <template #default="{ row }">
            <span>{{ row.confirmTotal ? row.lastTime : "" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="suggestionStatus"
          label="综合建议填写情况"
          :formatter="v => userDataSuggestStatus[v.suggestionStatus]"
        ></el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="primary" link @click="showUpdateDetail(row)"
              >变化详情</el-button
            >
            <Auth value="user:medicalData:view">
              <el-button
                type="primary"
                link
                :disabled="!row.confirmTotal && !row.doneTotal"
                @click="
                  router.push({
                    path: `/data/interpretUserData`,
                    query: {
                      archivesId: row.archivesId
                    }
                  })
                "
                >解读</el-button
              >
            </Auth>
            <Auth value="user:medicalData:view">
              <el-button
                type="primary"
                link
                :disabled="!row.lastMedicalReport?.mechanismId"
                @click="showDownloadReportDialog(row)"
                >PDF报告</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();
          }
        "
      ></el-pagination>
    </div>
    <el-dialog v-model="updateDetail.visible" title="变化详情">
      <div class="p-4">用户ID: {{ updateDetail.row.archivesId }}</div>
      <el-table :data="updateDetail.list" border>
        <el-table-column
          label="更新类型"
          :formatter="v => compareReportUpdateType[v.logType]"
        ></el-table-column>
        <el-table-column prop="updateTime" label="更新时间"></el-table-column>
        <el-table-column prop="medicalDataSn" label="编号"></el-table-column>
        <el-table-column
          label="数据类型"
          :formatter="v => uploadDataType[v.medicalDataType]"
        ></el-table-column>
      </el-table>
    </el-dialog>
    <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?.lastMedicalReport?.files[0]?.fileName
                  .split(".")
                  .slice(0, -1)
                  .join("")
              }}.pdf</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?.lastMedicalReport?.files[0]?.fileName
                    .split('.')
                    .slice(0, -1)
                    .join('')}.pdf`
                )
              "
              >下载报告</el-button
            >
          </div>
        </div>
      </div>
      <el-empty v-if="!downloadReportDialog.templateList.length"></el-empty>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated, watch, provide, h } from "vue";
import { useRoute, useRouter, onBeforeRouteLeave } from "vue-router";
import {
  uploadDataType,
  userDataSuggestStatus,
  uploadDataAbandon,
  compareReportUpdateType
} from "@/enumerated/archives";
import { ElMessage, ElMessageBox } from "element-plus";
import { request, parseJsonData, downloadReportRename } from "@/utils";

import JsonViewer from "vue-json-viewer";
import dayjs from "dayjs";

const router = useRouter();
const filter = ref({
  page: 1,
  pageSize: 10,
  medicalDataSn: "",
  archivesId: "",
  suggestionStatus: 0
});
// const filterDate = ref([dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')])
const filterSnType = ref("archivesId");

// watch(() => filterDate.value, d => {
//   console.log(d);
//   if (d) {
//     [filter.value.startTime, filter.value.endTime] = d
//   }
// })

const tableRowClassName = ({ row, rowIndex }) => {
  if (row.errors) {
    return "bg-red-50";
  }
  return "";
};
const list = ref([]);
const count = ref(0);
const getList = async () => {
  const { data } = await request.get(
    `/platformApi/idcService/backend/medicalData/compareReport/paginate`,
    {
      params: filter.value
    }
  );
  list.value = data.list;
  count.value = data.total;
  sessionStorage.setItem("userDataFilter", JSON.stringify(filter.value));
};
provide("getList", getList);

onBeforeRouteLeave(() => {
  sessionStorage.setItem("userDataFilter", JSON.stringify(filter.value));
});

const resetFilter = () => {
  filter.value = {
    page: 1,
    pageSize: 10,
    medicalDataSn: "",
    archivesId: "",
    suggestionStatus: 0
  };
  getList();
};
const updateDetail = reactive({
  visible: false,
  row: {},
  list: []
});

const showUpdateDetail = row => {
  updateDetail.row = row;
  getUserUpdateDetail();
  updateDetail.visible = true;
};
const getUserUpdateDetail = async () => {
  const { data } = await request.get(
    `/idcService/backend/medicalData/compareReport/log`,
    {
      params: {
        archivesId: updateDetail.row.archivesId
      }
    }
  );
  updateDetail.list = data.list;
};

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

const getPDFTemplateConfig = async row => {
  const { data } = await request.get(
    `/pdfTemplateService/backend/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/backend/medicalData/pdfResult/list`,
    {
      params: {
        // sn: row.lastMedicalReport?.sn,
        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 showDownloadReportDialog = row => {
  downloadReportDialog.row = { ...row };
  getPDFTemplateConfig(row);
  downloadReportDialog.visible = true;
};
const generatePdf = async pdfRow => {
  // console.log(pdfRow, downloadReportDialog.row)
  await request.post(
    `/idcService/backend/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);
  }
};

onMounted(() => {
  const sFilter = sessionStorage.getItem("userDataFilter");
  if (sFilter) {
    filter.value = JSON.parse(sFilter);
  }
  getList();
});
</script>

<style lang="scss">
.el-table .bg-red-50 {
  background: rgb(255, 220, 220);
}
</style>
