<template>
	<view class="upload-index">
		<uv-upload :fileList="fileList" name="1" multiple :maxCount="type === 'insert' ? 5 : list.length"
			:deletable="type === 'insert'" @afterRead="afterRead" @delete="deletePic">
		</uv-upload>
	</view>
</template>

<script>
	import config from "@/config";
	export default {
		name: "preview",
		props: {
			list: {
				type: Array,
				default: () => {
					return []
				}
			},
			type: {
				type: String,
				default: 'preview'
			},
		},
		data() {
			return {
				fileList: []
			};
		},
		created() {
			this.fileList = this.list;
		},
		methods: {
			// 删除图片
			deletePic(event) {
				uni.showModal({
					title: '有极提示',
					content: '是否删除该附件',
					success: res => {
						if (res.confirm) {
							this.fileList.splice(event.index, 1)
						}
					}
				});

			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length;
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					console.log(lists[i]);
					const result = await this.uploadFilePromise(lists[i].url)
					console.log(result);
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.node.url,
						id: result.id,
						name: result.name
					}))
					console.log(this.fileList);
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/file/filenode/-1', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'uploadFile',
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).data)
							}, 1000)
						}
					});
				})
			},
			getFile() {
				return this.fileList.map(res => {
					return {
						id: res.id,
						name: res.name,
						url: res.url,
						type: res.type
					}
				})
			}
		}
	}
</script>

<style>

</style>