<template>
  <my-quote
    message="注：系统已自动将所有考生违纪字段置为“0”，导入后会更新该字段，导入只更新导入的考生信息，其它考生不更新。"
    type="error"
    style="margin-bottom: 16px"
  >
  </my-quote>

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

  <!-- ImportDialog -->
  <ImportDialog
    ref="importDialogRef"
    title="违纪导入"
    upload-url="/api/admin/student/breach/import"
    :upload-data="uploadData"
    download-btn-title="违纪导入模版"
    :download-handle="downloadHandle"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import type { TableProps } from "ant-design-vue";
import { message } from "ant-design-vue";

import { BreachListItem } from "@/ap/types/resultExport";
import { breachList, breachTemplateDownload } from "@/ap/resultExport";
import { downloadByApi } from "@/utils/download";
import { useUserStore } from "@/store";

import ImportDialog from "@/components/ImportDialog/index.vue";

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

const loading = ref(false);
const dataList = ref<BreachListItem[]>([]);

const columns: TableProps["columns"] = [
  {
    title: "科目代码",
    dataIndex: "subjectCode",
  },
  {
    title: "科目名称",
    dataIndex: "subjectName",
  },
  {
    title: "已导入违纪考生数",
    dataIndex: "breachCount",
    width: "180px",
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "100px",
    customCell: () => {
      return {
        class: "operation-cell",
      };
    },
  },
];

async function getData() {
  const res = await breachList({ examId: userStore.curExam.id });
  dataList.value = res || [];
}

const importDialogRef = ref();
const uploadData = ref<Record<string, string>>({});
async function onImport(index: number) {
  const record = dataList.value[index];
  uploadData.value = {
    examId: userStore.curExam.id,
    subjectCode: "",
  };
  importDialogRef.value?.open();
}

async function downloadHandle() {
  const res = await downloadByApi(() => breachTemplateDownload()).catch(
    (e: Error) => {
      message.error(e.message || "下载失败，请重新尝试！");
    }
  );
  if (!res) return;
  message.success("下载成功！");
}

onMounted(() => {
  dataList.value = [
    { subjectCode: "8956145235", subjectName: "语法基础", breachCount: 12 },
  ];
  // getData()
});
</script>
