<template>
  <div>
    <div class="flex items-center flex-wrap">
      <div class="mr-4">
        <Auth value="data:upload">
          <el-button
            type="primary"
            class="mr-4"
            @click="uploadDialogVisible = true"
            >上传数据</el-button
          >
        </Auth>
        <!-- <span>自动生成分析报告</span>
        <el-switch></el-switch> -->
      </div>
      <div
        class="flex flex-wrap flex-1 items-center justify-end space-x-2 space-y-2"
      >
        <div class="mt-2">
          <el-checkbox
            v-model="filter.isAbandon"
            :true-label="2"
            :false-label="0"
            >隐藏作废数据</el-checkbox
          >
        </div>
        <div>
          <el-date-picker
            v-model="filterDate"
            type="daterange"
            class="w-40"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            :shortcuts="shortcuts"
            placeholder="请选择"
            :disabled-date="disabledDate"
            @change="dateClear"
          />
        </div>

        <el-select v-model.number="filter.type">
          <el-option label="全部数据类型" :value="0"></el-option>
          <template v-for="(item, index) in uploadDataPermissionType">
            <el-option
              v-if="!item?.permission || permissions.includes(item.permission)"
              :key="index"
              :label="item.label"
              :value="Number(index)"
            ></el-option>
          </template>
        </el-select>
        <el-select v-model.string="filter.statusList">
          <el-option label="全部处理状态" value="0"></el-option>
          <el-option
            v-for="(item, index) in uploadDataStatusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="filterSnType"
          @change="
            filter.sn = '';
            filter.archivesId = '';
          "
        >
          <el-option label="数据批次号" value="sn"></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
          type="primary"
          @click="
            filter.page = 1;
            getList();
          "
          >搜索</el-button
        >
      </div>
    </div>
    <div>
      <el-table :data="list" class="w-full mt-4">
        <el-table-column prop="sn" label="数据批次号"></el-table-column>
        <el-table-column
          prop="files.length"
          label="数据份数"
          width="80"
        ></el-table-column>
        <el-table-column label="文件名称">
          <template #default="{ row }">
            <div v-if="row.fileName">{{ row.fileName }}</div>
            <template v-else>
              <!-- <div v-for="(item, index) in row.files || []" :key="index">
                {{ item.fileName }}
              </div> -->

              {{ row.files[0] ? row.files[0].fileName : "未上传原始文件" }}
              {{ row.files.length > 1 ? "等" : "" }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="数据类型"
          :formatter="v => uploadDataType[v.type]"
        ></el-table-column>
        <el-table-column prop="createdAt" label="上传时间"></el-table-column>
        <el-table-column label="处理状态" width="120">
          <template #default="{ row }">
            <span :class="uploadDataStatus[row.status]?.showClass">{{
              uploadDataStatus[row.status]?.showLabel
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="archivesId"
          label="关联的档案号"
        ></el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <Auth value="data:view">
              <template v-if="[6].includes(row.type)">
                <Auth value="data:upload:visitRecord">
                  <el-button
                    type="primary"
                    link
                    @click="
                      router.push({
                        path: `/data/checkData`,
                        query: {
                          sn: row.sn
                        }
                      })
                    "
                    >查看数据</el-button
                  >
                </Auth>
              </template>
              <el-button
                v-else
                type="primary"
                link
                @click="
                  router.push({
                    path: `/data/checkData`,
                    query: {
                      sn: row.sn
                    }
                  })
                "
                >查看数据</el-button
              >
            </Auth>
            <Auth value="data:edit">
              <el-button type="primary" link @click="updateArchives(row)"
                >修改关联档案</el-button
              >
            </Auth>
            <!-- <Auth value="data:view">
              <el-button
                type="primary"
                link
                @click="showDownloadReportDialog(row)"
                >分析报告</el-button
              >
            </Auth> -->
            <el-button
              :type="row.isAbandon != 1 ? 'danger' : 'warning'"
              link
              @click="abandonData(row)"
              >{{ row.isAbandon == 1 ? "取消作废" : "作废数据" }}</el-button
            >
          </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>
    <UploadDataDialog v-model:visible="uploadDialogVisible" />
    <el-dialog v-model="updateArchivesVisible" title="修改关联档案">
      <el-form>
        <el-form-item label="数据批次号">
          <span>{{ updateArchivesRow.sn }}</span>
        </el-form-item>
        <el-form-item label="关联的档案">
          <div>
            <SearchArchivesSelect
              v-model="updateArchivesRow.archivesId"
              @change="archivesSelectChange"
            />
            <div class="mt-2">
              <el-alert
                v-if="!archivesBalanceFlag"
                title="该用户余额不足，无法关联"
                type="warning"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          :disabled="!archivesBalanceFlag"
          @click="saveUpdateArchive"
          >保存</el-button
        >
      </template>
    </el-dialog>

    <el-dialog v-model="downloadReportDialog.visible" title="下载分析报告">
      <div
        v-for="(item, index) in downloadReportDialog.pdfResultList"
        :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?.pdfTemplate.isMember" size="small" class="mr-2"
              >用户使用</el-tag
            >
            <span>{{ item?.pdfTemplate?.template?.name }}</span>
          </div>
          <span class="text-xs text-gray-500"
            >最近生成时间: {{ item?.pdfTransferEndTime || "暂无" }}</span
          >
        </div>
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <img src="@/assets/pdf.png" />
            <span
              >{{
                downloadReportDialog.row?.files[0]?.fileName
                  .split(".")
                  .slice(0, -1)
                  .join("")
              }}.pdf</span
            >
          </div>
          <div>
            <el-button
              type="primary"
              plain
              tag="a"
              target="_blank"
              :href="item?.pdfTransferResultUrl"
              >在线预览</el-button
            >
            <el-button
              type="primary"
              @click="
                downloadReportRename(
                  item?.pdfTransferResultUrl +
                    '?response-content-type=application/octet-stream',
                  `${downloadReportDialog.row?.files[0]?.fileName
                    .split('.')
                    .slice(0, -1)
                    .join('')}.pdf`
                )
              "
              >下载报告</el-button
            >
          </div>
        </div>
      </div>
      <el-empty v-if="!downloadReportDialog.pdfResultList.length"></el-empty>
      <!-- <div>
        <span>报告最近生成时间：{{ downloadReportDialog.row.pdfTransferEndTime || '暂无' }}</span>
        <el-button type="primary" class="ml-4" @click="generatePdf">生成/更新报告</el-button>
      </div>
      <div class="flex justify-center items-center flex-col pt-12">
        <div v-if="downloadReportDialog.row.pdfTransferStatus == 2" class="flex items-center">
          <img src="@/assets/pdf.png" />
          <span class="text-gray-500">正在生成中...</span>
          <el-button type="primary" class="ml-4" @click="refreshDetail">刷新</el-button>
        </div>
        <div v-if="downloadReportDialog.row.pdfTransferStatus == 3" class="flex items-center">
          <img src="@/assets/pdf.png" />
          <span>{{ downloadReportDialog.row.sn }}{{ downloadReportDialog.row.archivesId }}.pdf</span>
        </div>
        <div v-if="downloadReportDialog.row.pdfTransferResultUrl" class="flex justify-around items-center space-x-4 mt-12">
          <el-button type="primary" plain  tag="a" target="_blank" :href="downloadReportDialog.row.pdfTransferResultUrl">在线预览</el-button>
          <el-button type="primary" tag="a" target="_blank" :href="downloadReportDialog.row.pdfTransferResultUrl + '?response-content-type=application/octet-stream'" :download="`${downloadReportDialog.row.sn}${downloadReportDialog.row.archivesId}.pdf`">下载报告</el-button>
        </div>
      </div> -->
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, provide, shallowRef } from "vue";
import { useRoute, useRouter, onBeforeRouteLeave } from "vue-router";
import UploadDataDialog from "./components/UploadDataDialog.vue";
import SearchArchivesSelect from "@/components/Archives/SearchArchivesSelect.vue";
import {
  uploadDataType,
  uploadDataPermissionType,
  uploadDataStatus,
  uploadDataStatusList,
  uploadDataAbandon
} from "@/enums/archives";
import { request, downloadReportRename, disabledDate } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

const router = useRouter();
const filter = ref({
  page: 1,
  pageSize: 10,
  type: 0,
  statusList: "0",
  archivesId: "",
  startTime: dayjs().subtract(180, "day").format("YYYY-MM-DD"),
  endTime: dayjs().format("YYYY-MM-DD"),
  isAbandon: 2,
  sn: ""
});
const filterDate = ref([
  dayjs().subtract(180, "day").format("YYYY-MM-DD"),
  dayjs().format("YYYY-MM-DD")
]);
const dateClear = v => {
  if (!v) {
    filter.value.startTime = "";
    filter.value.endTime = "";
  }
};
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  },
  {
    text: "最近半年",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
      return [start, end];
    }
  }
];
const filterSnType = ref("sn");

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

const uploadDialogVisible = ref(false);

const list = ref([]);
const count = ref(0);
const getList = async () => {
  const { data } = await request.get(`/medicalData/paginate`, {
    params: filter.value
  });
  list.value = data.list;
  count.value = data.total;
};
provide("getList", getList);

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

const getPdfResultList = async row => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/pdfResult/list`,
    {
      params: { sn: row.sn }
    }
  );
  downloadReportDialog.pdfResultList = data.list || [];
};
const showDownloadReportDialog = row => {
  downloadReportDialog.row = { ...row };
  getPdfResultList(row);
  downloadReportDialog.visible = true;
};
// const generatePdf = async () => {
//   await request.post(`/medicalData/pdfReport/generate`, {
//     sn: downloadReportDialog.row.sn
//   })
//   ElMessage.info('开始生成,请耐心等待...')
//   downloadReportDialog.row.pdfTransferStatus = 2
//   downloadReportDialog.row.pdfTransferResultUrl = ''
//   downloadReportDialog.timer && clearTimeout(downloadReportDialog.timer)
//   downloadReportDialog.timer = setTimeout(refreshDetail, 2e3)
// }
// const refreshDetail = async () => {
//   const { data } = await request.get(`/medicalData/detail`, {
//     params: {
//       sn: downloadReportDialog.row.sn
//     }
//   })
//   downloadReportDialog.row = data.detail
//   if (!data.detail.pdfTransferResultUrl) {
//     downloadReportDialog.timer && clearTimeout(downloadReportDialog.timer)
//     downloadReportDialog.timer = setTimeout(refreshDetail, 2e3)
//   }
// }

const checkBalance = async archiveId => {
  const { data } = await request.get(
    `/walletService/mechanism/membershipCard/archive`,
    {
      params: {
        archiveId,
        walletTypeId: 1
      }
    }
  );
  if (!data.uploadReport) return false
  if (data.uploadReportTimes == -1) return true;
  return data.uploadReportTimes - data.uploadReportUsed > 0;
};
const updateArchivesRowOriginId = ref();
const updateArchivesRow = ref();
const updateArchivesVisible = ref(false);
const updateArchives = async row => {
  console.log(row);
  updateArchivesRowOriginId.value = row.archivesId;
  updateArchivesRow.value = { ...row };
  updateArchivesVisible.value = true;
};
const archivesBalanceFlag = ref(true);
const archivesSelectChange = async (archivesId, archives) => {
  console.log(archives);
  archivesBalanceFlag.value = true;
  if (
    updateArchivesRowOriginId.value &&
    archivesId == updateArchivesRowOriginId.value
  ) {
    return;
  }
  if (
    archives.familyIds &&
    archives.familyIds.includes(updateArchivesRowOriginId.value)
  ) {
    return;
  }
  archivesBalanceFlag.value = await checkBalance(
    archives.mainArchivesId || archives.id
  );
};
const saveUpdateArchive = async () => {
  await request.post(`/medicalData/update/archives`, {
    sn: updateArchivesRow.value.sn,
    archivesId: updateArchivesRow.value.archivesId
  });
  ElMessage.success("操作成功");
  getList();
  updateArchivesVisible.value = false;
};
const permissions = shallowRef([]);
const getPermissions = async () => {
  const { data } = await request.get(`/mechanismService/mechanism/profile`);
  permissions.value = data.profile?.permissions || [];
};
onBeforeRouteLeave(() => {
  sessionStorage.setItem("dataManageFilter", JSON.stringify(filter.value));
});
onMounted(() => {
  let sFilter = sessionStorage.getItem("dataManageFilter");
  if (sFilter) {
    filter.value = JSON.parse(sFilter);
    sessionStorage.removeItem("dataManageFilter");
  }

  const teamReportDataSourceFilter = sessionStorage.getItem(
    "tempReportDataSource"
  );
  if (teamReportDataSourceFilter) {
    filter.value = {
      ...filter.value,
      ...JSON.parse(teamReportDataSourceFilter)
    };
    filterDate.value = [filter.value.startTime, filter.value.endTime];
    sessionStorage.removeItem("tempReportDataSource");
  }
  getList();
  getPermissions();
});
const abandonData = row => {
  ElMessageBox.confirm(
    `确认${row.isAbandon == 1 ? "取消" : ""}作废该条数据吗？`,
    "提示"
  ).then(async () => {
    await request.post(
      `/medicalData/abandon${row.isAbandon == 1 ? "/cancel" : ""}`,
      { sn: row.sn }
    );
    ElMessage.success("删除成功");
    getList();
  });
};
</script>

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