<template>
    <el-upload ref="uploadRef" v-model:file-list="fileList" :action="uploadUrl" :headers="headers" :list-type="listType"
        :multiple="multiple" :limit="limit" :on-exceed="handleExceed" :on-change="handleChange"
        :on-progress="handleProgress" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload"
        :accept="accept" :disabled="disabled">
        <el-icon>
            <Plus />
        </el-icon>
        <template v-slot:tip>
            <div v-if="tip">{{ tip }}</div>
        </template>
    </el-upload>
</template>

<script setup>
import { ref } from 'vue';
import userStore from '@/utils/useStorage.js'
import { ElUpload, ElMessage } from 'element-plus';


const fileList = ref([])

// 定义接收的外部属性
const props = defineProps({
    uploadUrl: {
        type: String,
        default: import.meta.env.MODE == 'development' ? '/api/account/admin/common/upload' : import.meta.env.VITE_API_URL + '/account/admin/common/upload',
    },
    headers: {
        type: Object,
        default: () => ({
            token: userStore.get('token'),
            shopId: userStore.get('shopInfo').id,
            clientType: 'pc'
        }),
    },
    listType: {
        type: String,
        default: 'picture-card',
    },
    multiple: {
        type: Boolean,
        default: false,
    },
    limit: {
        type: Number,
        default: 1,
    },
    tip: {
        type: String,
        default: '',
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    accept: {
        type: String,
        default: 'image/jpeg,image/png,image/gif',
    },
});

const emits = defineEmits(['success'])

// 内部引用上传组件实例
const uploadRef = ref(null);

// 处理文件超出数量限制的情况
const handleExceed = (files, fileList) => {
    ElMessage.warning(`超出最大允许上传图片数量：${props.limit}`);
};

// 处理文件状态改变
const handleChange = (file, fileList) => {
    console.log('图片文件状态改变', file, fileList);
};

// 处理上传进度
const handleProgress = (event, file, fileList) => {
    console.log('图片上传进度', event.percent);
};

// 处理上传成功
const handleSuccess = (response, file, fileList) => {
    ElMessage.success('图片上传成功');
    console.log('图片上传成功响应', response);
    emits('success', response.data)
};

// 处理上传失败
const handleError = (error, file, fileList) => {
    ElMessage.error('图片上传失败');
    console.error('图片上传失败原因', error);
};

// 上传前校验，这里主要校验图片格式
const beforeUpload = (file) => {
    const isImage = props.accept.split(',').some(format => file.type === format.trim());
    if (!isImage) {
        ElMessage.error('请选择正确格式的图片文件');
        return false;
    }
    return true;
};

function init(arr = []) {
    fileList.value = arr
}

defineExpose({
    init
})
</script>