<template>
	<u-upload :disabled="readonly" :fileList="uplodFiles" @afterRead="afterRead" @delete="deletePic" name="1" multiple
		:maxCount="maxCount"></u-upload>
</template>

<script>
	import {
		getCache
	} from '@/utils/cache';
	import { uploadUrl } from '@/api/system';
	export default {
		name: "simpleUpload",
		props: {
			action: {
				type: String,
				required: false,
				default: uploadUrl,
			},
			headers: {
				type: Array,
				required: false,
				default: () => []
			},
			postData: {
				type: Object,
				required: false,
				default: () => ({})
			},
			fileList: {
				type: Array,
				required: false,
				default: () => [],
			},
			maxCount: {
				type: Number,
				required: false,
				default: 10,
			},

			readonly: {
				type: Boolean,
				required: false,
				default: false,
			}
		},
		data() {
			return {
				uplodFiles: this.fileList
			};
		},
		watch: {
			fileList(n, o) {
				this.uplodFiles = n
			}
		},
		methods: {
			async afterRead(event) {
				const tokenData = await getCache('token')
				const token = tokenData.data
				console.log('upload', event, this.uplodFiles, this.fileList);
				let lists = [].concat(event.file)
				lists.forEach(item => {
					this.uplodFiles.push({
						... item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for(let i = 0 ; i < this.uplodFiles.length; i ++) {
					const item = this.uplodFiles[i]
					if(item.status && item.status === 'uploading') {
						const res = await this.doUpload(item.url, token)
						const resData = JSON.parse(res.data)
						console.log(res);
						item.status = 'success'
						item.url = resData.data
						this.$set(this.uplodFiles, i, {
							... item
						})
					}
				}
				this.$emit('on-change', this.uplodFiles)
			},
			deletePic(event) {
				const url = event.file.url
				this.uplodFiles = this.uplodFiles.filter(d => d.url !== url)
				this.$emit('on-change', this.uplodFiles)
			},
			async doUpload(filePath, token) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.action,
						filePath: filePath,
						header: {
							token,
						},
						success: (res) => {
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			}
		}
	}
</script>

<style>

</style>