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

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

	const uploadHeaders = ref({
		"accessToken": uni.getStorageSync('loginInfo').accessToken
	})
	const props = defineProps({
		maxSize: {
			type: Number,
			default: 10*1024*1024
		},
		onBefore: {
			type: Function,
			default: null
		},
		onSuccess: {
			type: Function,
			default: null
		},
		onError: {
			type: Function,
			default: null
		}
	})
	const emits = defineEmits(['fail'])
	function selectAndUpload() {
		let chooseFile = uni.chooseFile || uni.chooseMessageFile;
		chooseFile({
			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)) {
						// 调用上传图片的接口
						uploadFile(file);
					}
				})
			}
		})
	}
	function  uploadFile(file) {
		uni.uploadFile({
			url: config.IM_BASE_URL + '/file/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) => {
				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>