<template>
	<div>
		<el-upload
			:action="upload_host"
			:data="dataObj"
			:multiple="uploadNum > 1?true:false"
			:show-file-list="false"

			:before-upload="beforeUpload"
			:on-remove="handleRemove"
			:on-success="handleUploadSuccess"
			:on-preview="handlePreview"
			:disabled="!isDisabled"
			:class="name"
			class="avatar-uploader2"
		>
		</el-upload>
		<div class="images">
		  <div class="item" v-for="(item, index) in fileList" :key="index">
		    <div class="img" @mouseover="item.hover = true;" @mouseout="item.hover = false;">
		      <el-image @click.stop="handleClickItem" ref="img" v-if="isImageUrl(item.url)" :src="item.url" :preview-src-list="previewImages()" style="width: 120px; height: 120px" fit="cover"></el-image>
		      <video v-else :src="item.url" controls style="width: 120px; height: 120px; display: block"></video>
		      <div class="mask" v-show="item.hover">
		        <i class="el-icon-zoom-in" @click="previewImage(item.url)" v-if="isImageUrl(item.url)"></i>
		        <i class="el-icon-zoom-in" @click="previewVideo(item.url)" v-else></i>
		        <i class="el-icon-upload2" @click="uploadImage(item.url)" v-if="!isDisabled"></i>
		        <i class="el-icon-delete" @click="deleteImage(item.url)" v-if="!isDisabled"></i>
		      </div>
		    </div>
		  </div>
		  <div class="add" v-if="fileList.length < uploadNum" @click="uploadImage()"><i class="el-icon-plus"></i></div>
		</div>
		<!-- <el-dialog :visible.sync="dialogVisible" :append-to-body="true"><img width="100%" :src="showImage" alt="" /></el-dialog> -->
	</div>
</template>
<script>
import request from '@/utils/request';
import { findElem } from '@/utils/util'
export default {
	name: 'ImageUploadPhp',
	props: {
		isDisabled: Boolean,
		fileType: String,
		name: String,
		// fileList: Array,
		uploadNum: {
			type: Number,
			default: 1,
		},
		index: {
			type: Number,
			default: 0,
		},
	},
	data() {
		return {
			dataObj: {
				policy: '',
				signature: '',
				key: '',
				ossaccessKeyId: '',
			},
			aliosstoken: '',
			upload_host: '',
			showImage: '',
			dialogVisible: false,
			uploadImageId: '',
			fileList: [],
			list: []
		};
	},
	created() {
		request({
			url: '/qviKHUYsyN.php/index/getAliOssToken',
			method: 'get',
			params: {}
		}).then(res => {
			this.aliosstoken = res.data.aliosstoken;
			this.upload_host = res.data.upload_host
		});
	},
	computed: {
		showFileList: {
			get: function() {
				if (this.fileList.length > 0 && this.fileList[0].url) {
					return true;
				} else {
					return false;
				}
			},
			set: function(newValue) {}
		}
	},
	methods: {
		emitInput(val) {
			this.$emit('input', val);
		},
		handleClickItem(){
			// 获取遮罩层dom
			setTimeout(function(){
			  let domImageMask = document.querySelector(".el-image-viewer__wrapper");
			  if (!domImageMask) {
			    return;
			  }
			  domImageMask.addEventListener("click", (e) => {
			    if(e.target.parentNode.className == 'el-image-viewer__actions__inner') {
			      return;  //如果点击底部菜单，不关闭
			    }
			    // 点击遮罩层时调用关闭按钮的 click 事件
			    document.querySelector(".el-image-viewer__close").click();
			  });
			},300)
		},
		handleRemove(file, fileList) {
			if (fileList.length == 0) {
				this.fileList = [{ name: '', url: '' }];
				// this.showFileList = false;
			} else {
				this.fileList = fileList;
			}
		},
		handlePreview(file) {
			// const fileExtension = file.name.substring(file.name.lastIndexOf('.') + 1);
			// if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
			// 	this.showImage = file.url;
			// 	// this.showImage = file.full_url;
			// 	this.dialogVisible = true;
			// } else {
			// 	window.open(file.url);
			// 	// window.open(file.full_url);
			// }
		},
		getUUID() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
				return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
			});
		},
		beforeUpload(file) {
			if(this.fileType == 'image'){
				if(!file.type.includes('image')){
					return this.$message.warning('该选项只支持上传图片格式的文件！');
				}
			}else if(this.fileType == 'video'){
				if(!file.type.includes('video')){
					return this.$message.warning('该选项只支持上传视频格式的文件！');
				}
			}else if(this.fileType == 'image/video'){
				if(!file.type.includes('image') && !file.type.includes('video')){
					return this.$message.warning('该选项只支持上传视频或图片格式的文件！');
				}
			}
			
			this.list.push(file.name)
			if(this.list.length > this.uploadNum){
				this.$message.warning('最多上传' + this.uploadNum +'个文件!');
				return false
			}
			const that = this;
			return new Promise((resolve, reject) => {
				request({
					url: '/addons/alioss/index/params',
					method: 'post',
					data: {
						method: 'POST',
						md5: file.name.substring(0, file.name.indexOf('.')),
						name: file.name,
						type: file.type,
						size: file.size,
						aliosstoken: this.aliosstoken
					}
				})
					.then(res => {
						that.dataObj = res.data;
						resolve(true);
					})
					.catch(err => {
						reject(false);
					});
			});
		},
		handleUploadSuccess(res, file, fileList) {
			console.log(this.fileList)
			// if (this.fileList.length == 1 && !this.fileList[0].url) {
			// 	this.fileList.pop();
			// }
			// this.showFileList = true;
			this.fileList.push({
				name: file.name,
				hover: false,
				url: process.env.VUE_APP_BASE_API + 'qviKHUYsyN.php/index/getOssSign?object=' + this.dataObj.key.replace('${filename}', file.name)
			});
			
			this.$emit('editUrl', {
				name: file.name,
				hover: false,
				url: this.dataObj.key.replace('${filename}', file.name)
			},this.name,this.index);
			// this.fileList.push({
			// 	name: file.name,
			// 	url: this.dataObj.key.replace('${filename}', file.name),
			// 	full_url: process.env.VUE_APP_BASE_API + 'qviKHUYsyN.php/index/getOssSign?object=' + this.dataObj.key.replace('${filename}', file.name)
			// });
		},
		previewImages() {
		  let images = [];
		  if(this.fileList && this.fileList.length > 0) {
		    this.fileList.forEach(item => {
		      if(this.isImageUrl(item.url)) {
		        images.push(item.url);
		      }
		    })
		  }
		  return images;
		},
		// 预览图片
		previewImage(url) {
		  let images = [];
		  this.fileList.forEach(item => {
		    if(this.isImageUrl(item.url)) {
		      images.push(item);
		    }
		  })
		  let index = findElem(images, 'url', url);
		  this.$refs.img[index].showViewer = true;
		},
		// 预览视频
		previewVideo(url) {
		  // this.previewVideoUrl = url;
		  // this.previewVideoDialog = true;
		},
		isImageUrl(url) {
			const fileSuffix = url.substring(url.lastIndexOf(".") + 1);
			const whiteList = ['jpg', 'jpeg', 'png'];
			if (whiteList.indexOf(fileSuffix) === -1) {
				return false;
			}else {
				return true;
			}
		},
		uploadImage(id) {
		    this.list = []
		    this.uploadImageId = id;
		    document.querySelector(`.${this.name} input`).click();
		},
		// 删除图片
		deleteImage(url) {
		  let index = findElem(this.fileList, 'url', url);
		  this.fileList.splice(index, 1);
		},
	}
};
</script>
<style type="text/css" lang="scss">
	.images {
	  display: flex;
	  flex-wrap: wrap;
	  .item {
	    display: flex;
	    flex-direction: column;
	    justify-content: center;
	    align-items: center;
	    width: 120px;
	    margin-right: 20px;
	    .img {
	      border: 1px dashed #eaeaea;
	      border-radius: 5px;
	      overflow: hidden;
	      position: relative;
	      .el-image {
	        display: block;
	      }
	      .mask {
	        position: absolute;
	        left: 0;
	        top: 0;
	        width: 120px;
	        height: 120px;
	        background: rgba($color: #000000, $alpha: 0.3);
	        display: flex;
	        align-items: center;
	        justify-content: center;
	        i {
	          font-size: 20px;
	          color: #ffffff;
	          cursor: pointer;
	          margin: 0 8px;
	        }
	      }
	    }
	    .add {
	      border: 1px solid #dddddd;
	      border-radius: 5px;
	      cursor: pointer;
	    }
	    .text {
	      font-size: 14px;
	      color: #666666;
	    }
	  }
	  .add {
	    width: 120px;
	    height: 120px;
	    border: 1px solid #dddddd;
	    border-radius: 5px;
	    cursor: pointer;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    i {
	      font-size: 30px;
	      color: #999;
	    }
	  }
	}
	.avatar-uploader2 {
	  height: 0;
	}
</style>