<template>
  <div ref="arbitrateImgRef" class="arbitrate-img" @scroll="onImgScroll">
    <img :src="imgUri" alt="扫描结果" @load="onImgLoad" />
  </div>
  <div ref="imgThumbRef" class="arbitrate-img-thumb">
    <img :src="imgUri" alt="扫描结果" />
    <div
      class="arbitrate-img-area"
      v-ele-move-directive.prevent.stop="{
        moveStart: moveAreaStart,
        moveElement: moveArea,
        moveStop: moveAreaStop,
      }"
      :style="areaStyle"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, reactive, onMounted } from "vue";
import { vEleMoveDirective } from "@/directives/eleMove";
import { getFileUrl } from "@/utils/tool";

defineOptions({
  name: "RecognizeImage",
});

const props = defineProps<{
  imgSrc: string;
}>();

const arbitrateImgRef = ref();

const imgUri = computed(() => {
  return getFileUrl(props.imgSrc);
});

// img
function updateImgAreaSize() {
  const imgBoxDom = arbitrateImgRef.value as HTMLDivElement;
  const imgDom = imgBoxDom.firstChild as HTMLImageElement;
  const { clientHeight } = imgThumbRef.value as HTMLDivElement;

  const areaRate = Math.min(imgBoxDom.clientHeight / imgDom.clientHeight, 1);
  const areaHeight = clientHeight * areaRate;
  areaSize.height = areaHeight;
}

function onImgLoad() {
  updateImgAreaSize();
}

let areaIsMoving = false;
function onImgScroll(e: Event) {
  if (areaIsMoving) {
    e.preventDefault();
    return;
  }

  const imgBoxDom = arbitrateImgRef.value as HTMLDivElement;
  const scrollTop = imgBoxDom.scrollTop;
  const imgDom = imgBoxDom.firstChild as HTMLImageElement;
  const { clientHeight } = imgThumbRef.value as HTMLDivElement;
  areaSize.top = (clientHeight * scrollTop) / imgDom.clientHeight;
}

// img-thumb area
const imgThumbRef = ref();
const areaSize = reactive({
  height: 40,
  top: 0,
});
const areaOriginTop = ref(0);

const areaStyle = computed(() => {
  return { height: `${areaSize.height}px`, top: `${areaSize.top}px` };
});
interface MovePos {
  left: number;
  top: number;
}

function moveAreaStart() {
  areaOriginTop.value = areaSize.top;
  areaIsMoving = false;
}
function moveArea(pos: MovePos) {
  areaIsMoving = true;
  const areaTop = pos.top + areaOriginTop.value;
  const { clientHeight } = imgThumbRef.value as HTMLDivElement;
  areaSize.top = Math.min(areaTop, clientHeight - areaSize.height);
  areaSize.top = Math.max(0, areaSize.top);

  const imgBoxDom = arbitrateImgRef.value as HTMLDivElement;
  const imgDom = imgBoxDom.firstChild as HTMLImageElement;
  imgBoxDom.scrollTop = (imgDom.clientHeight * areaSize.top) / clientHeight;
}

function moveAreaStop(pos: MovePos) {
  moveArea(pos);
  areaIsMoving = false;
}
</script>
