<template>
  <div class="part-box is-border">
    <el-form inline>
      <el-form-item label="科目">
        <select-subject v-model="searchModel.subject"></select-subject>
      </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 @click="onAdd">新增</el-button>
        <el-button @click="onDataCheck">数量校对</el-button>
        <el-button @click="onClose">关闭</el-button>
        <el-button @click="onSetTrialCount">设置试评数量</el-button>
      </el-space>
    </div>

    <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="groupNo" label="分组序号" width="100" />
      <el-table-column prop="questionNo" label="大题号" width="100" />
      <el-table-column
        prop="questionName"
        label="大题名称"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column prop="stepScore" label="步骤分" width="100" />
      <el-table-column label="包含选做题" width="120">
        <template #default="scope">
          <el-tag
            :type="scope.row.hasOptional ? 'success' : 'info'"
            size="small"
          >
            {{ scope.row.hasOptional ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="markerCount" label="评卷员人数" width="120" />
      <el-table-column prop="totalTasks" label="任务总数" width="100" />
      <el-table-column prop="completedTasks" label="完成总数" width="100" />
      <el-table-column prop="remainingTasks" label="剩余总数" width="100" />
      <el-table-column label="正在评卷" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isMarking ? 'success' : 'info'" size="small">
            {{ scope.row.isMarking ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" width="120">
        <template #default="scope">
          <el-progress
            :percentage="scope.row.progress"
            :color="scope.row.progress === 100 ? '#67c23a' : '#409eff'"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="markingAreaSetting"
        label="评卷区设置"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            link
            @click="onEdit(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>

  <SetTrialCountDialog
    ref="setTrialCountDialogRef"
    :subject-id="searchModel.subject"
  />
</template>

<script setup lang="ts">
  import { reactive, ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import {
    getMarkGroupList,
    markGroupDataCheck,
    markGroupClose,
  } from '@/api/mark';
  import { MarkGroupItem, MarkGroupListFilter } from '@/api/types/mark';
  import useTable from '@/hooks/table';
  import { modalConfirm } from '@/utils/ui';

  import SetTrialCountDialog from './components/SetTrialCountDialog.vue';

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

  const searchModel = reactive<MarkGroupListFilter>({
    subject: null,
  });

  const setTrialCountDialogRef =
    ref<InstanceType<typeof SetTrialCountDialog>>();

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

  // 计算选中的分组ID列表
  const selectedGroupIds = computed(() => {
    return selectedRows.value.map((row) => row.id);
  });

  // 新增分组
  function onAdd() {
    ElMessage.info('新增分组功能待实现');
    // TODO: 实现新增分组的逻辑
  }

  // 修改分组
  function onEdit(row: MarkGroupItem) {
    ElMessage.info(`修改分组：${row.groupNo}`);
    // TODO: 实现修改分组的逻辑，功能空着留着后面做
  }

  // 数量校对
  async function onDataCheck() {
    if (!searchModel.subject) {
      ElMessage.warning('请选择科目');
      return;
    }

    try {
      await markGroupDataCheck(searchModel.subject);
      ElMessage.success('数量校对成功');
      getList();
    } catch (error) {
      console.error('数量校对失败:', error);
    }
  }

  // 关闭分组
  async function onClose() {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择分组');
      return;
    }

    const confirm = await modalConfirm(
      `确认关闭所选的 ${selectedRows.value.length} 个分组的评卷吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      await markGroupClose(selectedGroupIds.value);
      ElMessage.success('批量关闭成功');
      getList();
    } catch (error) {
      console.error('批量关闭失败:', error);
    }
  }

  // 设置试评数量
  function onSetTrialCount() {
    setTrialCountDialogRef.value?.open();
  }
</script>
