<template>
  <div class="m-b-16px">
    <qm-button type="primary" :icon="h(PlusCircleOutlined)" @click="onAdd"
      >新增评卷点信息</qm-button
    >
  </div>

  <a-table
    :columns="columns"
    :row-key="(record) => record.subjectCode"
    :data-source="dataList"
    :pagination="pagination"
    :loading="loading"
    bordered
  >
    <template #bodyCell="{ column, index }">
      <template v-if="column.dataIndex === 'operation'">
        <qm-button type="link" @click="onEdit(index)">编辑</qm-button>
        <qm-button type="link" @click="onDelete(index)">删除</qm-button>
      </template>
    </template>
  </a-table>

  <!-- ModifyMarkSite -->
  <ModifyMarkSite
    ref="modifyMarkSiteRef"
    :row-data="curRow"
    @modified="getList"
  />
</template>

<script setup lang="ts">
import { ref, h } from "vue";
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 { MarkSiteListItem } from "@/ap/types/resultExport";
import { markSiteDelete, markSiteListPage } from "@/ap/resultExport";
import { showConfirm } from "@/utils/uiUtils";
import { useUserStore } from "@/store";

import ModifyMarkSite from "./ModifyMarkSite.vue";

defineOptions({
  name: "MarkSite",
});
const userStore = useUserStore();

const columns: TableProps["columns"] = [
  {
    title: "科目代码",
    dataIndex: "subjectCode",
  },
  {
    title: "科目名称",
    dataIndex: "subjectName",
  },
  {
    title: "条码值",
    dataIndex: "paperType",
    width: "120px",
  },
  {
    title: "奇数考场评卷点代码",
    dataIndex: "oddNumber",
    width: "160px",
  },
  {
    title: "偶数考场评卷点代码",
    dataIndex: "evenNumber",
    width: "160px",
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "110px",
    customCell: () => {
      return {
        class: "operation-cell",
      };
    },
  },
];
const curRow = ref({} as MarkSiteListItem);

const { dataList, pagination, loading, getList, toPage, deletePageLastItem } =
  useTable<MarkSiteListItem>(
    markSiteListPage,
    { examId: userStore.curExam.id },
    true
  );

const modifyMarkSiteRef = ref();
function onAdd() {
  curRow.value = {} as MarkSiteListItem;
  modifyMarkSiteRef.value?.open();
}

async function onEdit(index: number) {
  curRow.value = dataList.value[index];
  modifyMarkSiteRef.value?.open();
}

async function onDelete(index: number) {
  const confirm = await showConfirm({
    content: "确定要删除此评卷点信息？",
  }).catch(() => false);
  if (confirm !== "confirm") return;

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

  deletePageLastItem();
  message.success("操作成功");
}
</script>
