<template>
  <el-upload :action="action[listType]" :headers="headers" :list-type="listType" name="multipartFile" :multiple="multiple"
    :data="data" :show-file-list="false" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError"
    :disabled="disabled">
    <el-button v-if="listType === 'text'" :type="type" :loading="loading === 1">{{ title }}</el-button>
  </el-upload>
</template>

<script setup>
import { getToken } from "@/utils/auth";

const props = defineProps({
  // 是否支持多文件上传
  multiple: {
    type: Boolean,
    default: false
  },
  // 额外参数
  data: {
    type: Object || Function,
    default: () => { }
  },
  // 上传类型
  listType: {
    type: String,
    default: 'text'
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})

const { proxy } = getCurrentInstance()

// 上传文件
const form = ref({})

// 上传地址
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)
const action = ref({
  'text': `${baseUrl.value}/system/file/file/upload`,
  'picture-card': `${baseUrl.value}/system/file/picture/upload`
})
// 请求头
const headers = ref({ Authorization: "Bearer " + getToken() })
// 上传状态
const loading = ref(false)
const type = ref('primary')
const title = ref('点击上传')

// 上传之前
function beforeUpload(file) {
  form.value.name = file.name
  form.value.size = file.size
  loading.value = true
  title.value = 'Loading'
}

// 上传成功
function onSuccess(file) {
  if (file.code === 0) {
    loading.value = false
    type.value = 'success'
    title.value = '上传成功'
    form.value.file = file.data
    proxy.$emit('upload', form.value)
  } else {
    onError()
  }
}

// 上传失败
function onError() {
  loading.value = false
  type.value = 'danger'
  title.value = '上传失败'
}
</script>