<template>
	<div class="upload-container w100">
		<el-upload
			class="upload-demo w100"
			v-model:file-list="infoList"
			:action="props.actionUrl"
			:limit="props.limit"
			:disabled="props.disabled"
			:auto-upload="props.autoUpload"
			:multiple="props.multiple"
			:accept="props.accept"
			:on-exceed="handleExceed"
			:http-request="httpRequest"
			:on-change="handleChange"
			ref="uploadListRef"
		>
			<el-button> <SvgIcon name="ele-Upload" /> 上传附件 </el-button>
			<slot> </slot>
			<template #file="{ file }">
				<div class="el-upload-list__item-info" @click="handlePictureCardPreview(file)">
					<a class="el-upload-list__item-name">
						<SvgIcon class="mr5" :name="fileType(checkFile(file.name))" size="14px" />
						<span class="el-upload-list__item-file-name" :title="file.name">{{ file.name }}</span>
					</a>
				</div>
				<SvgIcon name="ele-Close" class="el-icon--close" size="14px" title="删除文件" @click="handleRemove(file)" />
			</template>
		</el-upload>
	</div>
</template>

<script setup lang="ts">
/**
 * @desc 封装 element UI el-upload
 * @param {fileLists} [v-model] - 双向绑定的值
 * @param {Number} [limit] [v-bind]- 上传个数限制
 * @param {String} [accept] [v-bind]- 上传后缀的限制
 * @param {disabled} [Boolean] [v-bind]- 是否禁用
 * @example <UpLoad :limit='1' v-model:fileLists='ruleForm.fileLists' accept='image/png,image/jpg'/>
 */
import { ref, onMounted } from 'vue';
import { checkFile, fileType } from '/@/utils/tools';
import type { UploadUserFile } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
// import { uploadUrl } from '/@/utils/appConfig';
const props = defineProps({
	limit: {
		type: Number,
	},
	accept: {
		type: String,
		default: '',
	},
	fileList: {
		type: Array,
		default: <EmptyArrayType>[],
		required: true,
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	multiple: {
		type: Boolean,
		default: false,
	},
	actionUrl: {
		type: String,
		default: 'https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15',
	},
	autoUpload: {
		type: Boolean,
		default: true,
	},
	// 大小限制(MB)
	fileSize: {
		type: Number,
		default: 10,
	},
});

const infoList = ref(<EmptyArrayType>[]);
const emit = defineEmits(['update:fileList']);
const uploadListRef = ref<RefType>();
onMounted(() => {
	infoList.value = props.fileList || [];
});
// 删除
const handleRemove = (uploadFile: UploadUserFile) => {
	ElMessageBox.confirm(`确定要删除？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			// infoList.value.forEach((v: any, i: any) => {
			// 	if (v.uid == uploadFile.uid) {
			// 		infoList.value.splice(i, 1);
			// 	}
			// });
			uploadListRef.value.handleRemove(uploadFile);
			emit('update:fileList', infoList.value);
		})
		.catch(() => {});
};
// 预览文件
const handlePictureCardPreview = (uploadFile: UploadUserFile) => {
	console.log(uploadFile, '121');
};
// 上传
const httpRequest = async (params: any) => {
	const file = params.file;
	// 文件名(8位随机数)：zokcutz4.jpg
	const fileName = Math.random().toString(36).substr(-8) + file.name.substr(file.name.lastIndexOf('.'));

	// 目录加文件名【上线前修改目录名】
	const fileSrc = `test20220824/${fileName}`;
	console.log(fileSrc);
	try {
		params.onProgress({ percent: 0 });
		//上传的自定义逻辑都在这里

		infoList.value = [
			...infoList.value,
			
		];
		// console.log(`上传成功 ${res.key}`)
		console.log(infoList.value)
		emit('update:fileList', infoList.value);
		params.onSuccess();
	} catch (err) {
		console.log(err, 'err');

		ElMessage.error('网络错误，请稍后重试');
		params.onError();
	}
};
//文件限制
const handleExceed = (files: any, fileList: any) => {
	ElMessage.warning(`当前限制选择 ${props.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};
//上传前的校验
const handleChange = (rawFile: any) => {
	const isLt = rawFile.size / 1024 / 1024 < props.fileSize;
	if (!isLt) {
		ElMessage.warning(`文件超过了最大限度 ${props.fileSize} MB!`);
		infoList.value = infoList.value.slice(0, infoList.value.length - 1);
		return;
	}
};
</script>

<style scoped lang="scss">
.upload-container {
	.upload-demo {
		:deep(.el-upload-list) {
			display: flex;
			flex-wrap: wrap;
			.el-upload-list__item {
				width: calc(25% - 10px);
				border: var(--el-border);
				margin-right: 10px;
			}
		}
	}
}
</style>
