<template>
  <a-modal
    v-model:open="visible"
    :width="320"
    :closable="false"
    :footer="null"
    :keyboard="false"
    :mask-closable="false"
  >
    <template #title> {{ task.name }}进度 </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 { asyncTaskProgress } 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: "TaskProgressDialog",
});

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

interface PromiseFunc {
  (): Promise<void>;
}

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

const curProgress = ref(0);

const tips = computed(() => {
  if (curProgress.value < 100) {
    return `${props.task.name}中……`;
  }

  if (props.downloadHandle) {
    return `文件生成完毕，正在下载……`;
  }

  return `任务执行成功！`;
});

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

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

  // 文件生成成功，开始下载
  if (result.status === "SUCCESS") {
    stop();
    if (props.downloadHandle) {
      await props.downloadHandle();
    }

    delayClose();
  }
}

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>
