<template>
  <div style="background: #ececec; padding-top: 0px; padding-left: 20px; padding-right: 20px; padding-bottom: 20px">
    <a-card title="英语六级数据导入" :bordered="false">
      <a-row :gutter="2">
        <a-col :xl="24" :style="{ marginBottom: '24px' }">
          <div class="clearfix">
            <span style="padding-top: 5px">考试批次：</span>
            <a-space direction="vertical" :size="12">
              <a-date-picker v-model:value="month" picker="month" />
            </a-space>
            <div class="clearfix">
              <!-- accept=".dbf" 属性限制文件类型 -->
              <a-upload
                :file-list="fileList"
                accept=".dbf"
                :max-count="1"
                :customRequest="handleUpload"
                :before-upload="beforeUpload"
                @remove="handleRemove"
              >
                <a-button type="primary">
                  <upload-outlined />
                  导入文件
                </a-button>
              </a-upload>
            </div>
            <!--<div class="clearfix">
              <a-button preIcon="ant-design:export-outlined" @click="downloadTemplate"> 下载模板</a-button>
            </div>-->
            <div class="clearfix">
              <a-button type="primary" :disabled="!canUpload" :loading="uploading" @click="handleUpload">
                {{ uploading ? 'Uploading' : '确认上传文件' }}
              </a-button>
            </div>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <a-col :xl="24">
          <a-table :dataSource="dataSourceCet4" :columns="columns" :pagination="false" :loading="loading" bordered class="custom-table" />
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { message } from 'ant-design-vue';
  import { defHttp } from '/@/utils/http/axios';
  import { downloadTemplateExcel } from './dataImportApi';
  import { conversionFileDownload } from '@/utils/download';
  const loading = ref(false);
  // 批次选择（月份选择器）
  const month = ref(null);
  const url = {
    downLoadTemplate: '/cetDataImport/downloadTemplate',
    importCet4Data: '/cetDataImport/dbfImport',
    loadImportData: '/cet_6/loadImportDataList',
  };
  // 文件上传部分
  const fileList: any = ref([]);
  const uploading = ref(false);

  // 计算属性：控制上传按钮的可用性
  const canUpload = computed(() => fileList.value.length > 0 && month.value !== null);

  // 移除文件
  const handleRemove = (file) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  };

  // 文件选择前的校验处理
  const beforeUpload = (file) => {
    console.log(file);
    fileList.value = [];
    fileList.value = [...fileList.value, file];
    let fileType = file.name.split('.').pop().toLowerCase();
    if (fileType !== 'dbf') {
      message.error('请上传.dbf文件');
      fileList.value = fileList.value.filter((item) => item.uid !== file.uid);
    }
    return false; // 阻止自动上传
  };
  // 处理上传逻辑
  const handleUpload = async () => {
    // 检查是否选择了文件
    if (!fileList.value || fileList.value.length === 0) {
      message.error('没有选择文件');
      return;
    }

    const file = fileList.value[0];
    if (!file) {
      message.error('没有选择文件');
      return;
    }

    // 读取文件为 Base64 编码
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = async () => {
      const base64File = reader.result as string;

      // 构建请求体
      const payload = {
        fileName: file.name,
        fileContent: base64File,
        batch: '',
        level: 'cet6',
      };

      // 处理 batch 参数
      let batch: any = month.value;
      if (batch) {
        batch = batch.format('YYYY-MM-DD');
        batch = setDayToFirst(batch); // 将日期的天改为当月第一天
        payload.batch = batch;
      }

      try {
        uploading.value = true;

        // 发送 POST 请求
        const response: any = await defHttp.post(
          {
            url: url.importCet4Data,
            data: payload,
            headers: { 'Content-Type': 'application/json' },
          },
          {
            isTransformResponse: false,
          }
        );

        // 清空文件列表和日期选择（根据需要）
        fileList.value = [];

        // 处理响应
        if (response.success) {
          message.success('上传成功');
        } else {
          message.error(response.message || '上传失败');
        }
      } catch (error) {
        console.error('上传失败:', error);
        message.error('上传失败');
      } finally {
        uploading.value = false;
      }
    };
    reader.onerror = (error) => {
      console.error('文件读取错误:', error);
      message.error('文件读取失败');
    };
  };

  /**
   * 将 'yyyy-MM-dd' 格式的日期字符串的天部分设置为 '01'
   * @param {string} dateStr - 原始日期字符串，格式为 'yyyy-MM-dd'
   * @returns {string} 修改后的日期字符串，格式为 'yyyy-MM-01'
   */
  const setDayToFirst = (dateStr) => {
    // 使用正则表达式验证日期格式
    const regex = /^(\d{4})-(\d{2})-(\d{2})$/;
    const match = dateStr.match(regex);

    if (!match) {
      throw new Error("日期格式不正确，应为 'yyyy-MM-dd'");
    }

    const year = match[1];
    const month = match[2];

    // 构造新的日期字符串，天部分设置为 '01'
    return `${year}-${month}-01`;
  };

  // 定义表格的数据源
  const dataSourceCet4 = ref([]);
  // 定义表格的列配置
  const columns = [
    {
      title: '考试批次',
      dataIndex: 'batch',
      key: 'batch',
      align: 'center',
    },
    {
      title: '参加人数',
      dataIndex: 'attendNumber',
      key: 'attendNumber',
      align: 'center',
    },
  ];
  //处理表格数据源
  const fetchData = async () => {
    loading.value = true; // 开始加载
    try {
      const response = await defHttp.post({ url: url.loadImportData });
      console.log(response, 'response');
      dataSourceCet4.value = response.data; // 将数据绑定到表格
    } catch (error) {
      message.error('Failed to load data.');
    } finally {
      loading.value = false; // 加载结束
    }
  };

  //const downloadTemplate = async () => {
  //  downloadTemplateExcel()
  //    .then((response: any) => {
  //      console.log(response, '123');
  //      conversionFileDownload(response);
  //    })
  //    .catch((error) => {
  //      console.error(error);
  //    });
  //};

  // 在组件挂载时调用 fetchData
  onMounted(fetchData);
</script>

<style scoped>
  .clearfix {
    display: flex;
    padding-left: 10px;
  }
</style>
