<template>
	<view class="imgs">
		<button class="btn" @click="choose()" v-if="!read">
			<text class="icon">&#xe658;</text>
			<text class="text">选择上传</text>
		</button>
		<view class="files omit" v-for="(item, index) in value" :key="index" @click="preview(item)">
			<view class="file omit">{{ index + 1 }}, {{ item.url }}</view>
			<view class="type">{{ item.type.toLowerCase() }}</view>
			<view class="look" v-if="read">查看</view>
			<view class="del" v-else @click.stop="del(item)">删除</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'images',
	props: {
		value: {
			type: Array
		},
		read: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			show: false,
			ip: this.http.ip,
			list: this.value,
			item: {},
			actions: [{ name: '图片' }, { name: '视频' }]
		};
	},
	methods: {
		getType(name) {
			return name.substring(name.lastIndexOf('.') + 1);
		},
		choose() {
			if (this.value.length >= 5) {
				uni.showModal({ content: '最多只能上传5个附件', showCancel: false });
				return;
			}
			uni.chooseFile({
				count: 5,
				success: e => {
					console.log('asd:' + JSON.stringify(e));
					e.tempFilePaths.forEach((item, index) => {
						uni.showLoading({ title: '正在上传...', mask: true });
						uni.uploadFile({
							url: this.http.urls.upload,
							filePath: item,
							name: 'file',
							header: { Authorization: this.getUser().token },
							success: res => {
								uni.hideLoading();
								let data = JSON.parse(res.data);
								if (data.code == 200) {
									if (this.value.length < 5) {
										this.value.push({ url: data.fileName, type: data.fileName.substring(data.fileName.lastIndexOf('.') + 1) });
										this.$forceUpdate();
										this.$emit('input', this.value);
									} else {
										uni.showModal({ content: '最多只能上传5个附件', showCancel: false });
									}
								} else {
									uni.showModal({ content: data.msg, showCancel: false });
								}
							},
							fail: res => {
								uni.hideLoading();
								uni.showModal({ content: '图片上传失败', showCancel: false });
							}
						});
					});
				}
			});
		},
		//预览资源
		preview(item) {
			if (item.type.toLowerCase() == 'jpg' || item.type.toLowerCase() == 'png') {
				uni.previewImage({
					urls: [this.ip + item.url]
				});
			}
			if (item.type.toLowerCase() == 'mp4') {
				this.item = item;
				this.show = true;
			}
		},
		del(item) {
			this.value.splice(this.value.indexOf(item), 1);
		}
	}
};
</script>

<style lang="scss" scoped>
.imgs {
	margin-top: -15px;
	.btn {
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0);
		border-radius: 5px;
		color: #656363;
		.icon {
			padding-right: 5px;
		}
		margin-bottom: 10px;
	}
}
.popup_xz {
	overflow: hidden;
	._video {
		width: 100%;
	}
}
</style>
