<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, record }">
        <template v-if="column.dataIndex === 'subjectName'">
          {{ record.subjectCode + "-" + record.subjectName }}
        </template>
        <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'">
          <span v-if="record.building">生成任务中...</span>
          <span v-else-if="record.reseting">重置中...</span>
          <span v-else-if="record.deleting">删除中...</span>
          <template v-else>
            <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>
      </template>
    </a-table>

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

  <router-view />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, onBeforeUnmount } 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,
  RecognizeConditionItem,
} from "@/ap/types/recognizeCheck";
import {
  recognizeCheckListPage,
  recognizeCheckTaskDelete,
  recognizeCheckResetTask,
  recognizeCheckBuildTask,
  recognizeCheckTaskStatusSave,
  recognizeConditionsList,
  recognizeConditionsListAll,
} from "@/ap/recognizeCheck";
import { showConfirm } from "@/utils/uiUtils";
import { useUserStore } from "@/store";

import ModifyRecognizeCheckTask from "./ModifyRecognizeCheckTask.vue";
import { useIntervalFn } from "@vueuse/core";

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

const userStore = useUserStore();

const router = useRouter();
const route = useRoute();

// condition action
const conditionListAll = ref<RecognizeConditionItem[]>([]);
const conditionList = ref<RecognizeConditionItem[]>([]);
const conditionMap = ref<Record<string, string>>({});
async function getConditionListAll() {
  const res = await recognizeConditionsListAll();

  conditionListAll.value = res || [];
  conditionListAll.value.forEach((item) => {
    conditionMap.value[item.code] = item.name;
  });
}
async function getConditionList() {
  const res = await recognizeConditionsList();
  conditionList.value = res || [];
}

// datalist
const searchModel = reactive({
  examId: userStore.curExam.id,
  subjectCode: "",
});

const columns: TableProps["columns"] = [
  {
    title: "任务条件",
    dataIndex: "condition",
    minWidth: 200,
  },
  {
    title: "科目",
    dataIndex: "subjectName",
    minWidth: 120,
  },
  {
    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<RecognizeCheckListItem | null>(null);

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

const { pause, isActive, resume } = useIntervalFn(getList, 30 * 1000, {
  immediate: 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 &&
      !(record.conditions || []).find(
        (item: any) => item.code === "FILL_SUSPECT"
      )
    );
  }
  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) => `${conditionMap.value[item.code]}${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: number) {
  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(async () => {
  if (route.name !== "RecognizeCheck") return;

  await getConditionListAll();
  await getConditionList();
  await toPage(1);
});

watch(
  dataList,
  () => {
    pause();
    if (
      dataList.value.find((item) => {
        return item.building || item.deleting || item.reseting;
      })
    ) {
      resume();
    }
  },
  { deep: true, immediate: true }
);
onBeforeUnmount(() => {
  pause();
});
</script>
