<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-item label="分组">
        <el-input
          v-model.trim="searchModel.groupNumber"
          placeholder="请输入分组"
          clearable
          style="width: 120px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="登录名">
        <el-input
          v-model.trim="searchModel.loginName"
          placeholder="请输入登录名"
          clearable
          style="width: 150px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          v-model.trim="searchModel.name"
          placeholder="请输入姓名"
          clearable
          style="width: 120px"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model.trim="searchModel.marked">已评卷 </el-checkbox>
      </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="onImport">导入</el-button>
        <el-button @click="onBatchEnable(true)">启用</el-button>
        <el-button @click="onBatchEnable(false)">禁用</el-button>
        <el-button @click="onBatchRecycle">回收</el-button>
        <el-button @click="onBatchSetTaskCount">设置评卷数</el-button>
        <el-button @click="onBatchResetPassword">重置密码</el-button>
      </el-space>
    </div>

    <el-table
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="loginName" label="登录名" width="120" sortable />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="subjectCode" label="科目" width="120" />
      <el-table-column prop="groupNumber" label="分组" width="100" sortable />
      <el-table-column prop="statusText" label="状态" width="100">
      </el-table-column>
      <el-table-column prop="markedCount" label="已评数量" width="120" sortable>
        <template #default="scope">
          <span>
            {{ scope.row.markedCount }}
          </span>
          <el-button
            type="danger"
            size="small"
            link
            @click="onResetFinishCount(scope.row)"
            >重置</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="currentCount" label="正在评卷" width="100">
      </el-table-column>
      <el-table-column prop="topCount" label="任务数" width="100" sortable />
      <el-table-column
        prop="classCount"
        label="绑定班级"
        min-width="150"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ scope.row.classCount || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 'disabled'"
            type="primary"
            link
            @click="onEnable(scope.row, true)"
          >
            启用
          </el-button>
          <el-button
            v-if="scope.row.status === 'enabled'"
            type="danger"
            link
            @click="onEnable(scope.row, false)"
          >
            禁用
          </el-button>
          <el-button type="danger" link @click="onUnbind(scope.row)">
            解绑
          </el-button>
          <el-button type="primary" link @click="onSetTaskCount(scope.row)">
            设置评卷数
          </el-button>
          <el-button type="primary" link @click="onRecycle(scope.row)">
            回收
          </el-button>
          <el-button type="warning" link @click="onResetPassword(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>

  <SetMarkCountDialog
    ref="setMarkCountDialogRef"
    :marker-ids="curMarkerIds"
    @modified="getList"
  />

  <!-- 导入 -->
  <ImportDialog
    ref="importDialogRef"
    title="导入评卷员"
    upload-url="/api/admin/exam/marker/import"
    :upload-data="uploadData"
    :format="['xls', 'xlsx']"
    :download-handle="() => downloadExport('markerImportTemplate')"
    download-filename="评卷员导入模板.xlsx"
  />

  <!-- 授权码 -->
  <CodeConfirmDialog
    ref="codeConfirmDialogRef"
    :progress="curMarkerGroupProgress"
    @modified="onResetFinishConfirm"
  />
</template>

<script setup lang="ts">
  import { reactive, ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import {
    getMarkMarkerList,
    markMarkerEnable,
    markMarkerUnbind,
    markMarkerTaskRecycle,
    markMarkerResetPassword,
    markMarkerResetFinishCount,
  } from '@/api/mark';
  import { MarkMarkerItem, MarkMarkerListFilter } from '@/api/types/mark';
  import useTable from '@/hooks/table';
  import { modalConfirm } from '@/utils/ui';
  import { downloadExport } from '@/utils/download-export';

  import SetMarkCountDialog from './components/SetMarkCountDialog.vue';
  import CodeConfirmDialog from './components/CodeConfirmDialog.vue';

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

  const searchModel = reactive<MarkMarkerListFilter>({
    subjectCode: null,
    groupNumber: '',
    loginName: '',
    name: '',
    marked: false,
  });

  const setMarkCountDialogRef = ref<InstanceType<typeof SetMarkCountDialog>>();
  const curMarkerIds = ref<number[]>([]);
  const curMarkerGroupProgress = ref<number>(0);
  const curRow = ref<MarkMarkerItem>();
  const codeConfirmDialogRef = ref<InstanceType<typeof CodeConfirmDialog>>();

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

  // 计算选中的评卷员ID列表
  const selectedMarkerIds = computed(() => {
    return selectedRows.value.map((row) => row.id);
  });

  // 启用/禁用评卷员
  async function onEnable(row: MarkMarkerItem, enable: boolean) {
    const action = enable ? '启用' : '禁用';
    const confirm = await modalConfirm(
      `确认${action}评卷员 ${row.name}(${row.loginName}) 吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      await markMarkerEnable({ ids: [row.id], enable });
      ElMessage.success(`${action}成功`);
      getList();
    } catch (error) {
      console.error(`${action}评卷员失败:`, error);
    }
  }

  // 批量启用/禁用
  async function onBatchEnable(enable: boolean) {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择评卷员');
      return;
    }

    const action = enable ? '启用' : '禁用';
    const confirm = await modalConfirm(
      `确认${action}所选的 ${selectedRows.value.length} 个评卷员吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;
    try {
      await markMarkerEnable({ ids: selectedMarkerIds.value, enable });
      ElMessage.success(`批量${action}成功`);
      getList();
    } catch (error) {
      console.error(`批量${action}评卷员失败:`, error);
    }
  }

  // 解绑评卷员
  async function onUnbind(row: MarkMarkerItem) {
    const confirm = await modalConfirm(
      `确认解绑评卷员 ${row.name}(${row.loginName}) 吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      await markMarkerUnbind(row.id);
      ElMessage.success('解绑成功');
      getList();
    } catch (error) {
      console.error('解绑评卷员失败:', error);
    }
  }

  // 设置评卷数量
  function onSetTaskCount(row: MarkMarkerItem) {
    curMarkerIds.value = [row.id];
    setMarkCountDialogRef.value?.open();
  }

  // 批量设置评卷数量
  function onBatchSetTaskCount() {
    curMarkerIds.value = selectedMarkerIds.value;
    setMarkCountDialogRef.value?.open();
  }

  // 回收任务
  async function onRecycle(row: MarkMarkerItem) {
    const confirm = await modalConfirm(
      `确认回收评卷员 ${row.name}(${row.loginName}) 的任务吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      await markMarkerTaskRecycle([row.id]);
      ElMessage.success('回收成功');
      getList();
    } catch (error) {
      console.error('回收任务失败:', error);
    }
  }

  // 批量回收
  async function onBatchRecycle() {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择评卷员');
      return;
    }

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

    try {
      await markMarkerTaskRecycle(selectedMarkerIds.value);
      ElMessage.success('批量回收成功');
      getList();
    } catch (error) {
      console.error('批量回收任务失败:', error);
    }
  }

  // 重置密码
  async function onResetPassword(row: MarkMarkerItem) {
    const confirm = await modalConfirm(
      `确认重置评卷员 ${row.name}(${row.loginName}) 的密码吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      await markMarkerResetPassword([row.id]);
      ElMessage.success('重置密码成功');
    } catch (error) {
      console.error('重置密码失败:', error);
    }
  }

  // 批量重置密码
  async function onBatchResetPassword() {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择评卷员');
      return;
    }
    const confirm = await modalConfirm(
      `确认重置所选的 ${selectedRows.value.length} 个评卷员的密码吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      await markMarkerResetPassword(selectedMarkerIds.value);
      ElMessage.success('批量重置密码成功');
    } catch (error) {
      console.error('批量重置密码失败:', error);
    }
  }

  // 重置已评数量
  async function onResetFinishCount(row: MarkMarkerItem) {
    // TODO:获取进度
    // curMarkerGroupProgress.value = row.progress;
    curRow.value = row;
    codeConfirmDialogRef.value?.open();
  }

  async function onResetFinishConfirm(deleteCode: string) {
    try {
      await markMarkerResetFinishCount(curRow.value.id, deleteCode);
      ElMessage.success('重置已评数量成功');
      getList();
    } catch (error) {
      console.error('重置已评数量失败:', error);
    }
  }

  // 导入
  const importDialogRef = ref();
  const uploadData = computed(() => {
    return { subjectCode: searchModel.subjectCode };
  });
  const onImport = () => {
    importDialogRef.value?.open();
  };
</script>
