<template>
  <div>
    <div class="flex items-center">
      <Auth value="channelMedicalReport:edit">
        <el-button type="primary" @click="appendTeamReportVisible = true"
          >新建</el-button
        >
      </Auth>
      <div class="flex flex-1 items-center justify-end space-x-2">
        <el-select v-model="filter.mechanismId" filterable>
          <el-option label="全部渠道" :value="''"></el-option>
          <el-option
            v-for="(item, index) in channelList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-input
          v-model="filter.name"
          class="w-40"
          placeholder="请输入报告名称"
        ></el-input>
        <el-button
          type="primary"
          @click="
            filter.page = 1;
            getList();
          "
          >查询</el-button
        >
      </div>
    </div>
    <el-table class="mt-4" :data="list">
      <el-table-column
        label="所属渠道"
        prop="channel.name"
      ></el-table-column>
      <el-table-column label="报告名称" prop="name"></el-table-column>
      <el-table-column label="创建日期" prop="createdAt"></el-table-column>
      <el-table-column
        label="分析体检总人数"
        prop="personTotal"
      ></el-table-column>
      <el-table-column
        label="分析体检总份数"
        prop="medicalDataTotal"
      ></el-table-column>
      <el-table-column label="分析体检日期">
        <template #default="{ row }">
          <span>{{ row.medicalDataStartDate }}</span>
          <span>~</span>
          <span>{{ row.medicalDataEndDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          
          <Auth value="channelMedicalReport:analysis">
            <el-button
              type="primary"
              link
              @click="
                router.push({
                  path: '/team/teamReport/analysis',
                  query: { id: row.id }
                })
              "
              >分析结果</el-button
            >
          </Auth>

              <el-button
                type="primary"
                link
                :disabled="!row.medicalDataTotal"
                @click="showDownloadReportDialog(row)"
                >PDF报告</el-button
              >
          <el-button type="warning" link @click="toDataSource(row)"
            >数据源</el-button
          >
          <Auth value="channelMedicalReport:delete">
            <el-popconfirm
              title="确定要删除这个分析结果吗？"
              @confirm="removeItem(row)"
            >
              <template #reference>
                <el-button type="danger" link>删除</el-button>
              </template>
            </el-popconfirm>
          </Auth>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-4 justify-end"
      background
      :current-page="filter.page"
      :page-size="filter.pageSize"
      :total="total"
      layout="total, prev, pager, next"
      @current-change="
        p => {
          filter.page = p;
          getList();
        }
      "
    ></el-pagination>
    <AppendTeamReport
      v-model:visible="appendTeamReportVisible"
      :channelList="channelList"
      @confirm="getList"
    />

    <el-dialog v-model="downloadReportDialog.visible" title="下载分析报告">
      <div
        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">

            <span>团队报告</span>
          </div>
          <span class="text-xs text-gray-500"
            >最近生成时间: {{ downloadReportDialog.detail?.pdfTransferEndTime || "暂无" }}</span
          >
        </div>
        <div class="flex items-center justify-between">
          <div v-if="downloadReportDialog.detail.pdfTransferResultUrl" class="flex items-center">
            <img src="@/assets/pdf.png" />
            <span
              >{{downloadReportDialog.row.name}}.pdf</span
            >
          </div>

          <div v-else-if="downloadReportDialog.detail.pdfTransferStatus == 2">报告生成中...</div>
          <div v-else>暂无报告</div>
          <div>
            <el-button
              v-if="downloadReportDialog.detail.pdfTransferStatus != 2"
              type="primary"
              class="ml-4"
              @click="generatePdf(item)"
              >{{ downloadReportDialog.detail.pdfTransferResultUrl ? "更新" : "生成" }}</el-button
            >
            <el-button
              v-else
              type="primary"
              class="ml-4"
              @click="getDetail"
              >刷新</el-button
            >
            <el-button
              type="primary"
              :disabled="!downloadReportDialog.detail.pdfTransferResultUrl"
              plain
              tag="a"
              target="_blank"
              :href="downloadReportDialog.detail.pdfTransferResultUrl"
              >在线预览</el-button
            >
            <el-button
              type="primary"
              :disabled="!downloadReportDialog.detail.pdfTransferResultUrl"
              @click="
                downloadReportRename(
                  downloadReportDialog.detail.pdfTransferResultUrl +
                    '?response-content-type=application/octet-stream',
                  `${downloadReportDialog.row.name || '团队报告'}_${dayjs(new Date()).format('YYYYMMDDHHmmss')}.pdf`
                )
              "
              >下载报告</el-button
            >
          </div>
        </div>
      </div>

    </el-dialog>
  </div>
</template>

<script setup>
import { request, downloadReportRename } from "@/utils";
import { ElMessage } from "element-plus";
import { ref, reactive  } from "vue";
import AppendTeamReport from "./components/AppendTeamReport.vue";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
const [route, router] = [useRoute(), useRouter()];
const filter = ref({
  mechanismId: "",
  name: ""
});
const list = ref([]);
const total = ref(0);
const getList = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/channelMedicalReport/paginate`,
    {
      params: filter.value
    }
  );
  list.value = data.list;
  total.value = data.total;
};
getList();
const channelList = ref([]);
const getChannelList = async () => {
  const { data } = await request.get("/archivesService/mechanism/channel/paginate", {
    params: {
      pageSize: 9999
    }
  });
  channelList.value = data.list;
};
getChannelList();
const appendTeamReportVisible = ref(false);
const removeItem = async row => {
  await request.post("/idcService/mechanism/channelMedicalReport/delete", {
    id: row.id
  });
  ElMessage.success("删除成功");
  getList();
};
const toDataSource = row => {
  sessionStorage.setItem(
    "tempReportDataSource",
    JSON.stringify({
      page: 1,
      isAbandon: 2,
      type: 1,
      mechanismId: row.mechanism.id,
      startTime:'',
      endTime:'',
      snList: row.medicalDataIds
    })
  );
  router.push({
    name: "dataUploadData"
  });
};




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

const showDownloadReportDialog = row => {
  downloadReportDialog.row = { ...row };
  getDetail()
  downloadReportDialog.visible = true;
};
const getDetail = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/channelMedicalReport/detail`,
    {
      params: {
        id: downloadReportDialog.row.id
      }
    }
  );
  downloadReportDialog.detail = data.detail;
};
const generatePdf = async () => {
  await request.post(
    `/idcService/mechanism/channelMedicalReport/generate/pdfReport`,
    {
      id: downloadReportDialog.row.id
    }
  );
  ElMessage.info("开始生成,请耐心等待...");
  getDetail();
};
</script>

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