<template>
  <Dialog title="导入银行流水" v-model="dialogVisible" width="500px">
    <el-upload
      ref="uploadRef"
      :limit="1"
      :auto-upload="false"
      :on-change="handleFileChange"
      :on-exceed="handleExceed"
      accept=".xls,.xlsx"
      drag
    >
      <Icon icon="ep:upload-filled" :size="60" class="text-gray-400" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">
          <el-checkbox v-model="updateSupport" class="mr-10px" />是否更新已存在的数据
          <el-link type="primary" :underline="false" @click="downloadTemplate" class="ml-10px">
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { BankTransactionApi } from '@/api/erp/finance/bank'
import download from '@/utils/download'

/** 银行流水导入表单 */
defineOptions({ name: 'BankTransactionImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref() // 上传组件的 Ref
const updateSupport = ref(false) // 是否更新已存在的数据
const fileList = ref<any[]>([]) // 文件列表

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  updateSupport.value = false
  fileList.value = []
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 文件变更处理 */
const handleFileChange = (file: any) => {
  fileList.value = [file]
}

/** 文件超出限制处理 */
const handleExceed = () => {
  message.warning('最多只能上传一个文件')
}

/** 下载模板 */
const downloadTemplate = async () => {
  const data = await BankTransactionApi.getImportTemplate()
  download.excel(data, '银行流水导入模板.xls')
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (fileList.value.length === 0) {
    message.warning('请选择要上传的文件')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const file = fileList.value[0].raw
    const result = await BankTransactionApi.importBankTransaction(file, updateSupport.value)
    message.success(result || '导入成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (e) {
    console.error('导入失败', e)
  } finally {
    formLoading.value = false
  }
}
</script>
