<template>
  <el-upload :file-list="[]"
             :limit="maxSize"
             with-credentials
             :multiple="multiple"
             :http-request="httpRequestHandle"
             :data="uploadParams"
             :auto-upload="true"
             :show-file-list="false"
             :before-upload="beforeUpload"
             :before-remove="beforeRemove"
             :on-remove="handleRemove"
  >
    <el-button color="#DED0B2" style="margin-right: 10px;" :disabled="disabled">导入</el-button>
  </el-upload>
</template>

<script setup>
import {ElMessageBox, ElNotification} from "element-plus";
import {getToken} from '@/utils/auth'
import axios from "axios";

const props = defineProps({
  value: {
    type: Array,
    default: () => {
      return []
    }
  },
  maxSize: {
    type: Number,
    default: 30
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
})


const baseURL = import.meta.env.VITE_BASE_URL
const uploadFileUrl = ref(baseURL + "/workflow/mosr/rd/expense/import")
const headers = reactive({
  authorization: getToken()
})
// const loading = ref(false)
const uploadParams = ref({})
const emit = defineEmits(["input", "getFile", "delete"])
const beforeRemove = (file) => {
  return ElMessageBox.confirm(`确认删除名称为${file.name}的文件吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => true)
}

const handleRemove = (file) => {
  emit("delete", file.response.data.id)
}
const beforeUpload = () => {
  // loading.value = true
  return true
}
const httpRequestHandle = (param) => {

  let file = param.file
  axios.post(uploadFileUrl.value, {
    file: file
  }, {
    headers: {
      'Content-Type': 'multipart/form-data',
      ...headers
    }
  }).then(res => {
    handleUploadSuccess(res)
  }).catch(error => {
    uploadError(error)
  })
}
const handleUploadSuccess = (res) => {
  let data = res.data
  ElNotification({
    title: '提示',
    message: data.code === 1000 ? '上传成功' : '上传失败',
    type: data.code === 1000 ? 'success' : 'error'
  })
  emit("success")
}
const uploadError = (error) => {
  console.log("🚀 ~ file:'error ", error.response.data.msg)

  // loading.value = false
  ElNotification({
    title: '提示',
    message: error.response.data.msg,
    type: 'error'
  })
}
defineExpose({
  handleRemove
})
</script>

<style lang="scss" scoped>
a {
  font-size: 14px;
  color: #2a99ff;
}

</style>
