<template>
	<view class="upload">
		<view class="upload_1">
			<view class="list" v-for="(item, index) in list" :key="index">
				<image class="image" :src="item.url" @click="toView(index, item)"></image>
				<uni-icons class="del" type="close" size="30" color="#ff0000" @click="uplDel(index, item)"></uni-icons>
			</view>
			<view class="list" v-if="list && list.length < count" @tap="uplSuc()">
				<uni-icons class="add" type="plusempty" size="55" color="#ff0000"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			list: {
				type: Array,
			},
			name: {
				type: String,
			},
			count: {
				type: Number,
				default: 1,
			},
		},
		data() {
			return {};
		},
		methods: {
			uplSuc() {
				const that = this;
				let serverUrl = that.$config.serverUrl;
				uni.chooseImage({
					count: 1,
					sizeType: ["original", "compressed"],
					sourceType: ["album", "camera"],
					async success(chooseRes) {
						let file = JSON.parse(JSON.stringify(chooseRes.tempFilePaths));
						let res = await that.$apifile("files/test/upload", null, file[0]);
						res = JSON.parse(res);
						if (res.errcode == "0") {
							let data = {
								name: res.name,
								uri: res.uri,
								url: serverUrl + res.uri
							}
							that.$emit("uplSuc", {
								data: data,
								name: that.name,
							});
						} else {
							uni.showToast({
								title: '请求接口失败',
								icon: 'fail',
							});
						}
					},
				});
			},
			// 删除图片
			uplDel(index, e) {
				const that = this;
				let data = {
					file: e,
					index: index,
				}
				that.$emit("uplDel", {
					data: data,
					name: that.name,
				});
			},
			// 图片预览
			toView(index, e) {
				const that = this;
				uni.previewImage({
					current: index,
					urls: [e.url],
				});
			},
		},
	};
</script>

<style lang="scss">
	.upload {
		padding: 0 2vw;

		.upload_1 {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;

			.list {
				position: relative;
				width: 30vw;
				height: 28vw;
				text-align: center;
				margin: 0 3vw 2vw 0;
				border-radius: 5px;
				box-shadow: 0 0 2px #858585;

				.image {
					width: 100%;
					height: 100%;
					border-radius: 5px;
				}

				.add {
					position: relative;
					top: 20px;
				}

				.del {
					position: absolute;
					right: 0;
					top: 0;
				}
			}

			.list:nth-child(3n) {
				margin: 0 0 2vw 0;
			}
		}
	}
</style>
