<template>
	<view @click="selectAndUpload()">
		<slot></slot>
	</view>
</template>

<script setup>
	import { ref, computed } from "vue";
	import config from "@/common/config/index.js";

	const props = defineProps({
		maxCount:{
			type: Number,
			default: 1
		},
		maxSize: {
			type: Number,
			default: 5*1024*1024
		},
		sourceType:{
			type: String,
			default: 'album'
		},
		onBefore: {
			type: Function,
			default: null
		},
		onSuccess: {
			type: Function,
			default: null
		},
		onError: {
			type: Function,
			default: null
		}
	})
	function  selectAndUpload() {
		uni.chooseImage({
			count: props.maxCount, //最多可以选择的图片张数，默认9
			sourceType: [props.sourceType], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
			sizeType: ['original'], //original 原图，compressed 压缩图，默认二者都有
			success: (res) => {
				res.tempFiles.forEach((file) => {
					// 校验大小
					if (props.maxSize && file.size > props.maxSize) {
						uni.showToast({
							icon: "none",
							title: `文件大小不能超过 ${fileSizeStr.value}!`,
						});
						emits("fail", file);
						return;
					}

					if (!props.onBefore || props.onBefore(file)) {
						// 调用上传图片的接口
						uploadImage(file);
					}
				})
			}
		})
	}
	function  uploadImage(file) {
		uni.uploadFile({
			url: config.IM_BASE_URL + '/image/upload',
			header: {
				accessToken: uni.getStorageSync("loginInfo").accessToken
			},
			filePath: file.path, // 要上传文件资源的路径
			name: 'file',
			success: (res) => {
				let data = JSON.parse(res.data);
				if(data.code != 200){
					props.onError && props.onError(file, data);
				}else{
					props.onSuccess && props.onSuccess(file, data);
				}
			},
			fail: (err) => {
				console.log(err);
				props.onError && props.onError(file, err);
			}
		})
	}
	const  fileSizeStr = computed(() => {
		if (props.maxSize > 1024 * 1024) {
			return Math.round(props.maxSize / 1024 / 1024) + "M";
		}
		if (props.maxSize > 1024) {
			return Math.round(props.maxSize / 1024) + "KB";
		}
		return props.maxSize + "B";
	})
</script>

<style>
</style>