<template>
	<view class="cell-pd">
		<view class="uni-uploader">
			<view class="uni-uploader-body">
				<view class="uni-uploader__files">
					<block v-for="(image,index) in imageList" :key="index">
						<view class="uni-uploader__file" style="position: relative;">
							<image mode="aspectFit" class="uni-uploader__img" :src="image" :data-src="image" ></image>
							<view @click="deleteImg(index)" style="position: absolute;right:0;top:0;">X</view>
						</view>
					</block>
					<view v-if="imageList.length != 3" class="uni-uploader__input-box deepHeight">
						<view class="uni-uploader__input" @tap="chooseImage"></view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data(){
			return{
				imageList:[],
				filelist:[],
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album','camera'], //从相册选择
				countIndex: 1,
				count: [0,1,2]
			}
		},
		onUnload() {
			    this.imageList = [],
				this.sourceTypeIndex = 2,
				this.sourceType =  ['album','camera'],
				this.sizeType = ['original', 'compressed'],
				this.countIndex = 1;
		},
		methods: {
			deleteImg(e) {
				let index = e;
				this.imageList.splice(index,1);
				this.filelist.splice(index,1);
				this.$emit("getImg", this.filelist);
			},
			chooseImage() {
				if (this.imageList.length === 3) {
					return;
				}
				uni.chooseImage({
					sourceType: this.sourceType,
					sizeType: this.sizeType,
					count: this.imageList.length + this.count[this.countIndex] > 3 ? 3 - this.imageList.length : this.count[this.countIndex],
					success: (res) => {
						const token = uni.getStorageSync('sessionId');
						this.imageList = this.imageList.concat(res.tempFilePaths);
						        console.log(res.tempFilePaths);
								uni.uploadFile({
						             url: 'https://www.qzaiwang.com/v2/upload/tmp',
						             filePath: res.tempFilePaths[0],
						             name: 'file',
									 header: {
									 'X-TOKEN' : token,
									 },
						             formData: {
						                 'user': 'test'
						             },
						            success: (uploadFileRes) => {
										console.log(uploadFileRes)
										let data = uploadFileRes.data;
										let newdata = JSON.parse(data);
										let url = newdata.data.file_name;
										let array = [];
										array.push({})
										array[0] = url;
										this.filelist = this.filelist.concat(array);
						                this.$emit("getImg", this.filelist);
						            }
						        });
					}
				})
			},
			
		}
	}
</script>

<style>
	.deepHeight {
		height: 108upx;
		width: 108upx;
	}
	.uni-uploader__file {
		width: 30%!important;
	}
</style>
