<template>
	<u-upload v-bind="$attrs" :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :notFile="notFile"
		:disabled="disabled">
	</u-upload>
	<view class="tips" v-if="tips">{{tips}}</view>
</template>

<script setup name="cyUpload">
	import {
		watch,
		ref
	} from 'vue';
	import baseUrl from '@/config/request.js';
	const emit = defineEmits(['update:filename', 'update:keyValue', 'success','update:loading'])

	const props = defineProps({
		filename: {
			type: [Array, String],
			default: () => []
		},
		url: {
			type: String
		},
		notFile: {
			type: Boolean,
			default: false
		},
		tips: {
			type: String
		},
		disabled: {
			type: Boolean,
			default: false
		},
		isUpdate: {
			type: Boolean,
			default: false
		},
        loading:{
            type:Boolean,
            default:false
        }
	})
	const fileList = ref([])

	watch(() => props.filename, (filename) => {
		if (!filename) return fileList.value = []
		if (typeof filename == 'string') {
			fileList.value = filename.split(',').map(v => ({
				url: baseUrl + v,
			}))
		} else {
			fileList.value = filename && filename.length > 0 ? filename.map(v => ({
				url: v.url || v,
			})) : []
		}
	}, {
		immediate: true,
		deep: true
	})

	const afterRead = async (e) => {
		const {
			file
		} = e
		fileList.value.push({
			...file,
			status: 'uploading',
			message: '上传中...',
		});
        emit('update:loading',true)
		const result = await uploadFilePromise(file.url);
		console.log(result, 'result')

		fileList.value.forEach((v,index) => {
			if(index == fileList.value.length - 1){
				v.url = result.url
				v.status = 'success'
				v.message = ''
			}
		})
		console.log(fileList.value, 'fileList.value')
		//更新外部参数
		emit('update:filename', fileList.value.map(v => v.url))
		emit('success', result)
        emit('update:loading',false)
	}

	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
	}

	const uploadFilePromise = (url, baseStr = '/app/common/upload') => {
		let token = uni.getStorageSync('token')
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: baseUrl + baseStr, // 图片上传地址
				filePath: url,
				name: 'file',
				header: {
					"Authorization": token
				},
				success: (res) => {
					let respic = JSON.parse(res.data)
					resolve(respic)
				},
			});
		});
	};
</script>

<style lang="scss" scoped>
	.tips {
		font-size: 24rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: #969696;
		line-height: 48rpx;
		margin-top: 10rpx;
	}

	::v-deep .align-right .u-upload__wrap {
		justify-content: flex-end;
	}
</style>