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

<script setup lang="ts">
interface Props {
	maxCount?: number;
	maxSize?: number;
	sourceType?: string;
	isPermanent?: boolean;
	thumbSize?: number;
	onBefore?: (file: any) => boolean;
	onSuccess?: (file: any, data: any) => void;
	onError?: (file: any, error: any) => void;
	action: string;
	token?: string;
}

interface UploadResponse {
	code: number;
	message: string;
	data?: any;
}

const props = withDefaults(defineProps<Props>(), {
	maxCount: 1,
	maxSize: 5 * 1024 * 1024,
	sourceType: 'album',
	isPermanent: false,
	thumbSize: 50
});

const selectAndUpload = () => {
	uni.chooseImage({
		count: props.maxCount,
		sourceType: [props.sourceType],
		sizeType: ['original'],
		success: (res: any) => {
			res.tempFiles.forEach((file: any) => {
				if (!props.onBefore || props.onBefore(file)) {
					// 调用上传图片的接口
					uploadImage(file);
				}
			});
		}
	});
};

const uploadImage = (file: any) => {
	let uploadUrl = props.action

	if (uploadUrl.indexOf('?') === -1) {
		uploadUrl += '?'
	}

	uploadUrl += `&isPermanent=${props.isPermanent}&thumbSize=${props.thumbSize}`

	uni.uploadFile({
		url: uploadUrl,
		header: {
			accessToken: props.token,
			authorization: `Bearer ${props.token}`
		},
		filePath: file.path,
		name: 'file',
		success: (res) => {
			const data: UploadResponse = JSON.parse(res.data);
			if (data.code !== 200) {
				uni.showToast({
					icon: "none",
					title: data.message,
				});
				props.onError?.(file, data);
			} else {
				props.onSuccess?.(file, data);
			}
		},
		fail: (err) => {
			console.log(err);
			props.onError?.(file, err);
		}
	});
};

// 暴露方法给父组件
// defineExpose({
// 	selectAndUpload
// });
</script>

<style></style>