<template>
  <el-dialog
    v-model="dialogVisible"
    title="导入"
    width="600"
    :close-on-click-modal="false"
  >
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :accept="accept"
      drag
      style="width: 300px; margin: 0 auto"
      v-loading="formLoading"
    >
      <el-icon color="#c0c4cc" :size="60"><UploadFilled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或'<em>点击上传</em></div>
    </el-upload>
    <template #footer>
      <div class="footerBtns">
        <div>
          <el-button type="success" plain @click="importTemplate">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
        </div>
        <div>
          <el-button :disabled="formLoading" type="primary" @click="submitForm">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
defineOptions({ name: 'importPop' })
import { reactive, ref, onMounted } from 'vue'
import { ElDialog,ElMessage } from 'element-plus'
import { downloadByData } from '@/utils/download'
import { getCommonImportTemplate } from '@/api/common/index'

import { useRoute } from 'vue-router'
const route = useRoute()

const dialogVisible = ref(false) // 弹窗的是否展示
const fileList = ref([]) // 文件列表
const uploadRef = ref()
const formLoading = ref(false) // 表单的加载中
const uploadHeaders = ref() // 上传 Header 头
// const importUrl = getBaseUrl() + import.meta.env.VITE_API_URL + (props.url || '/finance/common-excel-in/import')

const props = defineProps({
  // api名称
  apiName: {
    type: String,
    default: null
  },
  // 可以导入的文件类型
  accept: {
    type: String,
    required: false,
    default: '.xlsx,.xls'
  },
})

const importUrl =  `/api/${props.apiName}/import`

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
  fileList.value = []
}

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

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

/** 文件数超出提示 */
const handleExceed = (): void => {
    ElMessage.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = () => {
  formLoading.value = true
  getCommonImportTemplate(props.apiName)
    .then(res=>{
      downloadByData(res.data,route.meta.title+'_模板.xlsx')
    })
    .finally(() => (formLoading.value = false))
}

// /** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    ElMessage.error('请上传文件')
    return
  }
  // 提交请求
  // uploadHeaders.value = {
  //   Authorization: 'Bearer ' + getAccessToken(),
  //   'tenant-id': getTenantId()
  // }
  formLoading.value = true
  uploadRef.value!.submit()
}

// /** 文件上传成功 */
const emits = defineEmits(['success'])
// todo:成功后处理
const submitFormSuccess = (response: any) => {
  formLoading.value = true
  if (response) {
    if(response.code == '200'){
      ElMessage.success('导入成功！')
    }else{
      ElMessage.error(response.msg)
    }
    // if (response.code == 500) {
    //   uploadRef.value!.clearFiles()
    //   ElMessage.error('导入失败')
    //   formLoading.value = false
    //   return
    // } 
    // // todo:错误下载
    // else if (response.code == 0) {
    //   if (response.data.errorCount > 0) {
    //     ElMessage.confirm('文件中有部分数据导入失败，是否下载失败数据？').then(async () => {
    //         // todo:失败下载链接
    //       window.open(
    //         getJmreportBaseUrl() + response.data.errorFile,
    //         'TITLE'
    //       )
    //     })
    //   } else {
    //     ElMessage.success('导入成功')
    //   }
    // }
    // else if(response.data == null){
    //   ElMessage.error(response.msg)
    // }
  }

  // 发送操作成功的事件
  formLoading.value = false
  emits('success')
  dialogVisible.value = false
}
</script>
<style lang="scss" scoped>
  .footerBtns{
    display: flex;
    padding: 20px;
    justify-content: space-between;
  }
</style>