<script setup>
import Scroll from "./Scroll.vue";
import { ref, shallowRef, onMounted } from "vue";
import { useFocusHub } from "jsview";

const props = defineProps({
  step: Number,
  style: Object,
  scrollStyle: Object,
  scrollBlockStyle: Object,
  imageSrc: String,
});

const focusHub = useFocusHub();
const element = shallowRef(null);
const scrollY = ref(0);
const textY = ref(0);
const onAction = {
  onKeyDown: (ev) => {
    const valid =
      element.value &&
      element.value.clientHeight &&
      element.value.clientHeight > props.style.height;
    // let keyUsed = true;
    if (valid) {
      let text_y;
      switch (ev.keyCode) {
        case 38:
          if (textY.value !== 0) {
            text_y =
              textY.value + props.step >= 0 ? 0 : textY.value + props.step;
            (textY.value = text_y),
              (scrollY.value =
                (-text_y / (element.value.clientHeight - props.style.height)) *
                (props.scrollStyle.height - props.scrollBlockStyle.height));
          }
          break;
        case 40:
          if (textY.value !== props.style.height - element.value.clientHeight) {
            text_y =
              textY.value - props.step <=
              props.style.height - element.value.clientHeight
                ? props.style.height - element.value.clientHeight
                : textY.value - props.step;
            (textY.value = text_y),
              (scrollY.value =
                (-text_y / (element.value.clientHeight - props.style.height)) *
                (props.scrollStyle.height - props.scrollBlockStyle.height));
          } else {
            focusHub.setFocus("button");
          }
          break;
      }
    }
  },
  onFocus: () => {
    console.log("LongImageScroll getFocus");
  },
  onBlur: () => {
    console.log("LongImageScroll loseFocus");
  },
};

const onLoad = () => {
  // 图片加载完成的回调
  console.log("Image loaded!");
};

onMounted(() => {
  focusHub.setFocus("longImageScroll");
});
</script>


<template>
  <jsv-focus-block name="longImageScroll" :onAction="onAction">
    <div :style="{ overflow: 'hidden', ...style }">
      <img
        alt=""
        ref="element"
        :src="imageSrc"
        :style="{ top: textY, width: style.width }"
        :onLoad="onLoad"
      />
    </div>
    <Scroll
      :top="scrollY"
      :scrollStyle="scrollStyle"
      :scrollBlockStyle="scrollBlockStyle"
    />
  </jsv-focus-block>
</template>