<template>
  <Dialog title="许可证照导入" v-model="dialogVisible" width="400px">
    <div>
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        :action="importUrl"
        :headers="uploadHeaders"
        :limit="1"
        :on-success="submitFormSuccess"
        :on-error="submitFormError"
        :auto-upload="false"
        accept=".xlsx, .xls"
        drag
      >
        <Icon icon="ep:upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">
                下载模板
              </el-link>
            </div>
            <div class="el-upload__tip" style="color: red">提示：仅允许导入xls、xlsx格式文件！</div>
          </div>
        </template>
      </el-upload>
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'
import { PermitApi } from '@/api/safe/permit'

defineOptions({ name: 'PermitImportForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/safe/permit/import-excel' // 导入的请求地址
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表

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

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = () => {
  if (fileList.value.length == 0) {
    message.error('请选择要上传的文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = '上传成功数量：' + data.successCount + ';'
  for (let name of data.errorMessages) {
    text += '< br / >' + name
  }
  message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  emit('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  fileList.value = []
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await PermitApi.importPermitTemplate()
  download.excel(res, '许可证照导入模板.xls')
}
</script>
