<template>
  <el-dialog v-model="visible" :title="`${title}批量导入`" width="460px" append-to-body @closed="reset">
    <el-upload
      ref="uploadRef"
      drag
      :limit="1"
      accept=".xlsx, .xls"
      :headers="headers"
      :action="actionUrl"
      :disabled="isUploading"
      :auto-upload="false"
      :before-upload="validateFile"
      :on-progress="onProgress"
      :on-success="onSuccess"
      :on-error="onError"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">
          <el-checkbox v-model="updateSupport">更新已存在的业务编码</el-checkbox>
          <el-link type="primary" :underline="false" @click="downloadTemplate">下载模板</el-link>
          <div>仅支持 xls、xlsx，业务编码为空的行将被跳过。</div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button type="primary" :loading="isUploading" @click="submit">开始导入</el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref } from 'vue'
import { getToken } from '@/utils/auth'
import { download } from '@/utils/request'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  title: { type: String, required: true },
  uploadUrl: { type: String, required: true },
  templateUrl: { type: String, required: true }
})
const emit = defineEmits(['update:modelValue', 'imported'])
const uploadRef = ref()
const updateSupport = ref(false)
const isUploading = ref(false)
const headers = { Authorization: `Bearer ${getToken()}` }
const actionUrl = computed(() => `${import.meta.env.VITE_APP_BASE_API}${props.uploadUrl}?updateSupport=${updateSupport.value}`)
const visible = computed({ get: () => props.modelValue, set: value => emit('update:modelValue', value) })

function submit() { uploadRef.value?.submit() }
function validateFile(file) {
  if (!/\.(xlsx|xls)$/iu.test(file?.name || '')) {
    ElMessage.error('仅支持 xls、xlsx 文件')
    return false
  }
  return true
}
function onProgress() { isUploading.value = true }
function onSuccess(response) {
  isUploading.value = false
  if (response?.code && response.code !== 200) {
    ElMessage.error(response.msg || '导入失败，请检查文件格式')
    return
  }
  ElMessage.success(response?.msg || '导入成功')
  emit('imported')
  visible.value = false
}
function onError(error) {
  isUploading.value = false
  ElMessage.error(error?.message || '导入失败，请检查文件格式')
}
function downloadTemplate() {
  download(props.templateUrl, {}, `${props.title}导入模板.xlsx`)
}
function reset() {
  updateSupport.value = false
  isUploading.value = false
  uploadRef.value?.clearFiles()
}
</script>
