<script lang="ts" setup>
import type { UploadProps, UploadUserFile } from 'element-plus';

import { ref } from 'vue';

import { useAppConfig } from '@easyflow/hooks';
import { useAccessStore } from '@easyflow/stores';

import { ElButton, ElMessage, ElUpload } from 'element-plus';

import { $t } from '#/locales';
import {
  normalizeUploadError,
  resolveUploadPath,
} from '#/utils/upload-response';

const props = defineProps({
  action: {
    type: String,
    default: '/api/v1/commons/upload',
  },
  tips: {
    type: String,
    default: '',
  },
  limit: {
    type: Number,
    default: 1,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits([
  'success', // 文件上传成功
  'error',
  'handleDelete',
  'handlePreview',
  'beforeUpload',
]);

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

const accessStore = useAccessStore();
const headers = ref({
  'easyflow-token': accessStore.accessToken,
});
const fileList = ref<UploadUserFile[]>([]);

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  emit('beforeUpload', rawFile);
};
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  emit('handleDelete', file, uploadFiles);
};
const handleSuccess: UploadProps['onSuccess'] = (response) => {
  try {
    emit('success', resolveUploadPath(response));
  } catch (error) {
    const normalizedError = normalizeUploadError(error);
    ElMessage.error(normalizedError.message);
    emit('error', normalizedError);
  }
};
const handleError: UploadProps['onError'] = (error) => {
  const normalizedError = normalizeUploadError(error);
  ElMessage.error(normalizedError.message);
  emit('error', normalizedError);
};
</script>

<template>
  <ElUpload
    v-model:file-list="fileList"
    class="upload-demo"
    :headers="headers"
    :action="`${apiURL}${props.action}`"
    :multiple="props.multiple"
    :before-upload="beforeUpload"
    :on-remove="handleRemove"
    :limit="props.limit"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <ElButton type="primary">{{ $t('button.upload') }}</ElButton>
  </ElUpload>
</template>
