<template>
	<view>
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="imgType == 'single' ? 1 : 99" :previewFullImage="true"></u-upload>
	</view>
</template>

<script>
// import Emitter from '@/uni_modules/uview-ui/libs/util/emitter.js';
export default {
	name: 'fa-upload-image',
	// mixins: [Emitter],
	props: {
		value: {
			type: String,
			default: ''
		},
		imgType: {
			type: String,
			default: 'single'
		},
		fileList: {
			type: Array,
			default() {
				return [];
			}
		}
	},
	created() {},
	data() {
		return {
			header: {},
			formdata: {},
			vuex_token: '',
			vuex_user: {}
		};
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this.fileList.splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			console.log(event);
			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++) {
				const result = await this.uploadFilePromise(lists[i].url);

				let item = this.fileList[fileListLen];
				this.fileList.splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
			console.log(this.fileList);
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let userToken = '';
				let auth = this.$db.get('auth');
				userToken = auth.token;

				let a = uni.uploadFile({
					url: this.$config.baseUrl + 'api/common/upload?token=' + userToken, // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',

					formData: {},
					success: (res) => {
						setTimeout(() => {
							console.log(res);
							resolve(JSON.parse(res.data).data.fullurl);
						}, 1000);
					}
				});
			});
		}
	}
};
</script>

<style lang="scss"></style>
