<template>
  <div class="part-box is-filter">
    <el-form inline>
      <el-form-item label="科目">
        <select-subject v-model="searchModel.subjectCode"></select-subject>
      </el-form-item>
      <el-form-item label="分组">
        <el-select
          v-model="searchModel.groupNumber"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="请选择" value="" />
          <!-- TODO: 添加分组选项 -->
        </el-select>
      </el-form-item>
      <el-form-item label="问题">
        <Select-data v-model="searchModel.problemId" type="problemType">
        </Select-data>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="searchModel.status"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="(label, value) in ISSUE_PAPER_STATUS"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="密号">
        <el-input
          v-model="searchModel.secretNumber"
          placeholder="请输入密号"
          clearable
          style="width: 120px"
        />
      </el-form-item>
    </el-form>
    <el-divider class="form-divider" />

    <div class="part-action">
      <el-space wrap>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
        <el-button :disabled="selectedRows.length === 0" @click="batchReset">
          批量重置
        </el-button>
        <el-button @click="onExport">导出</el-button>
      </el-space>
    </div>
  </div>
  <div class="part-box">
    <el-table
      ref="tableRef"
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="subjectName" label="科目" min-width="120" />
      <el-table-column prop="groupNumber" label="分组序号" min-width="100" />
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          <el-tag>
            {{ dictFilter.issuePaperStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="examNumber" label="准考证号" min-width="120" />
      <el-table-column prop="secretNumber" label="密号" min-width="100" />
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="markLogin" label="评卷员" min-width="100" />
      <el-table-column prop="markTime" label="提交时间" min-width="150" />
      <el-table-column prop="problemType" label="问题类型" min-width="120" />
      <el-table-column prop="problemUserName" label="处理人" min-width="100" />
      <el-table-column
        prop="problemRestTime"
        label="处理时间"
        min-width="150"
      />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            size="small"
            @click="viewDetail(scope.row)"
          >
            试卷详情
          </el-button>
          <el-button
            type="primary"
            link
            size="small"
            @click="resetSingle(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>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { ElTable, ElMessage } from 'element-plus';
  import { getIssuePaperList, resetIssuePaper } from '@/api/issue-paper';
  import {
    IssuePaperItem,
    IssuePaperListFilter,
  } from '@/api/types/issue-paper';
  import useTable from '@/hooks/table';
  import { modalConfirm } from '@/utils/ui';
  import { ISSUE_PAPER_STATUS } from '@/constants/enumerate';
  import { dictFilter } from '@/utils/filter';
  import { downloadExport } from '@/utils/download-export';

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

  const tableRef = ref<InstanceType<typeof ElTable>>();

  const searchModel = reactive<IssuePaperListFilter>({
    subjectCode: null,
    groupNumber: undefined,
    problemId: undefined,
    status: undefined,
    secretNumber: '',
  });

  const {
    dataList,
    pagination,
    loading,
    selectedRows,
    toPage,
    pageSizeChange,
    handleSelectionChange,
  } = useTable<IssuePaperItem>(getIssuePaperList, searchModel, false);

  async function batchReset() {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请选择要重置的数据');
      return;
    }

    const confirm = await modalConfirm(
      `确定要重置选中的 ${selectedRows.value.length} 条数据吗？`,
      '批量重置确认'
    ).catch(() => false);
    if (!confirm) return;

    try {
      // 调用批量重置接口
      const ids = selectedRows.value.map((row) => row.id);
      await resetIssuePaper(ids);
      ElMessage.success('批量重置成功');

      // 清空选择
      tableRef.value?.clearSelection();
      // 刷新数据
      toPage(pagination.pageNumber);
    } catch (error) {
      console.log(error);
    }
  }

  async function resetSingle(row: IssuePaperItem) {
    const confirm = await modalConfirm(
      `确定要重置「${row.name}」的问题卷吗？`,
      '重置确认'
    ).catch(() => false);
    if (!confirm) return;

    try {
      // 调用单个重置接口
      await resetIssuePaper([row.id]);
      ElMessage.success('重置成功');

      // 刷新数据
      toPage(pagination.pageNumber);
    } catch (error) {
      console.log(error);
    }
  }

  async function onExport() {
    await downloadExport('exportIssuePaper', searchModel);
  }

  function viewDetail(row: IssuePaperItem) {
    // TODO: 实现查看详情功能
    console.log('查看问题卷详情', row);
  }
</script>
