<script lang="ts" setup>
import type { UploadUserFile } from 'element-plus';

import { ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { ExcelIcon } from '@vben/icons';

import { UploadFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

import { filterImportData } from '#/api/oilstation/filter/filter';

const emit = defineEmits<{ reload: [] }>();

// 是否更新/覆盖已存在的过滤器数据
const isUpdateRef = ref<boolean>(false);
// 上传的文件列表
const upFileListRef = ref<UploadUserFile[]>([]);
const [Modal, ModalApi] = useVbenModal({
  async onConfirm() {
    if (upFileListRef.value.length <= 0) {
      ElMessage.error('请上传附件');
      return;
    }
    this.confirmLoading = true;
    // 组装参数
    const data = {
      file: upFileListRef.value[0]!.raw as Blob,
      updateSupport: unref(isUpdateRef),
    };
    try {
      const { code, msg } = await filterImportData(data);
      if (code === 200) {
        await ModalApi.close();
        // 更新列表
        emit('reload');
      } else {
        ElMessage.error(msg);
      }
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
// 下载模板
function downloadTemplate() {
  console.log('下载模板');
  try {
    // 使用 import.meta.url 构建模板文件的绝对路径，确保使用正确的协议和路径
    const currentUrl = new URL(import.meta.url);
    const templateUrl = new URL('./filter-import-template.xls', currentUrl).href;
    
    // 创建a标签进行下载
    const link = document.createElement('a');
    link.href = templateUrl;
    link.download = 'filter-import-template.xls';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载模板失败:', error);
    // 备用方案：使用相对路径
    const templateUrl = './filter-import-template.xls';
    window.open(templateUrl, '_blank');
  }
}
</script>

<template>
  <Modal title="过滤器导入">
    <el-upload
      drag
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      limit="1"
      :auto-upload="false"
      v-model:file-list="upFileListRef"
    >
      <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
      <div>点击或者拖拽到此处上传文件</div>
    </el-upload>
    <div class="mb-1.5 flex items-center gap-[4px]">
      <span>允许导入xlsx, xls文件</span>
      <ExcelIcon />
      <ElButton link type="primary" @click="downloadTemplate">下载模板</ElButton>
    </div>
    <div>
      <span class="mr-2" :class="{ 'text-red-500': isUpdateRef }">
        是否更新/覆盖已存在的数据
      </span>
      <el-switch v-model="isUpdateRef" />
    </div>
  </Modal>
</template>
