<template>
  <a-modal
    v-model:visible="visible"
    :width="500"
    title-align="start"
    top="10vh"
    :align-center="false"
    :mask-closable="false"
    :esc-to-close="false"
    @before-open="modalBeforeOpen"
  >
    <template #title> 任务进度 </template>

    <a-descriptions
      :data="taskInfo"
      title="任务详情"
      layout="inline-horizontal"
      :align="{ label: 'right' }"
    />

    <a-descriptions title="进度">
      <a-descriptions-item label="">
        <a-progress :percent="progressNum" :stroke-width="10" />
      </a-descriptions-item>
    </a-descriptions>

    <template #footer>
      <a-button @click="close">取消</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { DescData, Message } from '@arco-design/web-vue';
  import useModal from '@/hooks/modal';
  import useTimeout from '@/hooks/timout';
  import { PICTURE_TYPE, PictureTypeEnum } from '@/constants/enumerate';
  import { useUserStore } from '@/store';

  import { TrackTaskData } from '../../../../electron/db/models/trackTask';

  defineOptions({
    name: 'ModifySet',
  });

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

  const { addSetTimeout, clearSetTimeout } = useTimeout();
  const userStore = useUserStore();

  const PROGRESS_KEY = 'progress';

  const taskInfo = ref<DescData[]>([]);
  const task = ref<TrackTaskData>({} as TrackTaskData);
  const total = ref(0);
  const finishCount = ref(0);
  const progressNum = ref(0);

  async function updateProgress() {
    clearSetTimeout(PROGRESS_KEY);
    finishCount.value = await window.db.getTrackTaskDetailCount({
      trackTaskId: task.value?.id as number,
      status: 'FINISH',
    });
    progressNum.value = !total.value
      ? 0
      : Math.floor((10000 * finishCount.value) / total.value) / 10000;

    if (finishCount.value === total.value) {
      await window.db.updateTrackTaskStatus({
        id: task.value.id,
        status: 'FINISH',
      });
      window.electron.stopWinProcess();
      return;
    }

    addSetTimeout(PROGRESS_KEY, updateProgress, 1 * 1000);
  }

  function getExportUrl() {
    const page = '#/track-task-export';
    const user = window.btoa(JSON.stringify(userStore.userInfo));
    return `${page}?user=${user}`;
  }

  /* init modal */
  async function modalBeforeOpen() {
    const res = await window.db.getUnfinishTrackTask(
      userStore.curSchoolInfo.id
    );
    if (!res) {
      Message.warning('没有未完成任务');
      close();
      return;
    }

    task.value = res;
    taskInfo.value = [
      {
        value: res.semesterName,
        label: '学期',
      },
      {
        value: res.examName,
        label: '考试',
      },
    ];
    if (res.courseId) {
      taskInfo.value.push({
        value: `${res.courseName}(${res.courseCode})`,
        label: '科目',
      });
    }
    if (res.paperNumber) {
      taskInfo.value.push({
        value: res.paperNumber,
        label: '试卷编码',
      });
    }
    taskInfo.value.push(
      ...[
        {
          value: (res.pictureType.split(',') as PictureTypeEnum[])
            .map((k) => PICTURE_TYPE[k])
            .join('，'),
          label: '下载文件',
        },
        {
          value: res.outputDir,
          label: '保存目录',
        },
      ]
    );

    total.value = await window.db.getTrackTaskDetailCount({
      trackTaskId: res.id,
    });
    updateProgress();

    window.electron.startWinProcess(2, getExportUrl());
  }
</script>
