<template>
  <div class="part-box is-border">
    <el-form inline>
      <el-form-item label="科目">
        <select-subject v-model="searchModel.subjectCode"></select-subject>
      </el-form-item>
    </el-form>
    <el-divider class="form-divider" />
    <div class="part-action box-justify">
      <el-space wrap>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
        <el-button type="success" @click="onAdd">新增</el-button>
        <el-button :disabled="checkLoading" @click="onDataCheck"
          >数量校对</el-button
        >
        <el-button :disabled="closeLoading" @click="onBatchClose"
          >关闭</el-button
        >
        <el-button @click="onSetTrialCount">设置试评数量</el-button>
      </el-space>
      <div>
        <el-tooltip effect="dark" content="预览所有试卷" placement="top">
          <el-button class="is-shade">全卷预览</el-button>
        </el-tooltip>
      </div>
    </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="groupNumber" label="分组序号" width="100" />
      <el-table-column prop="mainNumber" label="大题号" width="100" />
      <el-table-column
        prop="title"
        label="大题名称"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column prop="scoreList" label="步骤分" width="100" />
      <el-table-column label="包含选做题" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.selective ? 'success' : 'info'" size="small">
            {{ scope.row.selective ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="markerCount" label="评卷员人数" width="120" />
      <el-table-column prop="libraryCount" label="任务总数" width="100" />
      <el-table-column prop="markedCount" label="完成总数" width="100" />
      <el-table-column prop="leftCount" label="剩余总数" width="100" />
      <el-table-column prop="currentCount" label="正在评卷" width="100" />
      <el-table-column label="进度" width="120">
        <template #default="scope">
          <el-progress
            :percentage="scope.row.percent"
            :color="scope.row.percent === 100 ? '#67c23a' : '#409eff'"
          />
        </template>
      </el-table-column>
      <el-table-column prop="picList" label="评卷区设置" min-width="150">
        <template #default="scope">
          <el-tag :type="scope.row.picList ? 'success' : 'info'" size="small">
            {{ scope.row.picList ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            link
            @click="onView(scope.row)"
          >
            预览
          </el-button>
          <el-button
            type="primary"
            size="small"
            link
            @click="onEdit(scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="primary"
            size="small"
            link
            :disabled="startMarkLoading"
            @click="onStartMark(scope.row)"
          >
            开始正评
          </el-button>
          <el-button
            type="danger"
            size="small"
            link
            :disabled="releaseLoading"
            @click="onRelease(scope.row)"
            >回收</el-button
          >
          <el-button
            type="danger"
            size="small"
            link
            :disabled="closeLoading"
            @click="onClose(scope.row)"
            >结束</el-button
          >
          <el-button
            type="danger"
            size="small"
            link
            :disabled="deleteLoading"
            @click="onDelete(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.subjectCode"
  />
</template>

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

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

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

  const searchModel = reactive<MarkGroupListFilter>({
    subjectCode: null,
  });
  // const curRow = ref<MarkGroupItem>();

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

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

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

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

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

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

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

  // 数量校对
  const { loading: checkLoading, setLoading: setCheckLoading } = useLoading();
  async function onDataCheck() {
    if (checkLoading.value) return;
    if (!searchModel.subjectCode) {
      ElMessage.warning('请选择科目');
      return;
    }

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

  // 批量关闭分组
  const { loading: closeLoading, setLoading: setCloseLoading } = useLoading();
  async function onBatchClose() {
    if (closeLoading.value) return;
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择分组');
      return;
    }

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

    setCloseLoading(true);
    try {
      await markGroupClose(
        searchModel.subjectCode!,
        selectedGroupNumbers.value
      );
      ElMessage.success('批量关闭成功');
      getList();
    } catch (error) {
      console.error('批量关闭失败:', error);
    } finally {
      setCloseLoading(false);
    }
  }

  // 关闭分组
  async function onClose(row: MarkGroupItem) {
    if (closeLoading.value) return;
    const confirm = await modalConfirm(
      `确认关闭分组 ${row.groupNumber} 的评卷吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    setCloseLoading(true);
    try {
      await markGroupClose(searchModel.subjectCode!, [row.groupNumber!]);
      ElMessage.success('关闭成功');
      getList();
    } catch (error) {
      console.error('关闭失败:', error);
    } finally {
      setCloseLoading(false);
    }
  }

  // 回收分组任务
  const { loading: releaseLoading, setLoading: setReleaseLoading } =
    useLoading();
  // 回收分组任务
  async function onRelease(row: MarkGroupItem) {
    if (releaseLoading.value) return;
    const confirm = await modalConfirm(
      `确认回收分组 ${row.groupNumber} 的任务吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    setReleaseLoading(true);
    try {
      await markGroupTaskRecycle({
        subjectCode: row.subjectCode!,
        number: row.groupNumber!,
      });
      ElMessage.success('回收成功');
      getList();
    } catch (error) {
      console.error('回收失败:', error);
    } finally {
      setReleaseLoading(false);
    }
  }

  // 删除
  const { loading: deleteLoading, setLoading: setDeleteLoading } = useLoading();
  async function onDelete(row: MarkGroupItem) {
    if (deleteLoading.value) return;

    setDeleteLoading(true);
    const params = {
      subjectCode: row.subjectCode!,
      number: row.groupNumber!,
    };
    let res = true;
    await markGroupDelete(params).catch(() => {
      res = false;
    });
    setDeleteLoading(false);
    if (!res) return;

    ElMessage.success(`删除成功！`);
    getList();
  }

  // 开始正评
  const { loading: startMarkLoading, setLoading: setStartMarkLoading } =
    useLoading();
  async function onStartMark(row: MarkGroupItem) {
    if (startMarkLoading.value) return;
    const confirm = await modalConfirm(
      `确认开始分组 ${row.groupNumber} 的正评吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    setStartMarkLoading(true);
    try {
      await markGroupUpdateStatus({
        subjectCode: row.subjectCode!,
        number: row.groupNumber!,
        status: 'FORMAL',
      });
      ElMessage.success('开始正评成功');
      getList();
    } catch (error) {
      console.error('开始正评失败:', error);
    } finally {
      setStartMarkLoading(false);
    }
  }
</script>
