<template>
	<el-upload
		action="#"
		class="upload"
		:limit="parameter.limit"
		:show-file-list="false"
		:http-request="uploadExcel"
		:before-upload="beforeExcelUpload"
		:on-exceed="handleExceed"
		:on-success="excelUploadSuccess"
		:on-error="excelUploadError"
		:accept="parameter.fileType!.join(',')"
	>
		<slot name="default">
			<div class="el-upload__title ml10">{{ parameter.title || '选择文件' }}</div>
		</slot>
	</el-upload>
</template>
<script setup lang="tsx" name="importUpload">
import { ref } from 'vue';
import { ElNotification, UploadRequestOptions, UploadRawFile } from 'element-plus';

export interface ExcelParameterProps {
	title: string; // 标题
	fileSize?: number; // 上传文件的大小
	fileType?: any[]; // 上传文件的类型
	limit?: number; // 上传文件的个数
	params?: {}; // 上传文件的参数
	importApi?: (params: any) => Promise<any>; // 批量导入的Api
}

// 父组件传过来的参数
const parameter = ref<ExcelParameterProps>({
	title: '门店导入',
	limit: 1,
	fileSize: 5,
	fileType: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
	params: {},
});

// 定义父组件传过来的值
const props = defineProps({
	title: {
		type: String,
		default: '',
	},
	importApi: {
		type: Function,
		default: (params: any) => Promise<any>,
	},
	limit: {
		type: Number,
		default: 1,
	},
	fileSize: {
		type: Number,
		default: 5,
	},
	fileType: {
		type: String,
		default: () => ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
	},
	params: {
		type: Object,
		default: () => ({}),
	},
	reLoad: {
		type: Function,
		default: () => {},
	},
});

// 文件上传
const uploadExcel = async (param: UploadRequestOptions) => {
	let excelFormData = new FormData();
	excelFormData.append('file', param.file);
	props.params &&
		Object.keys(props.params).map((item: any) => {
			excelFormData.append(item, props.params[item]);
		});
	const res = await props.importApi!(excelFormData);
	if (props.reLoad) {
		props.reLoad();
	}
};

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = (file: UploadRawFile) => {
	const isExcel = props.fileType!.includes(file.type as File.ExcelMimeType);
	const fileSize = file.size / 1024 / 1024 < props.fileSize!;
	if (!isExcel)
		ElNotification({
			title: '温馨提示',
			message: '上传文件只能是 xls / xlsx 格式！',
			type: 'warning',
		});
	if (!fileSize)
		setTimeout(() => {
			ElNotification({
				title: '温馨提示',
				message: `上传文件大小不能超过 ${props.fileSize}MB！`,
				type: 'warning',
			});
		}, 0);
	return isExcel && fileSize;
};

// 文件数超出提示
const handleExceed = () => {
	ElNotification({
		title: '温馨提示',
		message: '最多只能上传一个文件！',
		type: 'warning',
	});
};

// 上传错误提示
const excelUploadError = () => {
	ElNotification({
		title: '温馨提示',
		message: `批量添加${props.title}失败，请您重新上传！`,
		type: 'error',
	});
};

// 上传成功提示
const excelUploadSuccess = (response: any) => {
	ElNotification({
		title: '温馨提示',
		message: `批量添加${props.title}成功！`,
		type: 'success',
	});
};
</script>
