<template>
  <a-modal
    v-model:open="visible"
    :width="320"
    :closable="false"
    :footer="null"
    :keyboard="false"
    :mask-closable="false"
  >
    <template #title> 导出进度 </template>

    <p>{{ tips }}</p>
    <a-progress :percent="curProgress" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { message } from "ant-design-vue";
import { dbfExportProgress, dbfExportTaskDownload } from "@/ap/resultExport";

import useLoading from "@/hooks/useLoading";
import useModal from "@/hooks/useModal";
import useLoop from "@/hooks/useLoop";
import { downloadByUrl } from "@/utils/download";

defineOptions({
  name: "ExportTaskProgressDialog",
});

/* modal */
const { visible, open, close } = useModal();
defineExpose({ open, close });

const props = defineProps<{
  task: {
    id: string;
    name: string;
  };
}>();

const curProgress = ref(0);

const tips = computed(() => {
  return curProgress.value < 100
    ? `${props.task.name}导出中……`
    : `文件生成完毕，正在下载……`;
});

const { start, stop } = useLoop(getProgress, 1000);
async function getProgress() {
  const result = await dbfExportProgress(props.task.id).catch(() => {});
  if (!result) {
    stop();
    return;
  }
  if (!result.success) {
    message.error(result.errMsg);
    stop();
    return;
  }
  curProgress.value = result.progress;

  // 文件生成成功，开始下载
  if (result.progress >= 100) {
    stop();
    downloadTaskFile();
  }
}

async function downloadTaskFile() {
  const res = await dbfExportTaskDownload(props.task.id).catch(() => false);
  if (!res) return;
  message.success("文件下载成功！");

  setTimeout(() => {
    close();
  }, 500);
}

watch(
  () => visible.value,
  (val) => {
    if (val) {
      modalOpenHandle();
    } else {
      stop();
    }
  },
  {
    immediate: true,
  }
);

/* init modal */
function modalOpenHandle() {
  curProgress.value = 0;

  if (!props.task.id) {
    message.error("任务丢失！");
    return;
  }

  start();
}
</script>
