<script setup lang="ts">
/**
 * @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';

const { data } = BtnPermissionStore();

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

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

function hasPermission(permissions: string | string[]): boolean {
	if (typeof permissions === 'string') {
		return data.includes(permissions);
	} else if (Array.isArray(permissions)) {
		return permissions.every((permission) => data.includes(permission));
	}
	return false;
}

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

<style scoped></style>
