<script lang="ts" setup>
/**
 * @Name: index.vue
 * @Description: 文件上传
 * @Author: Cheney
 */
import { ButtonProps, genFileId, UploadInstance, UploadRawFile } from 'element-plus';
import { BtnPermissionStore } from '/@/plugin/permission/store.permission';
import { uploadFile } from '/@/views/product-manage/product-list/api';
import { hasPermission } from '/@/utils/hasPermission';


const attrs = useAttrs() as any;
const refreshView = inject('refreshView');

const props = defineProps<
    {
      uploadFunction: (url: 'URL') => Promise<any>;
    } & Partial<Omit<ButtonProps, 'disabled' | 'loading' | 'color'>>
>();

const upload = ref<UploadInstance>();
const upBtnLoading = ref(false);
const emits = defineEmits([ 'handel-error' ]);

/**
 * @description 替换文件并上传
 * @param files 文件列表
 */
function handleExceed(files: any) {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
}

/**
 * 上传文件
 * @param uploadRequest 上传请求
 */
async function handleCustomUpload(uploadRequest: any) {
  upBtnLoading.value = true;
  try {
    const { file } = uploadRequest;
    const formData = new FormData();
    formData.append('file', file);
    const resp = await uploadFile(formData);
    const fileUrl = resp.data.url;
    const response = await props.uploadFunction({ url: fileUrl });
    handleResponse(response);
    uploadRequest.onSuccess(response);
  } catch (error) {
    console.log('==Error==', error);
    uploadRequest.onError(error);
  } finally {
    upBtnLoading.value = false;
  }
}

/**
 * 统一处理响应
 * @param response 后端返回的响应
 */
function handleResponse(response: any) {
  if (response.data && response.data.length !== 0) {
    emits('handel-error', response.data);
    return;
  }
  if (response.code === 2000) {
    ElMessage.success({ message: response.msg, plain: true });
    if (refreshView) {
      refreshView();
    }
  } else {
    ElMessage.error({ message: '上传失败', plain: true });
  }
}
</script>

<template>
  <div>
    <el-upload
        ref="upload"
        :auto-upload="true"
        :http-request="handleCustomUpload"
        :limit="1"
        :on-exceed="handleExceed"
        :show-file-list="false"
        accept=".xls,.xlsx"
        action="#"
    >
      <template #trigger>
        <el-button
            v-if="attrs.show ? hasPermission(attrs.show) : true"
            :color="attrs.myColor"
            :disabled="attrs.permissions ? !hasPermission(attrs.permissions) : false"
            :loading="upBtnLoading"
            v-bind="props"
        >
          <!--:loading="upBtnLoading" color="#6366f1" v-bind="props">-->
          <slot></slot>
        </el-button>
      </template>
    </el-upload>
  </div>
</template>

<style scoped></style>
