<template>
  <div class="part-box is-filter">
    <a-space class="filter-line" :size="12" wrap>
      <SelectSemester
        v-model="searchModel.semesterId"
        :clearable="false"
        select-default
        placeholder="请选择"
        prefix
        @change="semesterChange"
      />
      <SelectExam
        v-model="searchModel.examId"
        :semester-id="searchModel.semesterId"
        :clearable="false"
        select-default
        placeholder="请选择"
        prefix
        @default-selected="toPage(1)"
        @change="examChange"
      />
      <SelectCourse
        v-model="searchModel.courseId"
        :semester-id="searchModel.semesterId"
        :exam-id="searchModel.examId"
        placeholder="请选择"
        prefix
        @change="courseChange"
      />
      <a-button type="primary" @click="toPage(1)">查询</a-button>
    </a-space>
  </div>
  <div class="part-box">
    <a-space class="part-action" :size="6">
      <a-button type="text" @click="toBatchDownload">
        <template #icon>
          <svg-icon name="icon-import" />
        </template>
        批量下载
      </a-button>
      <a-button type="text" @click="toSet">
        <template #icon>
          <svg-icon name="icon-add" />
        </template>
        下载设置
      </a-button>
    </a-space>
    <a-table
      class="page-table"
      :columns="columns"
      :data="dataList"
      :pagination="pagination"
      :scroll="{ x: 600 }"
      :bordered="false"
    >
      <template #courseCode="{ record }">
        {{ courseNameCodeFilter(record) }}
      </template>
      <template #action="{ record }">
        <a-button type="text" class="btn-primary" @click="toDownload(record)"
          >下载</a-button
        >
      </template>
    </a-table>
  </div>

  <!-- ModifySet -->
  <ModifySet ref="modifySetRef" />
  <TaskProgress ref="taskProgressRef" />

  <!-- data loading tips -->
  <TaskDetailBuildProgess
    ref="taskDetailBuildProgessRef"
    :task-id="trackTaskId"
    :task-stop="detailBuildStop"
  />
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';

  import useTable from '@/hooks/table';
  import useLoading from '@/hooks/loading';

  import { courseNameCodeFilter } from '@/utils/filter';
  import { CourseItem, TrackExportItem } from '@/api/types/task';
  import { trackExportListPage } from '@/api/task';
  import { TrackConfigType } from '@/store/modules/app/types';
  import { useAppStore, useUserStore } from '@/store';
  import { OptionListItem } from '@/types/global';
  import useTask from './useTask';

  import TaskDetailBuildProgess from './taskDetailBuildProgess.vue';
  import ModifySet from './modifySet.vue';
  import TaskProgress from './taskProgress.vue';

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

  const appStore = useAppStore();
  const userStore = useUserStore();

  const searchModel = reactive({
    semesterId: '',
    examId: '',
    courseId: '',
  });

  const columns: TableColumnData[] = [
    {
      title: '课程（代码）',
      slotName: 'courseCode',
    },
    {
      title: '试卷编号',
      dataIndex: 'paperNumber',
    },
    {
      title: '参考人数',
      dataIndex: 'studentCount',
      width: 100,
    },
    {
      title: '操作',
      slotName: 'action',
      width: 80,
      fixed: 'right',
      cellClass: 'action-column',
    },
  ];
  const { dataList, pagination, toPage } = useTable<TrackExportItem>(
    trackExportListPage,
    searchModel,
    false
  );

  const seNames = {
    semesterName: '',
    examName: '',
    courseName: '',
    courseCode: '',
  };

  function semesterChange(val: OptionListItem) {
    seNames.semesterName = val.label;
    seNames.examName = '';
    seNames.courseName = '';
    seNames.courseCode = '';
  }
  function examChange(val: OptionListItem) {
    seNames.examName = val.label;
    seNames.courseName = '';
    seNames.courseCode = '';
  }
  function courseChange(val: CourseItem) {
    seNames.courseName = val.name;
    seNames.courseCode = val.code;
  }

  // table action
  const modifySetRef = ref();
  function toSet() {
    modifySetRef.value?.open();
  }

  const {
    trackTaskId,
    createTrackTask,
    updateTrackTaskReady,
    getTrackExportDetailList,
    getTrackExportList,
  } = useTask();
  const taskProgressRef = ref();
  const taskDetailBuildProgessRef = ref();
  const detailBuildStop = ref(false);

  function checkTrackConfigExist() {
    return Boolean(
      appStore.trackConfig.outputDir && appStore.trackConfig.pictureType.length
    );
  }

  // 下载前的检查
  async function downloadCheck() {
    if (!checkTrackConfigExist()) {
      Message.error('请先编辑下载设置');
      return false;
    }

    if (!appStore.trackConfig.outputDirIsDefault) {
      const result = await window.electron.dialogSelectFile({
        title: '选择保存目录',
        properties: ['openDirectory'],
      });

      if (result.canceled) return false;

      appStore.setInfo({
        trackConfig: {
          ...appStore.trackConfig,
          curOutputDir: result.filePaths[0],
        },
      });
    }

    return true;
  }
  const { loading, setLoading } = useLoading();
  // 批量下载
  async function toBatchDownload() {
    detailBuildStop.value = false;
    if (loading.value) return;

    const res = await downloadCheck();
    if (!res) return;

    setLoading(true);
    let result = true;
    await createTrackTask({
      ...searchModel,
      ...seNames,
      paperNumber: null,
      schoolId: userStore.curSchoolInfo.id,
      pictureType: appStore.trackConfig.pictureType.join(),
      outputDir: appStore.trackConfig.curOutputDir,
      status: 0,
    }).catch(() => {
      result = false;
      setLoading(false);
    });
    if (!result) {
      Message.error('创建任务错误！');
      return;
    }

    // 构建任务提示
    taskDetailBuildProgessRef.value?.open();

    // 开始构建任务
    let tRes = true;
    await getTrackExportList(searchModel).catch((error) => {
      console.log(error);
      tRes = false;
    });
    setLoading(false);

    if (!tRes) {
      detailBuildStop.value = true;
      Message.error('创建任务详情错误！');
      return;
    }

    await updateTrackTaskReady();
    detailBuildStop.value = true;
    // taskProgressRef.value?.open();
  }

  // 单个课程下载
  async function toDownload(row: TrackExportItem) {
    detailBuildStop.value = false;
    if (loading.value) return;

    const res = await downloadCheck();
    if (!res) return;

    setLoading(true);
    let result = true;
    await createTrackTask({
      ...searchModel,
      ...seNames,
      courseCode: row.courseCode,
      courseName: row.courseName,
      paperNumber: row.paperNumber,
      schoolId: userStore.curSchoolInfo.id,
      pictureType: appStore.trackConfig.pictureType.join(),
      outputDir: appStore.trackConfig.curOutputDir,
      status: 0,
    }).catch(() => {
      result = false;
      setLoading(false);
    });
    if (!result) {
      Message.error('创建任务错误！');
      return;
    }

    // 构建任务提示
    taskDetailBuildProgessRef.value?.open();

    // 开始构建任务
    let tRes = true;
    await getTrackExportDetailList(row).catch((error) => {
      console.log(error);
      tRes = false;
    });
    setLoading(false);

    if (!tRes) {
      Message.error('创建任务详情错误！');
      return;
    }

    await updateTrackTaskReady();
    detailBuildStop.value = true;
    taskProgressRef.value?.open();
  }

  async function initData() {
    const res = await window.db.getDict('trackConfig');
    if (res) {
      const trackConfig = JSON.parse(res) as TrackConfigType;
      appStore.setInfo({ trackConfig });
    }
  }
  initData();
</script>
