<template>
  <el-dialog
    custom-class="task-progress-dialog"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="300px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    @open="openHandle"
    @close="closeHandle"
  >
    <div class="progress-body">
      <p>{{ tips }}</p>
      <el-progress :percentage="curProgress"></el-progress>
    </div>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import useLoop from "../plugins/useLoop";
import { asyncTaskProgressApi } from "../modules/question/api";

export default {
  name: "TaskProgressDialog",
  props: {
    task: {
      type: Object,
      default() {
        return {
          id: "",
          name: "",
        };
      },
    },
    downloadHandle: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      modalIsShow: false,
      curProgress: 0,
      startLoop: null,
      stopLoop: null,
    };
  },
  computed: {
    title() {
      return `${this.task.name}进度`;
    },
    tips() {
      if (this.curProgress < 100) {
        return `${this.task.name}中……`;
      }

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

      return `任务执行成功！`;
    },
  },
  mounted() {
    const { start, stop } = useLoop(this.getProgress, 1000);
    this.startLoop = start;
    this.stopLoop = stop;
  },
  methods: {
    openHandle() {
      this.curProgress = 0;

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

      this.startLoop();
    },
    closeHandle() {
      this.stopLoop();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    delayClose() {
      setTimeout(() => {
        this.modalIsShow = false;
      }, 500);
    },
    async getProgress() {
      const res = await asyncTaskProgressApi(this.task.id).catch(() => {});
      const result = res?.data;

      if (!result) {
        this.stopLoop();
        this.delayClose();
        return;
      }
      if (result.status === "FAILED") {
        this.$message.error(result.errMsg);
        this.stopLoop();
        this.delayClose();
        return;
      }
      this.curProgress = Math.ceil(Number(result.progress || 0));

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

        this.$emit("finished");
        this.delayClose();
      }
    },
  },
};
</script>
