<template>
  <div class="review-action">
    <div class="review-tabs">
      <div
        :class="[
          'review-tab',
          { 'is-active': reviewStore.tabKey === 'review' },
        ]"
        @click="switchTab('review')"
      >
        复核校验
      </div>
      <div
        :class="[
          'review-tab',
          { 'is-active': reviewStore.tabKey === 'history' },
        ]"
        @click="switchTab('history')"
      >
        历史记录
      </div>
    </div>

    <div v-show="reviewStore.tabKey === 'review'" class="review-tbody">
      <a-collapse v-model:activeKey="reviewKey" :bordered="false">
        <a-collapse-panel key="1">
          <template #header><FilterFilled />搜索条件 </template>
          <span>科目：</span>
          <a-select
            v-model:value="searchCourseCode"
            placeholder="请选择科目"
            :options="courses"
            :field-names="fieldNames"
            filter-option
            style="width: 140px"
          ></a-select>
          <a-button class="m-l-8px" type="primary" @click="onSearch"
            >搜索</a-button
          >
        </a-collapse-panel>
        <a-collapse-panel key="2">
          <template #header><WarningFilled />导出异常 </template>

          <span>科目：</span>
          <a-select
            v-model:value="exportCourseCode"
            placeholder="请选择科目"
            :options="courses"
            :field-names="fieldNames"
            filter-option
            style="width: 140px"
          ></a-select>
          <a-button class="m-l-8px" :disabled="downloading" @click="onExport">
            导出
          </a-button>
        </a-collapse-panel>
        <a-collapse-panel key="3">
          <template #header><PushpinFilled />复核标记 </template>

          <a-radio-group v-model:value="result" @change="onMark">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="0">异常</a-radio>
          </a-radio-group>
        </a-collapse-panel>
        <a-collapse-panel key="4">
          <template #header><RightSquareFilled />重置 </template>

          <span>科目：</span>
          <a-select
            v-model:value="resetCourseCode"
            placeholder="请选择科目"
            :options="courses"
            :field-names="fieldNames"
            filter-option
            style="width: 140px"
          ></a-select>
          <a-button class="m-l-8px" type="primary" danger @click="onReset"
            >重置</a-button
          >
        </a-collapse-panel>
      </a-collapse>
    </div>
    <div
      v-show="reviewStore.tabKey === 'history'"
      class="review-tbody tbody-history"
    >
      <a-collapse :activeKey="['1']" :bordered="false">
        <a-collapse-panel key="1">
          <template #header><PushpinFilled />复核标记 </template>

          <a-radio-group v-model:value="historyResult" @change="onMark">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="0">异常</a-radio>
          </a-radio-group>
        </a-collapse-panel>
      </a-collapse>
      <div class="history-list">
        <table class="table">
          <colgroup>
            <col />
            <col width="80" />
          </colgroup>
          <thead>
            <tr>
              <th>准考证号</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(item, index) in dataList"
              :key="item.id"
              :class="{ 'is-active': reviewStore.curTask?.id === item.id }"
              @click="setCurTask(index)"
            >
              <td>{{ item.examNumber }}</td>
              <td :class="item.markStatus ? 'color-success' : 'color-error'">
                {{ item.markStatus ? "正常" : "异常" }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="history-footer">
        <SimplePagination
          :total="pagination.total"
          :page-size="pagination.pageSize"
          @change="toPage"
        />
      </div>
    </div>
  </div>

  <!-- ExportTypeDialog -->
  <ExportTypeDialog ref="exportTypeDialogRef" @confirm="onExportConfirm" />
</template>

<script setup lang="ts">
import { ref } from "vue";
import { subjectList } from "@/ap/base";
import {
  FilterFilled,
  WarningFilled,
  RightSquareFilled,
  PushpinFilled,
} from "@ant-design/icons-vue";
import { showConfirm } from "@/utils/uiUtils";

import { reviewWarningTaskExport, reviewTaskHistory } from "@/ap/review";
import { ReviewTaskListItem } from "@/ap/types/review";
import { SubjectItem } from "@/ap/types/base";

import { downloadByApi } from "@/utils/download";
import useTable from "@/hooks/useTable";
import useLoading from "@/hooks/useLoading";
import { useUserStore, useReviewStore } from "@/store";

import SimplePagination from "@/components/SimplePagination/index.vue";
import ExportTypeDialog from "./ExportTypeDialog.vue";

defineOptions({
  name: "ReviewAction",
});
const emit = defineEmits(["search", "reset", "mark"]);

const userStore = useUserStore();
const reviewStore = useReviewStore();

const fieldNames = { label: "subjectName", value: "subjectCode" };

// tab
const reviewKey = ref(["1", "2", "3", "4"]);

async function switchTab(key: "review" | "history") {
  reviewStore.setInfo({ tabKey: key });

  if (key === "history") {
    await toPage(1);
    setCurTask(0);
  }
}

// course data
const courses = ref<SubjectItem[]>([]);
async function getCourses() {
  const res = await subjectList({ examId: userStore.curExam.id });
  courses.value = res || [];
}

const searchCourseCode = ref("");
const exportCourseCode = ref("");
const resetCourseCode = ref("");
const result = ref(1);
const historyResult = ref(1);

// history
const curHistoryTaskIndex = ref(0);
const { dataList, pagination, loading, getList, toPage, setPageSize } =
  useTable<ReviewTaskListItem>(
    reviewTaskHistory,
    { examId: userStore.curExam.id },
    false
  );
setPageSize(30);

function setCurTask(index: number) {
  curHistoryTaskIndex.value = index;
  reviewStore.setInfo({ curTask: dataList.value[index] });
}

// actions
function onSearch() {
  emit("search", searchCourseCode.value);
}

function onReset() {
  let subjectData: SubjectItem | null = null;
  if (resetCourseCode.value) {
    subjectData = courses.value.find(
      (item) => item.subjectCode === resetCourseCode.value
    );
    subjectData = subjectData || null;
  }
  emit("reset", subjectData);
}

function onMark() {
  emit(
    "mark",
    reviewStore.tabKey === "review" ? result.value : historyResult.value
  );
}

// 导出
const { loading: downloading, setLoading } = useLoading();
const exportTypeDialogRef = ref();
function onExport() {
  if (downloading.value) return;
  exportTypeDialogRef.value?.open();
}
async function onExportConfirm(type: "student" | "room") {
  if (downloading.value) return;

  setLoading(true);
  const res = await downloadByApi(() =>
    reviewWarningTaskExport({
      examId: userStore.curExam.id,
      subjectCode: exportCourseCode.value,
      type,
    })
  ).catch((e: Error) => {
    message.error(e.message || "下载失败，请重新尝试！");
  });
  setLoading(false);

  if (!res) return;
  message.success("导出成功！");
}
</script>
