<template>
  <div v-if="route.name === 'RecognizeCheck'" class="page-box">
    <a-space class="m-b-16px" :size="8">
      <div>
        <span>科目：</span>
        <select-course
          v-model:value="searchModel.subjectCode"
          :exam-id="userStore.curExam.id"
          allow-clear
        ></select-course>
      </div>
      <a-button @click="toPage(1)">查询</a-button>
      <a-divider type="vertical" style="margin: 0" />
      <qm-button type="primary" :icon="h(PlusCircleOutlined)" @click="onAdd"
        >新增评卷点信息</qm-button
      >
    </a-space>

    <a-table
      :columns="columns"
      :row-key="(record) => record.id"
      :data-source="dataList"
      :pagination="pagination"
      :loading="loading"
      bordered
    >
      <template #bodyCell="{ column, index }">
        <template v-if="column.dataIndex === 'condition'">
          {{ getConditionContent(index) }}
        </template>
        <template v-if="column.dataIndex === 'finishCount'">
          {{ getConditionProgress(index) }}
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <qm-button type="link" @click="onArbitrate(index)">仲裁</qm-button>
          <qm-button type="link" @click="onEdit(index)">修改</qm-button>
          <qm-button type="link" @click="onReset(index)">重置</qm-button>
          <qm-button type="link" @click="onRecheck(index)">复查</qm-button>
          <qm-button type="link" @click="onBuildTask(index)"
            >生成任务</qm-button
          >
          <qm-button type="link" @click="onDelete(index)">删除</qm-button>
        </template>
      </template>
    </a-table>

    <ModifyRecognizeCheckTask
      ref="modifyRecognizeCheckTaskRef"
      :row-data="curRow"
      @modified="getList"
    />
  </div>

  <router-view />
</template>

<script setup lang="ts">
import { ref, h, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PlusCircleOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import type { TableProps } from "ant-design-vue";

import useTable from "@/hooks/useTable";
import { RecognizeCheckListItem } from "@/ap/types/recognizeCheck";
import {
  recognizeCheckListPage,
  recognizeCheckTaskDelete,
  recognizeCheckResetTask,
  recognizeCheckBuildTask,
  recognizeCheckTaskStatusSave,
} from "@/ap/recognizeCheck";
import { showConfirm } from "@/utils/uiUtils";
import { useUserStore } from "@/store";

import ModifyRecognizeCheckTask from "./ModifyRecognizeCheckTask.vue";

defineOptions({
  name: "RecognizeCheck",
});

const userStore = useUserStore();

const router = useRouter();
const route = useRoute();
const searchModel = reactive({
  examId: userStore.curExam.id,
  subjectCode: "",
});

const columns: TableProps["columns"] = [
  {
    title: "任务条件",
    dataIndex: "condition",
    minWidth: "200px",
  },
  {
    title: "科目",
    dataIndex: "subjectName",
    minWidth: "120px",
  },
  {
    title: "状态",
    dataIndex: "stage",
    width: "80px",
  },
  {
    title: "任务总数",
    dataIndex: "totalCount",
    width: "90px",
  },
  {
    title: "完成进度",
    dataIndex: "finishCount",
    width: "90px",
  },
  {
    title: "已仲裁数量",
    dataIndex: "arbitratedCount",
    width: "110px",
  },
  {
    title: "待仲裁数量",
    dataIndex: "unarbitrateCount",
    width: "110px",
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "200px",
    customCell: () => {
      return {
        class: "operation-cell",
      };
    },
  },
];
const curRow = ref(null as RecognizeCheckTaskSaveParams | null);

const { dataList, pagination, loading, getList, toPage, deletePageLastItem } =
  useTable<RecognizeCheckListItem>(recognizeCheckListPage, searchModel, false);

function getConditionContent(index: number): string {
  const record = dataList.value[index];
  return record.conditions
    .map((item) => `${item.name}${item.value || ""}`)
    .join(";");
}
function getConditionProgress(index: number): string {
  const record = dataList.value[index];
  if (!record.totalCount) return "0.00%";
  const progress = ((100 * record.finishCount) / record.totalCount).toFixed(2);
  return `${progress}%`;
}

const modifyRecognizeCheckTaskRef = ref();
function onAdd() {
  curRow.value = null;
  modifyRecognizeCheckTaskRef.value?.open();
}
function onEdit(index: number) {
  curRow.value = dataList.value[index];
  modifyRecognizeCheckTaskRef.value?.open();
}

function onArbitrate(index) {
  const record = dataList.value[index];
  router.push({ name: "RecognizeArbitrate", params: { groupId: record.id } });
}

async function onReset(index: number) {
  const confirm = await showConfirm({
    content: "确定要重置任务吗？",
  }).catch(() => false);
  if (confirm !== "confirm") return;

  const record = dataList.value[index];
  const res = await recognizeCheckResetTask(record.id).catch(() => false);
  if (!res) return;

  message.success("操作成功");
  await getList();
}

async function onRecheck(index: number) {
  const confirm = await showConfirm({
    content: "确定要复查任务吗？",
  }).catch(() => false);
  if (confirm !== "confirm") return;

  const record = dataList.value[index];
  const res = await recognizeCheckTaskStatusSave(record.id).catch(() => false);
  if (!res) return;

  message.success("操作成功");
  await getList();
}

async function onBuildTask(index: number) {
  const record = dataList.value[index];
  const res = await recognizeCheckBuildTask(record.id).catch(() => false);
  if (!res) return;

  message.success("操作成功");
  await getList();
}

async function onDelete(index: number) {
  const confirm = await showConfirm({
    content: "确定要删除任务吗？",
  }).catch(() => false);
  if (confirm !== "confirm") return;

  const record = dataList.value[index];
  const res = await recognizeCheckTaskDelete(record.id).catch(() => false);
  if (!res) return;

  deletePageLastItem();
  message.success("操作成功");
}

onMounted(() => {
  if (route.name !== "RecognizeCheck") return;

  toPage(1);
});
</script>
