<template>
  <div class="part-box is-filter">
    <el-form inline>
      <el-form-item label="考试名称">
        <el-input
          v-model.trim="searchModel.name"
          placeholder="请输入"
          clearable
          style="width: 200px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-select
          v-model="searchModel.type"
          placeholder="不限"
          clearable
          style="width: 140px"
        >
          <el-option
            v-for="(val, key) in EXAM_TYPE"
            :key="key"
            :label="val"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="searchModel.status"
          placeholder="不限"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="(val, key) in EXAM_STATUS"
            :key="key"
            :label="val"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
        <el-button type="success" @click="onAdd">新建考试</el-button>
        <el-button :loading="finishLoading" @click="onFinish"
          >结束考试</el-button
        >
      </el-form-item>
    </el-form>
  </div>
  <div class="part-box">
    <el-table
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="考试名称" min-width="200">
        <template #default="scope">
          <el-button type="primary" link @click="onViewDetail(scope.row)">{{
            scope.row.name
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="140">
        <template #default="scope">
          {{ dictFilter.examType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="examTime" label="考试日期" min-width="100">
        <template #default="scope">
          {{ dateFilter(scope.row.examTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="forceSpecialTag" label="强制标记" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.forceSpecialTag ? 'primary' : 'info'">
            {{ scope.row.forceSpecialTag ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          {{ dictFilter.examStatus(scope.row.status) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="onViewDetail(scope.row)">
            详情
          </el-button>
          <el-button type="primary" link @click="onEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="primary" link @click="onEditIssueType(scope.row)">
            问题卷分类
          </el-button>
          <el-button type="primary" link @click="onEditRejectType(scope.row)">
            打回卷分类
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.pageNumber"
      v-model:page-size="pagination.pageSize"
      :layout="pagination.layout"
      :total="pagination.total"
      @size-change="pageSizeChange"
      @current-change="toPage"
    />
  </div>

  <!-- 统计信息弹窗 -->
  <ExamStatDialog ref="statDialogRef" :exam-id="currentExamId" />

  <!-- 问题卷分类管理弹窗 -->
  <IssuePaperTypeDialog ref="issueTypeDialogRef" :exam-id="currentExamId" />

  <!-- 打回卷分类管理弹窗 -->
  <RejectTypeDialog ref="rejectTypeDialogRef" :exam-id="currentExamId" />
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getExamList, finishExam } from '@/api/exam';
  import { ExamQueryItem, ExamListFilter } from '@/api/types/exam';
  import { EXAM_STATUS, EXAM_TYPE } from '@/constants/enumerate';
  import useTable from '@/hooks/table';
  import useLoading from '@/hooks/loading';
  import { dictFilter, dateFilter } from '@/utils/filter';
  import { modalConfirm } from '@/utils/ui';

  import ExamStatDialog from './components/ExamStatDialog.vue';
  import IssuePaperTypeDialog from './components/IssuePaperTypeDialog.vue';
  import RejectTypeDialog from './components/RejectTypeDialog.vue';

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

  const router = useRouter();

  const searchModel = reactive<ExamListFilter>({
    name: '',
    type: undefined,
    status: undefined,
  });

  const {
    dataList,
    pagination,
    loading,
    selectedRows,
    toPage,
    pageSizeChange,
    handleSelectionChange,
  } = useTable<ExamQueryItem>(getExamList, searchModel, true);

  // action相关
  const currentExamId = ref(0);
  // 详情统计弹窗
  const statDialogRef = ref();
  // 问题卷分类弹窗
  const issueTypeDialogRef = ref();
  // 打回卷分类弹窗
  const rejectTypeDialogRef = ref();

  function onViewDetail(row: ExamQueryItem) {
    currentExamId.value = row.id;
    statDialogRef.value?.open();
  }

  const { loading: finishLoading, setLoading: setFinishLoading } = useLoading();
  async function onFinish() {
    if (finishLoading.value) return;
    if (selectedRows.value.length === 0) {
      ElMessage.error('请先选择考试');
      return;
    }

    const confirm = await modalConfirm(
      `确定要结束所选的${selectedRows.value.length}个考试吗？`,
      '提示'
    ).catch(() => false);
    if (!confirm) return;

    setFinishLoading(true);
    try {
      await finishExam({ ids: selectedRows.value.map((item) => item.id) });
      ElMessage.success('操作成功！');
    } catch (error) {
      console.error('操作失败:', error);
    } finally {
      setFinishLoading(false);
    }
  }

  function onAdd() {
    router.push({ name: 'ExamEdit' });
  }

  function onEdit(row: ExamQueryItem) {
    router.push({
      name: 'ExamEdit',
      query: { id: row.id },
    });
  }

  function onEditIssueType(row: ExamQueryItem) {
    currentExamId.value = row.id;
    issueTypeDialogRef.value?.open();
  }

  function onEditRejectType(row: ExamQueryItem) {
    currentExamId.value = row.id;
    rejectTypeDialogRef.value?.open();
  }
</script>
