<template>
	<u-upload :name="name" 
		:width="width" :height="height" 
		:accept="accept" :fileList="fileList" 
		:multiple="multiple" :maxCount="maxCount" 
		@afterRead="afterRead" @delete="onDelete">
		<slot name="content" :data="fileList"></slot>
		
     <image
      v-if="customImg"
      src="@/static/discover/ic_upload.png"
      mode=""
      :style="{width: width + 'px', height: height + 'px'}"
    ></image>
	</u-upload>
</template>

<script>
import { baseUrl } from '@/common/config.js';
export default {
	name: "",
	props: {
		api: {
			type: String,
			default: '/common/upload'
		},
		name: {
			type: String,
			default: uni.$u.props.upload.name
		},
		accept: {
			type: String,
			default: 'image' // 默认接受图片
		},
		width: {
			type: [String, Number],
			default: uni.$u.props.upload.width
		},
		height: {
			type: [String, Number],
			default: uni.$u.props.upload.height
		},
        // 文件大小限制，单位为byte
		maxSize: {
			type: [String, Number],
            default: uni.$u.props.upload.maxSize
		},
		maxCount: {
			type: Number,
			default: 5
		},
		multiple: {
			type: Boolean,
			default: true
		},
		// 图片格式限制
		imageFormats: {
			type: Array,
			default: () => ['png', 'jpg', 'jpeg']
		},
		// 视频格式限制
		videoFormats: {
			type: Array,
			default: () => ['mp4', 'mov', 'mkv', 'wmv']
		},
		// 图片大小限制，单位为byte
		maxImageSize: {
			type: Number,
			default: 2 * 1024 * 1024 // 默认2MB
		},
		// 视频大小限制，单位为byte
		maxVideoSize: {
			type: Number,
			default: 50 * 1024 * 1024 // 默认50MB
		},
		customImg: {
			type: Boolean,
			default: false
		},
		fileList: {
			type: Array,
			default: []
		},
	},
	data() {
		return {
			//fileList: [],
		};
	},
	computed: {

	},
	mounted() {

	},
	beforeDestroy() {

	},
	methods: {
		// 上传后的处理函数
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList`].length;
			
			// 验证文件格式和大小
			for (let i = 0; i < lists.length; i++) {
				const file = lists[i];
				const fileName = file.name.split('/').pop();
				const fileExtension = fileName.split('.').pop().toLowerCase();
				
				// 根据文件扩展名判断是图片还是视频（优先使用扩展名判断）
				const isImage = this.imageFormats.includes(fileExtension);
				const isVideo = this.videoFormats.includes(fileExtension);
				
				if (isImage) {
					// 图片验证
					if (file.size && file.size > this.maxImageSize) {
						const maxSizeMB = (this.maxImageSize / 1024 / 1024).toFixed(1);
						uni.$u.toast(`图片大小不能超过 ${maxSizeMB}MB`);
						return;
					}
				} else if (isVideo) {
					// 视频验证
					if (file.size && file.size > this.maxVideoSize) {
						const maxSizeMB = (this.maxVideoSize / 1024 / 1024).toFixed(1);
						uni.$u.toast(`视频大小不能超过 ${maxSizeMB}MB`);
						return;
					}
				} else {
					// 既不是图片也不是视频，检查是否有file.type
					if (file.type) {
						if (file.type.startsWith('image/')) {
							// 是图片但扩展名不在允许列表中
							uni.$u.toast(`图片格式仅限 ${this.imageFormats.join(', ')}`);
							return;
						} else if (file.type.startsWith('video/')) {
							// 是视频但扩展名不在允许列表中
							uni.$u.toast(`视频格式仅限 ${this.videoFormats.join(', ')}`);
							return;
						}
					}
					// 无法判断类型或类型不支持
					uni.$u.toast('不支持的文件格式');
					return;
				}
			}
			
			lists.map((item) => {
				this[`fileList`].push({
					...item,
					status: "uploading",
					message: "上传中",
				});
			});
			// 无预览时，使用toast
			if (!this.$attrs.previewImage) {
				uni.showLoading({
					title: '上传中...'
				});
			}
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this[`fileList`][fileListLen];
				this[`fileList`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: "success",
						message: "",
						url: baseUrl + result,
					})
				);
				fileListLen++;
				// 无预览时，使用toast
				if (!this.$attrs.previewImage) {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: result.message || '上传完成',
						duration: 2000
					});
					this.$emit('complete');
				}
			}
			this.$emit('fileList', this.fileList);
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: baseUrl + this.api,
					name: "file",
					header: {
						'Authorization': `tf: ${uni.getStorageSync('access-token')}`
					},
					formData: {
						'biz': 'temp',
					},
					filePath: url,
					success: (res) => {
						let data = JSON.parse(res.data);
						if (data.code === 200) {
							resolve(data.fileName);
						} else {
							uni.$u.toast('上传失败');
							reject();
						}
					},
				});
			});
		},
		onDelete(event) {
			uni.showModal({
				title: '提示',
				content: '确定要删除？',
				cancelText: '取消',
				confirmText: '确定',
				success: res => {
					if (res.confirm) {
						this[`fileList`].splice(event.index, 1);
						this.$emit('fileList', this.fileList);
					}
				}
			})
		},
	}
}
</script>

<style lang="scss" scoped></style>