<template>
	<view>
		<!-- 图片 -->
		<view class="" style="margin-top: 40rpx">
			<view class="" style="margin-bottom: 20rpx">巡查图片{{ uploadNumber + '/' + 9 }}</view>
			<view class="">
				<!-- 上传照片 -->
				<view style="margin-left: 56rpx">
					<u-upload
						width="200rpx"
						height="200rpx"
						:maxCount="9"
						:deletable="true"
						:fileList="fileList1"
						@afterRead="afterRead"
						@delete="deletePic"
						multiple
						name="1"
					></u-upload>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'SCimage',
	props: {
		fileList: {
			type: Array,
			default() {
				return [];
			}
		}
	},
	data() {
		return {
			// 上传的图片
			fileList1: []
		};
	},
	computed: {
		log() {
			// console.log(this.fileList, 'uuuu');
			return this.fileList;
		},
		uploadNumber() {
			this.fileList1 = this.fileList;
			return this.fileList1.length;
		}
	},
	methods: {
		async afterRead(event) {
			// console.log(event, '上传图片');
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map((item) => {
				this[`fileList${event.name}`].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${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
			// console.log(this[`fileList${event.name}`], 'jjjjj');

			this.$emit('childEvent', this[`fileList${event.name}`]);
		},
		// 删除图片
		deletePic(event) {
			console.log(event, 'event');
			this[`fileList${event.name}`].splice(event.index, 1);
			this.$emit('childEvent', this[`fileList${event.name}`]);
		},
		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,
					// url: '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></style>
