<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
        :style="{ width: '260px' }"
        @change="semesterChange"
      />
      <SelectExam
        v-model="searchModel.examId"
        :semester-id="searchModel.semesterId"
        :clearable="false"
        select-default
        placeholder="请选择"
        prefix
        :style="{ width: '260px' }"
        @default-selected="toPage(1)"
        @change="examChange"
      />
      <SelectCourse
        v-model="searchModel.courseId"
        :semester-id="searchModel.semesterId"
        :exam-id="searchModel.examId"
        placeholder="请选择"
        prefix
        clearable
        :style="{ width: '260px' }"
        @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" :disabled="loading" @click="toBatchDownload">
        <template #icon>
          <svg-icon name="icon-import" />
        </template>
        批量下载
      </a-button>
      <a-button type="text" :disabled="loading" @click="toSet">
        <template #icon>
          <svg-icon name="icon-system" />
        </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"
          :disabled="loading"
          @click="toDownload(record)"
          >下载</a-button
        >
        <a-button
          type="text"
          class="btn-primary"
          :disabled="loading"
          @click="toDetail(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"
  />
  <!-- IndexDetail -->
  <IndexDetail
    ref="indexDetailRef"
    :row-data="curRow"
    @download-by-students="toDownloadByStudents"
    @download-by-filter="toDownloadByFilter"
  />
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } 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,
    TrackExportDetailItem,
    TrackExportDetailListFilter,
  } 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 { modalConfirm } from '../../../utils/arco';

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

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

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

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

  const curRow = ref({} as TrackExportItem);

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

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

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

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

  const {
    trackTaskId,
    createTrackTask,
    updateTrackTaskReady,
    getTrackExportDetailList,
    getTrackExportList,
    createTrackTaskDetailsFromStudents,
  } = 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;
    }

    const continueRun = await confirmUnfinishTaskContinue();
    if (continueRun) 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,
      trackConfig: JSON.stringify(appStore.trackConfig),
      filterData: '',
      status: 0,
      courseId: '',
    }).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();
  }

  // 单个课程下载
  function toDownload(row: TrackExportItem) {
    toDownloadByFilter(row, {
      examId: row.examId,
      paperNumber: row.paperNumber,
    });
  }

  // 设置筛选条件下载
  async function toDownloadByFilter(
    row: TrackExportItem,
    filterData: TrackExportDetailListFilter
  ) {
    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,
      courseId: '',
      paperNumber: row.paperNumber,
      schoolId: userStore.curSchoolInfo.id,
      trackConfig: JSON.stringify(appStore.trackConfig),
      filterData: JSON.stringify(filterData),
      status: 0,
    }).catch(() => {
      result = false;
      setLoading(false);
    });
    if (!result) {
      Message.error('创建任务错误！');
      return;
    }

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

    // 开始构建任务
    let tRes = true;
    await getTrackExportDetailList(filterData).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 toDownloadByStudents(
    row: TrackExportItem,
    students: TrackExportDetailItem[]
  ) {
    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,
      courseId: '',
      paperNumber: row.paperNumber,
      schoolId: userStore.curSchoolInfo.id,
      trackConfig: JSON.stringify(appStore.trackConfig),
      filterData: JSON.stringify(
        students.map((item) => `${item.studentName}(${item.studentCode})`)
      ),
      status: 0,
    }).catch(() => {
      result = false;
      setLoading(false);
    });
    if (!result) {
      Message.error('创建任务错误！');
      return;
    }

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

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

    await updateTrackTaskReady();
    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 });
    }

    await confirmUnfinishTaskContinue();
  }

  // 判断是否继续进行未完成任务
  async function confirmUnfinishTaskContinue() {
    const unfinishTask = await window.db.getUnfinishTrackTask(
      userStore.curSchoolInfo.id
    );
    if (!unfinishTask) return false;

    const confirmRes = await modalConfirm(
      '提示',
      `存在未完成的下载任务，是否继续？`
    ).catch(() => false);
    if (confirmRes === 'confirm') {
      taskProgressRef.value?.open();
      return true;
    }

    await window.db.finishAllUnfinishTask(userStore.curSchoolInfo.id);
    return false;
  }

  // 详情
  const indexDetailRef = ref();
  function toDetail(row: TrackExportItem) {
    curRow.value = row;
    indexDetailRef.value?.open();
  }

  onMounted(() => {
    initData();
  });
</script>
