<template>
	<u-upload
		@afterRead="afterRead"
		@delete="deletePic"
		accept="image"
		uploadIconColor="#999"
		v-bind="omit($attrs, ['disabled', 'maxCount', 'maxSize'])"
		:fileList="fileList"
		:deletable="!$attrs.disabled"
		:maxSize="10 * 1024 * 1024"
		:maxCount="$attrs.disabled ? fileList.length : $attrs.maxCount"
	/>
</template>

<script setup>
import { omit } from 'lodash-es'
const instance = getCurrentInstance()
const { $api } = instance.proxy
const emits = defineEmits(['update:modelValue'])
const props = defineProps({
	modelValue: {
		type: Array,
		default: () => []
	}
})
const fileList = ref(props.modelValue)
// 删除图片
const deletePic = (event) => {
	fileList.value.splice(event.index, 1)
	emits(
		'update:modelValue',
		fileList.value.map((item) => ({
			size: item.size,
			type: item.type,
			url: item.url
		}))
	)
}

// 新增图片
const afterRead = async (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	let lists = [].concat(event?.file || [])
	let fileListLen = fileList.value.length
	lists.map((item) => {
		fileList.value.push({
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	for (let i = 0; i < lists.length; i++) {
		let item = fileList.value[fileListLen]
		const result = await $api.uploadFile({
			name: 'file',
			filePath: lists[i].url
		})
		result.code === 200
			? fileList.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result.msg
			  })
			: fileList.value.splice(fileListLen, 1)
		fileListLen++
	}
	emits(
		'update:modelValue',
		fileList.value.map((item) => ({
			size: item.size,
			type: item.type,
			url: item.url
		}))
	)
}
</script>
<style lang="scss" scoped>
:deep {
	.u-upload__button {
		background-color: #f2f2f2;
		border-radius: 12rpx;
	}
	.u-icon__icon {
		font-size: 80rpx !important;
	}
}
</style>
