<template>
  <qm-dialog
    v-if="store.setting.uiSetting['minimap.modal']"
    top="10%"
    width="312px"
    height="400px"
    title="缩略图"
    @close="close"
  >
    <div
      v-if="imagesHtml && imagesHtml.length"
      class="mini-map-container"
      @click.stop="setScrollTo"
      v-html="imagesHtml"
    ></div>
    <div v-else>请关闭或重新打开</div>
  </qm-dialog>
</template>

<script setup lang="ts">
import { onBeforeUpdate, watch } from "vue";
import { store } from "@/store/store";

// 切换任务后，关闭缩略图
watch(
  () => store.currentTask,
  () => {
    close();
  }
);

let imagesHtml = $ref([]);

onBeforeUpdate(() => {
  const imgDom = document.querySelectorAll(
    ".mark-body-container .single-image-container > img"
  );
  if (!imgDom.length) {
    imagesHtml = "";
    return;
  }
  imagesHtml = "";
  imgDom.forEach((item) => {
    imagesHtml += item.outerHTML;
  });
});

const setScrollTo = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  const imgDom = document.querySelector(
    `.mark-body-container .single-image-container > img[src='${target.src}']`
  );

  const container = imgDom.parentElement?.parentElement as HTMLDivElement;
  const containerPos = container.getBoundingClientRect();
  const parent = imgDom.parentElement as HTMLDivElement;
  const parentPos = parent.getBoundingClientRect();
  // console.log(containerPos, parentPos);
  // 试验出来的... 大概就是2个顶部距离相减，得到相对距离
  const scrollToX =
    (e.offsetX + parentPos.x - containerPos.x) /
    parseFloat(getComputedStyle(container).width);
  const scrollToY =
    (e.offsetY + parentPos.y - containerPos.y) /
    parseFloat(getComputedStyle(container).height);
  if (typeof scrollToX === "number" && typeof scrollToY === "number") {
    store.minimapScrollToX = scrollToX;
    store.minimapScrollToY = scrollToY;
  }
};
const close = () => {
  store.setting.uiSetting["minimap.modal"] = false;
};
</script>

<style>
.mini-map-container img {
  display: block;
  padding: 5px;
  border: 1px solid #f0f0f0;
  cursor: pointer;
  margin-bottom: 10px;
}
.mini-map-container img:hover {
  border-color: #165dff;
}
</style>
