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

    <a-descriptions
      :data="taskInfo"
      title="任务详情"
      :align="{ label: 'right' }"
      :column="1"
    />
    <a-collapse
      v-if="taskFilterInfo.length"
      expand-icon-position="right"
      style="margin: 8px 0"
      :default-active-key="[1]"
    >
      <a-collapse-item :key="1" header="筛选条件">
        <a-descriptions
          :data="taskFilterInfo"
          title=""
          :align="{ label: 'right' }"
          :column="1"
        />
      </a-collapse-item>
    </a-collapse>

    <a-descriptions title="进度" :column="1" :align="{ label: 'right' }">
      <a-descriptions-item label="任务总数">
        {{ total }}
      </a-descriptions-item>
      <a-descriptions-item label="完成数量">
        {{ finishCount }}
      </a-descriptions-item>
      <a-descriptions-item label="总体进度">
        <a-progress :percent="progressNum" :stroke-width="10" />
      </a-descriptions-item>
    </a-descriptions>

    <template #footer>
      <a-button v-if="progressNum >= 1" type="primary" @click="close"
        >确定</a-button
      >
      <a-button v-else @click="toCancel">取消</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 } from '@/constants/enumerate';
  import { useUserStore } from '@/store';
  import { TrackConfigType } from '@/store/modules/app/types';
  import { TrackExportDetailListFilter } from '@/api/types/task';
  import { objTypeOf } from '@/utils/utils';

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

  type FilterDataType = TrackExportDetailListFilter | string[];

  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 taskFilterInfo = 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,
      status: 'FINISH',
    });
    progressNum.value = !total.value
      ? 0
      : Math.floor((10000 * finishCount.value) / total.value) / 10000;
    // console.log(total.value, finishCount.value, progressNum.value);

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

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

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

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

    await window.db.releaseAllRunningTaskDetail(res.id);

    task.value = res;
    const trackConfig = JSON.parse(res.trackConfig) as TrackConfigType;
    const filterData = res.filterData
      ? (JSON.parse(res.filterData) as FilterDataType)
      : null;
    updateTaskFilerInfo(filterData);

    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: trackConfig.pictureType.map((k) => PICTURE_TYPE[k]).join('，'),
          label: '下载文件',
        },
        {
          value: trackConfig.outputDir,
          label: '保存目录',
        },
      ]
    );

    total.value = await window.db.getTrackTaskDetailCount({
      trackTaskId: res.id,
    });
    if (total.value === 0) {
      await window.db.updateTrackTaskStatus({
        id: task.value.id,
        status: 'FINISH',
      });
      Message.warning('当前无可执行任务！');
      close();
      return;
    }

    updateProgress();

    // 开启导出进程
    const appConfig = window.api.getConfigData({});
    window.electron.startWinProcess(
      appConfig.downloadProcessCount,
      getExportUrl()
    );
    // window.electron.startWinProcess(2, getExportUrl());
  }

  function updateTaskFilerInfo(data: FilterDataType | null) {
    taskFilterInfo.value = [];
    if (!data) return;

    if (objTypeOf(data) === 'array') {
      taskFilterInfo.value = [
        {
          value: (data as string[]).join('，'),
          label: '选择的学生',
        },
      ];
      return;
    }

    if (Object.keys(data as TrackExportDetailListFilter).length === 2) return;

    const datas = data as Required<TrackExportDetailListFilter>;
    // 设置的详情数据
    taskFilterInfo.value = [
      {
        label: '学院',
        value: datas.college,
      },
      {
        label: '专业',
        value: datas.majorName,
      },
      {
        label: '班级',
        value: datas.className,
      },
      {
        label: '姓名',
        value: datas.studentName,
      },
      {
        label: '学号',
        value: datas.studentCode,
      },
      {
        label: '学号区间',
        value:
          datas.startStudentCode || datas.endStudentCode
            ? `${datas.startStudentCode}~${datas.endStudentCode}`
            : '',
      },
      {
        label: '成绩区间',
        value:
          datas.startScore || datas.endScore
            ? `${datas.startScore}~${datas.endScore}`
            : '',
      },
      {
        label: '客观题分区间',
        value:
          datas.objectiveStartScore || datas.objectiveEndScore
            ? `${datas.objectiveStartScore}~${datas.objectiveEndScore}`
            : '',
      },
      {
        label: '主观题分区间',
        value:
          datas.subjectiveStartScore || datas.subjectiveEndScore
            ? `${datas.subjectiveStartScore}~${datas.subjectiveEndScore}`
            : '',
      },
    ].filter((item) => item.value);
  }

  async function toCancel() {
    const confirmRes = await modalConfirm(
      '提示',
      `确定要停止正在执行的任务吗？`
    ).catch(() => false);
    if (confirmRes !== 'confirm') return;

    window.electron.stopWinProcess();
    close();
  }
</script>
