<template>
	<view class="base-upload" @click="handleUpload">
		<slot>
			<view class="grid" hover-class="hover-active">
				<view class="icon"></view>
			</view>
		</slot>
	</view>
</template>

<script setup>
	import { computed, ref, unref } from 'vue';
	import  { uploadFile } from "./upload.js"
	const props = defineProps({
		value: { type: [String, Array], default: () => [] },
		// 最多上传数量
		limit: { type: Number, default: 1 },
		showList: { type: Boolean, default: false },
		sourceType: { type: String }, // camera 打开相机
		type: { type: String, default: 'default' }
	})
	const emit = defineEmits(['update:value', 'change'])
	
	const getImgList = computed({
		get: () => props.value,
		set: (val) => emit('update:value', val)
	})
	
	function handleUpload(){
		uni.chooseImage({
		  count: 1,
		  sizeType: ["original"],
		  extension: ["gif", "jpg", "jpeg", "png", "bmp", "webp"],
		  sourceType: props.sourceType ? [props.sourceType] : undefined,
		  success: res => {
		    const tempFiles = res.tempFiles;
		    const tempFilePaths = res.tempFilePaths;
		// console.log('上传 res', res)
		// return
		    if (tempFiles && tempFiles.length > 0) {
		      const fileItem = tempFiles[0];
		      const { size } = fileItem;
		      if (size / 1024 / 1024 > 8) {
		        uni.showToast({ icon: "none", mask: true, title: "文件需要8M以内" });
		      } else {
				// 上传方法
				uploadFile({
					type: props.type,
					filePath: tempFilePaths[0],
				}).then(url => {
					emit('change', url)
					if(props.limit>1){
						getImgList.value.push(url)
					}else{
						getImgList.value = url
					}
				})
		      }
		    }
		  },
		  fail: err => {
		    console.log("handelSelectFile-fail", err);
		  },
		});
	}
</script>

<style lang="scss" scoped>
	.base-upload{
		display: inline-block;
		.btn{ 
			width: 100%;
			height: 72rpx;
			border-radius: 8rpx;
			border: 1rpx solid #1677FF;
			color: #1677FF;
			font-size:  24rpx;
			background: #1677FF10;
			.img{
				width: 28rpx;
				height: 28rpx;
				margin-right: 12rpx;
			}
		}
		.grid{
			width: 118rpx;
			height: 118rpx;
			border-radius: 8rpx;
			background: #F7FAFC;
			position: relative;
			border: 2px solid #EBF1F5;
			&::after, &::before{
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				content: ' ';
				clear: both;
				display: block;
				background: #C0C5CA;
				border-radius: 3rpx;
			}
			&::after{
				width: 3rpx;
				height: 40rpx;
			}
			&::before{
				width: 40rpx;
				height: 3rpx;
			}
		}
	}
</style>