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

  <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/cust-status/import"
    :upload-data="uploadData"
    download-btn-title="考生状态导入模版"
    :download-handle="downloadHandle"
  >
    <a-form-item
      label="科目"
      :label-col="{ style: { width: '80px' } }"
      label-align="left"
      >{{ curRow.subjectName }}</a-form-item
    >
  </ImportDialog>
</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 { StudentStatusListItem } from "@/ap/types/resultExport";
import { studentStatusList, statusTemplateDownload } from "@/ap/resultExport";
import { downloadByApi } from "@/utils/download";

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

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

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

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

const curRow = ref({} as StudentStatusListItem);

async function getData() {
  const res = await studentStatusList({ examId: "" });
  dataList.value = res || [];
}

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

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

onMounted(() => {
  dataList.value = [
    { subjectCode: "123456789", subjectName: "数学理论", custStatusCount: 89 },
  ];

  // getData()
});
</script>
