<script lang="ts" setup>
import { type ButtonProps, ElMessage, genFileId, UploadInstance, UploadRawFile } from 'element-plus';
import { SUCCESS_CODE, WARNING_CODE } from '/@/utils/requestCode';


const props = defineProps<Partial<Omit<ButtonProps, 'loading'>>>();
const attrs = useAttrs() as any;
const emit = defineEmits([ 'upload-success', 'upload-error' ]);

const upload = ref<UploadInstance>();
const loading = ref(false);

async function handleCustomUpload(uploadRequest: any) {
  try {
    loading.value = true;
    const { file } = uploadRequest;
    const formData = new FormData();
    formData.append('file', file);
    const response = await attrs.api(formData);
    handleResponse(response);
    uploadRequest.onSuccess(response);
  } catch (error) {
    console.log('Error==>', error);
    uploadRequest.onError(error);
    emit('upload-error', error);
  } finally {
    loading.value = false;
  }
}

function handleExceed(files: any) {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
}

function handleResponse(response: any) {
  if (response.code === SUCCESS_CODE) {
    ElMessage.success({ message: response.msg, plain: true });
    emit('upload-success', response);
  } else if (response.code === WARNING_CODE) {
    ElMessage.warning({ message: response.msg, plain: true });
  } else {
    ElMessage.error({ message: response.msg, plain: true });
    emit('upload-error', response);
  }
}
</script>

<template>
  <el-upload
      ref="upload"
      :auto-upload="true"
      :http-request="handleCustomUpload"
      :limit="1"
      :on-exceed="handleExceed"
      :show-file-list="attrs.showFileList"
      action="#"
      v-bind="attrs">
    <template #trigger>
      <el-button :loading="loading" plain round type="warning" v-bind="props">
        <slot></slot>
      </el-button>
    </template>
  </el-upload>
</template>
