<template>
  <el-upload ref="upload" :action="actionApi" :auto-upload="auto" :limit="1" :before-remove="beforeRemove"
    :on-exceed="handleExceed" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
    :headers="{ authorization: token }" v-bind="$attrs">
    <template v-for="(index, name) in $slots" v-slot:[name]>
      <slot :name="name"></slot>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { env } from '@/support/helper'
import { getAuthToken } from '@/support/helper'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}

const props = defineProps({
  action: {
    type: String,
    default: 'upload',
  },
  auto: {
    type: Boolean,
    default: true,
  },
})
const emit = defineEmits(['success', 'destory']);

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log(response, uploadFile.raw);
  emit('success', response.data);
}

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
  emit('destory');
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确定要删除 ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

const baseURL = env('VITE_BASE_URL')

const actionApi = ref<string>('')

actionApi.value = baseURL + props.action

const token = ref<string>()
token.value = 'Bearer ' + getAuthToken()
</script>
