<template>
	<fix-base-style :styleSpacing="styleSpacing" :styleColor="styleColor" :position="position">
		<view class="fix-hot-image" :class="[`fix-hot-image-${index}`]">
			<image
				v-if="data.pic"
				mode="widthFix"
				:src="data.pic"
				class="img hot-image"
				@load="loadImage"
				@click="toPath"
			/>
			<view
				v-for="(item, index) in hot"
				:key="index"
				class="hot-item"
				:style="{
					width: `${item.relativeW}px`,
					height: `${item.relativeH}px`,
					top: `${item.relativeY}px`,
					left: `${item.relativeX}px`,
					zIndex: item.index,
				}"
				@click="hotJump(item)"
			>
			</view>
		</view>
	</fix-base-style>
</template>

<script lang="ts" name="fix-hot-image" setup>
import { type PropType, ref, nextTick, getCurrentInstance } from "vue";
import type { Form } from "../../types/form";
import { baseProps } from "../../hooks";
const { proxy }: any = getCurrentInstance();

const props = defineProps({
	data: {
		type: Object as PropType<Form.HotImage>,
		default: () => {
			return {
				pic: "",
				link: {},
				width: 0,
				height: 0,
				attr: [],
			};
		},
	},
	index: {
		type: Number,
		default: 0,
	},
	...baseProps,
});
const emits = defineEmits(["jump"]);

const hot = ref<Form.Hot[]>(props.data.attr);

function refreshHot() {
	nextTick(() => {
		uni.createSelectorQuery()
			// #ifndef MP-ALIPAY
			.in(proxy)
			// #endif
			.select(`.fix-hot-image-${props.index}`)
			.boundingClientRect((res: any) => {
				const { width, height } = res;

				// 调整等比例缩放位置 大小
				const scaleX = width / props.data.width;
				const scaleY = height / props.data.height;
				// 调整子元素属性
				hot.value = props.data.attr.map((element) => {
					element.relativeX = Math.floor(element.x * scaleX);
					element.relativeY = Math.floor(element.y * scaleY);
					element.relativeW = Math.floor(element.w * scaleX);
					element.relativeH = Math.floor(element.h * scaleY);
					return element;
				});
			})
			.exec();
	});
}

function loadImage(event: any) {
	refreshHot();
}

function hotJump(item: Form.Hot) {
	emits("jump", item.link);
}
function toPath() {
	const link = props.data.link;
	emits("jump", link);
}
</script>

<style lang="scss" scoped>
.fix-hot-image {
	box-sizing: border-box;
	overflow: hidden;
	position: relative;
	.img {
		width: 100%;
		max-width: 100%;
		vertical-align: middle;
	}
	.hot-item {
		position: absolute;
	}
}
</style>
