<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" />
      <a-button type="primary" @click="onAdd">
        <template #icon> <PlusCircleOutlined /> </template>
        新增评卷点信息</a-button
      >
    </a-space>

    <a-table
      :columns="columns"
      :row-key="(record) => record.id"
      :data-source="dataList"
      :pagination="pagination"
      :loading="loading"
      bordered
    >
      <template #bodyCell="{ column, index, text }">
        <template v-if="column.dataIndex === 'condition'">
          {{ getConditionContent(index) }}
        </template>
        <template v-if="column.dataIndex === 'stage'">
          {{ text === "SECOND" ? "第二次复查" : "第一次复查" }}
        </template>
        <template v-if="column.dataIndex === 'finishCount'">
          {{ getConditionProgress(index) }}
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a-button
            v-if="checkActionValid(index, 'arbitrate')"
            type="link"
            :diabled="checkDangerActionRunning(index)"
            @click="onArbitrate(index)"
            >仲裁</a-button
          >
          <a-button
            v-if="checkActionValid(index, 'edit')"
            type="link"
            :diabled="checkDangerActionRunning(index)"
            @click="onEdit(index)"
            >修改</a-button
          >
          <a-button
            v-if="checkActionValid(index, 'reset')"
            type="link"
            :diabled="checkDangerActionRunning(index)"
            @click="onReset(index)"
            >重置</a-button
          >
          <a-button
            v-if="checkActionValid(index, 'recheck')"
            type="link"
            :diabled="checkDangerActionRunning(index)"
            @click="onRecheck(index)"
            >复查</a-button
          >
          <a-button
            v-if="checkActionValid(index, 'buildTask')"
            type="link"
            :diabled="checkDangerActionRunning(index)"
            @click="onBuildTask(index)"
            >生成任务</a-button
          >
          <a-button
            v-if="checkActionValid(index, 'delete')"
            type="link"
            :diabled="checkDangerActionRunning(index)"
            @click="onDelete(index)"
            >删除</a-button
          >
        </template>
      </template>
    </a-table>

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

  <router-view />
</template>

<script setup lang="ts">
import { ref, 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: "120px",
  },
  {
    title: "任务总数",
    dataIndex: "totalCount",
    width: "90px",
  },
  {
    title: "完成进度",
    dataIndex: "finishCount",
    width: "90px",
  },
  {
    title: "已仲裁数量",
    dataIndex: "arbitratedCount",
    width: "110px",
  },
  {
    title: "待仲裁数量",
    dataIndex: "unarbitrateCount",
    width: "110px",
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "240px",
    customCell: () => {
      return {
        class: "operation-cell",
      };
    },
  },
];
const curRow = ref(null as RecognizeCheckTaskSaveParams | null);

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

type ActionType =
  | "arbitrate"
  | "edit"
  | "reset"
  | "recheck"
  | "buildTask"
  | "delete";
function checkActionValid(index: number, type: ActionType): boolean {
  const record = dataList.value[index];

  if (type === "arbitrate") {
    return record.stage === "SECOND" && record.unarbitrateCount > 0;
  }
  if (type === "edit") {
    return record.totalCount === 0;
  }
  if (type === "reset") {
    return true;
  }
  if (type === "recheck") {
    return (
      record.stage === "FIRST" &&
      record.finishCount === record.totalCount &&
      record.finishCount > 0
    );
  }
  if (type === "buildTask") {
    return !record.fixed;
  }
  if (type === "delete") {
    return !record.fixed;
  }

  return true;
}
function checkDangerActionRunning(index: number) {
  const record = dataList.value[index];
  return record.building || record.deleting || record.reseting;
}

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>
