<template>
  <el-upload :file-list="_value"
             :action="uploadFileUrl"
             :headers="headers"
             :limit="maxSize"
             with-credentials
             :multiple="multiple"
             :data="uploadParams"
             :show-file-list="showFileList"
             :auto-upload="true"
             :before-upload="beforeUpload"
             :on-success="handleUploadSuccess"
             :on-error="uploadError"
             :before-remove="beforeRemove"
             :on-remove="handleRemove"
  >
    <el-button color="#DED0B2" :loading="loading" :disabled="disabled">上传文件</el-button>
  </el-upload>
</template>

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

const baseURL = import.meta.env.VITE_BASE_URL
const uploadFileUrl = ref(baseURL + "/workflow/process/file/upload")
const headers = reactive({
  authorization: getToken()
})
const loading = ref(false)
const showTable = ref(false)
const uploadParams = ref({})
const props = defineProps({
  value: {
    type: Array,
    default: () => {
      return []
    }
  },
  maxSize: {
    type: Number,
    default: 30
  },
  showFileList: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(["input", "getFile", "delete"])
const fileList = ref([])
const _value = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit("input", val);
  }
})
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 handleUploadSuccess = (res) => {
  ElNotification({
    title: '提示',
    message: res.code === 1000 ? '上传成功' : '上传失败',
    type: res.code === 1000 ? 'success' : 'error'
  })
  loading.value = false
  showTable.value = true
  let data = res.data
  fileList.value.push(data)
  emit("getFile", res.data)
}
const uploadError = () => {
  loading.value = false
  ElNotification({
    title: '提示',
    message: "上传失败，请稍后再试！",
    type: 'error'
  })
}
defineExpose({
  handleRemove
})
</script>

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

:deep(.el-upload-list) {
  width: 400px;
}
</style>
