<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.selective"
          placeholder="不限"
          clearable
          style="width: 120px"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="searchModel.inspected"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="已复核" :value="true" />
          <el-option label="未复核" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="标记卷">
        <el-select
          v-model="searchModel.marked"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="学院">
        <select-option v-model="searchModel.college" type="college">
        </select-option>
      </el-form-item>
      <el-form-item label="试卷总分">
        <el-space>
          <el-input-number
            v-model="searchModel.startScore"
            placeholder="低分"
            :min="0"
            :max="999"
            :step="0.1"
            :precision="1"
            :controls="false"
            step-strictly
            style="width: 80px"
          />
          <span>到</span>
          <el-input-number
            v-model="searchModel.endScore"
            placeholder="高分"
            :min="0"
            :max="999"
            :step="0.1"
            :precision="1"
            :controls="false"
            step-strictly
            style="width: 80px"
          />
        </el-space>
      </el-form-item>
      <el-form-item label="选做题">
        <el-select
          v-model="searchModel.selectiveStatus"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="(val, key) in OPTIONAL_EXCEPTION_TYPE"
            :key="key"
            :label="val"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="复核次数">
        <el-select
          v-model="searchModel.inspectRound"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in reviewRoundList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="复核人">
        <el-input
          v-model.trim="searchModel.inspectorName"
          placeholder=""
          clearable
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="大题">
        <el-select
          v-model="searchModel.mainNumber"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="请选择" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="大题得分">
        <el-space>
          <el-input-number
            v-model="searchModel.mainStartScore"
            placeholder="低分"
            :min="0"
            :max="999"
            :step="0.1"
            :precision="1"
            :controls="false"
            step-strictly
            style="width: 80px"
          />
          <span>到</span>
          <el-input-number
            v-model="searchModel.mainEndScore"
            placeholder="高分"
            :min="0"
            :max="999"
            :step="0.1"
            :precision="1"
            :controls="false"
            step-strictly
            style="width: 80px"
          />
        </el-space>
      </el-form-item>
      <el-form-item label="小题得分">
        <el-input-number
          v-model="searchModel.questionScore"
          placeholder=""
          :min="0"
          :max="999"
          :step="0.1"
          :precision="1"
          :controls="false"
          step-strictly
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="密号">
        <el-input
          v-model.trim="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="search">查询</el-button>
        <el-button @click="onBatchReview"
          >批量复核({{ pagination.total }})</el-button
        >
        <el-button @click="onRestartReview">再次复核</el-button>
        <el-button @click="onBatchCancelReview">取消复核</el-button>
        <el-button @click="onImport">导入</el-button>
        <el-dropdown @command="onExportCommand">
          <el-button class="is-shade">
            导出
            <el-icon class="el-icon--right"><CaretBottom /> </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="exportFullReviewList"
                >复核列表</el-dropdown-item
              >
              <el-dropdown-item command="exportReviewWorkload"
                >工作量</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-space>
    </div>
  </div>

  <div class="part-box">
    <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="subjectName"
        label="科目"
        min-width="200"
        sortable
      />
      <el-table-column prop="marked" label="标记卷" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.marked ? 'success' : 'info'">
            {{ scope.row.marked ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="secretNumber" label="密号" width="120" />
      <el-table-column label="选做异常" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.selectiveError ? 'warning' : 'success'">
            {{ scope.row.selectiveError || '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="objectiveScoreString" label="客观分" width="100" />
      <el-table-column
        prop="subjectiveScoreString"
        label="主观分"
        width="100"
      />
      <el-table-column
        prop="totalScore"
        label="试卷总分"
        width="110"
        sortable
      />
      <el-table-column
        prop="subjectiveScoreList"
        label="得分明细"
        min-width="200"
      />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="onTrackView(scope.row)">
            轨迹图
          </el-button>
          <el-button type="primary" link @click="onCancelReview(scope.row)">
            取消复核
          </el-button>
          <el-button type="primary" link @click="onReview(scope.row)">
            进入复核
          </el-button>
        </template>
      </el-table-column>
      <template v-for="item in reviewRoundList" :key="item">
        <el-table-column
          :prop="`inspectHistoryMap.additionalProperties${item}.inspectorName`"
          label="复核人"
          width="120"
          sortable
        >
          <template #default="scope">
            <span
              v-if="
                scope.row.inspectHistoryMap &&
                scope.row.inspectHistoryMap[`additionalProperties${item}`]
              "
            >
              {{
                scope.row.inspectHistoryMap?.[`additionalProperties${item}`]
                  .inspectorName
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :prop="`inspectHistoryMap.additionalProperties${item}.inspectTime`"
          label="复核时间"
          width="180"
          sortable
        >
          <template #default="scope">
            <span
              v-if="
                scope.row.inspectHistoryMap &&
                scope.row.inspectHistoryMap[`additionalProperties${item}`]
              "
            >
              {{
                scope.row.inspectHistoryMap?.[`additionalProperties${item}`]
                  .inspectTime
              }}
            </span>
          </template>
        </el-table-column>
      </template>
    </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>

  <!-- 导入 -->
  <ImportDialog
    ref="importDialogRef"
    title="导入数据"
    upload-url="/api/admin/exam/inspected/import"
    :format="['xls', 'xlsx']"
    :download-handle="() => downloadExport('reviewImportTemplate')"
    download-filename="导入模板.xlsx"
  />
</template>

<script setup lang="ts">
  import { reactive, ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { CaretBottom } from '@element-plus/icons-vue';
  import {
    getFullReviewList,
    cancelReview,
    checkReReview,
    reReview,
    getSubjectStatusInfo,
    getReviewRoundList,
  } from '@/api/review';
  import { OPTIONAL_EXCEPTION_TYPE } from '@/constants/enumerate';
  import {
    FullReviewItem,
    FullReviewListFilter,
    SubjectStatusInfo,
  } from '@/api/types/review';
  import useTable from '@/hooks/table';
  import { modalConfirm } from '@/utils/ui';
  import { downloadExport } from '@/utils/download-export';

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

  const searchModel = reactive<FullReviewListFilter>({
    subjectCode: null,
    selective: undefined,
    inspected: undefined,
    marked: undefined,
    college: undefined,
    startScore: undefined,
    endScore: undefined,
    selectiveStatus: undefined,
    inspectRound: undefined,
    inspectorName: undefined,
    mainNumber: undefined,
    mainStartScore: undefined,
    mainEndScore: undefined,
    questionScore: undefined,
    secretNumber: undefined,
  });

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

  async function search() {
    await toPage(1);
    await updateSubjectInfo();
    await updateReviewRoundList();
  }

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

  // 科目状态信息
  const curSubjectInfo = ref<SubjectStatusInfo>({
    showNextInspect: false,
    showNextInspectMsg: false,
  });
  async function updateSubjectInfo() {
    const res = await getSubjectStatusInfo(searchModel.subjectCode);
    curSubjectInfo.value = res || {
      showNextInspect: false,
      showNextInspectMsg: false,
    };
  }

  // 复核轮数信息
  const reviewRoundList = ref<number[]>([]);
  async function updateReviewRoundList() {
    const res = await getReviewRoundList(searchModel);
    reviewRoundList.value = res || [];
  }

  // 批量复核
  function onBatchReview() {
    if (selectedRows.length === 0) {
      ElMessage.warning('请选择要复核的试卷');
      return;
    }
    // TODO: 批量复核
    console.log('批量复核:', selectedRows);
  }

  // 进入复核
  function onReview(row: FullReviewItem) {
    // TODO: 进入复核
    console.log('复核:', row);
  }

  // 轨迹图
  function onTrackView(row: FullReviewItem) {
    // TODO: 轨迹图
    console.log('复核:', row);
  }

  // 再次复核
  async function onRestartReview() {
    const checkRes = await checkReReview(searchModel.subjectCode);
    // -1-不可以再次复核，并弹出消息，0-需要弹出消息以待确认，1-可以再次复核
    if (checkRes.status === 1) {
      await reReview(searchModel.subjectCode);
      return;
    }

    if (checkRes.status === 0) {
      const confirm = await modalConfirm(checkRes.message, '提示 ').catch(
        () => false
      );
      if (!confirm) return;

      await reReview(searchModel.subjectCode);
      return;
    }

    if (checkRes.status === -1) {
      ElMessage.error(checkRes.message);
    }
  }

  // 批量取消复核
  async function onBatchCancelReview() {
    if (selectedRows.length === 0) {
      ElMessage.warning('请选择要取消复核的数据');
      return;
    }
    const confirm = await modalConfirm(
      `确认取消复核选中的 ${selectedStudentIds.value.length}条数据吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      const res = await cancelReview(selectedStudentIds.value);
      if (res.success) {
        ElMessage.success('取消复核成功');
        getList();
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      console.error('取消复核失败:', error);
    }
  }

  // 取消复核
  async function onCancelReview(row: FullReviewItem) {
    const confirm = await modalConfirm(
      `确认取消当前复核数据吗？`,
      '提示 '
    ).catch(() => false);
    if (!confirm) return;

    try {
      const res = await cancelReview([row.id]);
      if (res.success) {
        ElMessage.success('取消复核成功');
        getList();
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      console.error('取消复核失败:', error);
    }
  }

  // 导入
  const importDialogRef = ref();
  function onImport() {
    importDialogRef.value?.open();
  }

  // 导出
  const onExportCommand = async (
    command: 'exportReviewWorkload' | 'exportReviewStatList'
  ) => {
    await downloadExport(command, searchModel);
  };
</script>
