<template>
	<div class="spec-preview">
		<!-- <img :src="Objimg.imgUrl" /> -->
		<!-- ../images/s1.png -->
		<!-- 小图片 -->
		<img :src="Objimg.imgUrl" alt="" ref="smallimg" />

		<!-- 写逻辑事件的地方 -->
		<!-- css样式是图片大小即可拉  z-index放在前 并是绝对定位-->
		<div class="event" @mousemove="maskyidong"></div>

		<!-- 大图片 -->
		<div class="big" ref="bigbox">
			<!-- <img :src="Objimg.imgUrl" /> -->
			<img :src="Objimg.imgUrl" alt="" ref="bigimg" />
		</div>

		<!-- 绿色遮罩层 -->
		<div class="mask" ref="maxk"></div>
	</div>
</template>

<script>
export default {
	name: 'Zoom',
	props: ['skuImageList'],
	methods: {
		maskyidong(e) {
			console.log(e.offsetX,e.pageX);
			let mask = this.$refs.maxk
			let smallimg = this.$refs.smallimg
			let bigimg = this.$refs.bigimg
			let bigbox = this.$refs.bigbox
			// 鼠标在盒子内的坐标
			let maskX = e.offsetX - mask.offsetWidth / 2
			let maskY = e.offsetY - mask.offsetHeight / 2
			if (maskX <= 0) {
				maskX = 0
			}
			if (maskX >= smallimg.offsetWidth - mask.offsetWidth) {
				maskX = smallimg.offsetWidth - mask.offsetWidth
			}
			if (maskY <= 0) {
				maskY = 0
			}
			if (maskY >= smallimg.offsetHeight - mask.offsetHeight) {
				maskY = smallimg.offsetHeight - mask.offsetHeight
			}
			mask.style.left = maskX + 'px'
			mask.style.top = maskY + 'px'

			// 大图片跟着移动 是成比例关系的
			// 大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层的最大移动距离
			let imgUrlMax = bigimg.offsetWidth - bigbox.offsetWidth //大图片最大移动距离
			let MaskMax = smallimg.offsetWidth - mask.offsetWidth
			let imgUrlyidongX = -(maskX * imgUrlMax) / MaskMax + 'px'
			let imgUrlyidongY = -(maskY * imgUrlMax) / MaskMax + 'px'
			bigimg.style.left=imgUrlyidongX
			bigimg.style.top=imgUrlyidongY
		}
	},
	data() {
		return {
			// 默认展示第一张
			currentindex: 0
		}
	},
	computed: {
		Objimg() {
			// 一旦this.currentindex就会重新进行计算
			return this.skuImageList[this.currentindex] || []
		}
	},
	mounted() {
		// 接收兄弟组件的索引,根据索引来展示图片
		// 因为imageList遍历的是全部图片
		// Zoom默认显示的是第一张
		this.$bus.$on('changeindex', (index) => {
			console.log(index)
			// 修改data
			this.currentindex = index
		})
	}
}
</script>

<style lang="less">
.spec-preview {
	position: relative;
	width: 400px;
	height: 400px;
	border: 1px solid #ccc;

	img {
		width: 100%;
		height: 100%;
	}

	.event {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 998;
	}

	.mask {
		width: 50%;
		height: 50%;
		background-color: rgba(0, 255, 0, 0.3);
		position: absolute;
		left: 0;
		top: 0;
		display: none;
	}

	.big {
		width: 100%;
		height: 100%;
		position: absolute;
		top: -1px;
		left: 100%;
		border: 1px solid #aaa;
		overflow: hidden;
		z-index: 998;
		display: none;
		background: white;

		img {
			width: 200%;
			max-width: 200%;
			height: 200%;
			position: absolute;
			left: 0;
			top: 0;
		}
	}

	.event:hover ~ .mask,
	.event:hover ~ .big {
		display: block;
	}
}
</style>
