<template>
  <el-upload ref="upload" :action="action" :headers="reactiveData.headers" :list-type="listType" name="file"
    :multiple="multiple" :data="data" :accept="accept" :show-file-list="showFileList" :before-upload="beforeUpload"
    :on-success="onSuccess" :on-error="onError" :before-remove="beforeRemove" :on-remove="handleRemove"
    :disabled="disabled">
    <div class="image" v-if="listType === 'picture-card'">
      <el-icon v-if="src === ''" size="28">
        <Plus />
      </el-icon>
      <el-image v-else :src="src" />
    </div>
    <el-button v-else :type="type" :loading="loading === 1">{{ title }}</el-button>
  </el-upload>
</template>

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

const { proxy } = getCurrentInstance()

const props = defineProps({
  // 上传路径
  url: {
    type: String,
    default: undefined
  },
  // 是否支持多文件上传
  multiple: {
    type: Boolean,
    default: false
  },
  // 额外参数
  data: {
    type: Object || Function,
    default: () => { }
  },
  // 上传类型
  listType: {
    type: String,
    default: 'text'
  },
  // 文件类型
  accept: {
    type: String,
    default: ''
  },
  // 是否显示上传列表
  showFileList: {
    type: Boolean,
    default: false
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 图片
  src: {
    type: String,
    default: ''
  }
})

// 上传地址
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)

const action = ref(`${baseUrl.value}/common/upload`)

const reactiveData = reactive({
  headers: { Authorization: "Bearer " + getToken() },
  // 上传文件
  form: [],
})

// 上传状态
const loading = ref(false)
const type = ref('primary')
const title = ref('点击上传')

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

// 上传成功
function onSuccess(file) {
  if (file.code === 200) {
    loading.value = false
    type.value = 'success'
    title.value = '上传成功'
    if (props.multiple) {
      file.data.map(i => reactiveData.form.push(i))
    } else {
      reactiveData.form.data = file
    }
    proxy.$emit('upload', reactiveData.form)
  } else {
    onError()
  }
}

// 文件移除之前
function beforeRemove() {
  return proxy.$modal.confirm('是否删除？').then(
    () => true,
    () => false
  )
}

// 文件列表移除时
function handleRemove(file) {
  let e = reactiveData.form.filter(i => i.name !== file.name)
  proxy.$emit('upload', e)
}

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

// 重置组件
function onRefresh() {
  type.value = 'primary'
  title.value = '点击上传'
  proxy.$refs.upload.clearFiles()
}

defineExpose({
  onRefresh
})
</script>

<style lang="scss" scoped>
.image {
  width: 148px;
  height: 148px;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-image{
    height: 100%;
  }
}
</style>