<script setup>
import { HORIZONTAL, VERTICAL, MetroWidget, useFocusHub } from "jsview";
import { shallowRef } from "vue";
import Item from "./Item.vue";

const props = defineProps({
  data: Object,
  onItemEdge: Function,
  onAction: Object,
});
const focusHub = useFocusHub();
const mwRef = shallowRef(null);

const measures = (item) => {
  return item;
};
const randomColor = () => {
  let randomColor = Math.round(Math.random() * 2 ** 24).toString(16);
  return (
    "#" + new Array(6 - randomColor.length).fill("0").join("") + randomColor
  );
};
const provideData = () => {
  const data = [];
  for (let i = 0; i < 42; i++) {
    data.push({
      width: 100,
      height: 90,
      marginRight: 10,
      marginBottom: 10,
      content: i,
      color: randomColor(),
    });
  }
  return data;
};
const onFocus = (rect) => {
  /** 重要代码: 参数rect为父MetroWidget传递的, 焦点过来的区域
   *  因此需要调用setEnterFocusRect来设置焦点进入区域, 以寻找最近的焦点
   */
  mwRef.value?.setEnterFocusRect(rect);
  focusHub.setFocus(props.data.name);
};
const onBlur = () => {
  //onBlur时需要返还焦点给父MetroWidget
  focusHub.returnFocusToParent();
};

props.onAction.register("onFocus", onFocus);
props.onAction.register("onBlur", onBlur);

const onScroll = () => {
  console.log("testtest on scroll", props.name);
};
</script>

<template>
  <div
    :style="{
      width: 900,
      height: 50,
      fontSize: 30,
      color: '#FFFFFF',
    }"
  >
    {{ data.name }}
  </div>
  <!-- 重要代码: sendFocusRectEvent可以让MetroWidget的item在获焦时发送事件, 通知父的MetroWidget进行滚动 -->
  <!-- 重要代码: onItemEdge直接作为onEdge回调, 既子MetroWidget到达边缘时触发父的onItemEdge -->
  <metro-widget
    ref="mwRef"
    :onScroll="onScroll"
    :name="data.name"
    :top="30"
    :width="data.width"
    :height="data.height"
    :provideData="provideData"
    :direction="VERTICAL"
    :padding="{
      left: 30,
      right: 30,
      top: 10,
      bottom: 10,
    }"
    :measures="measures"
    :onEdge="onItemEdge"
    :sendFocusRectEvent="false"
    :enableItemRenderBreak="true"
    :placeHolderSetting="{
      backgroundColor: 'rgba(78,105,127, 0.8)',
      focusBackgroundColor: '#770088aa',
      borderRadius: 10,
      gap: 10,
    }"
    :keepTraceRange="2"
  >
    <template #renderItem="{ data, onAction }">
      <item :data="data" :onAction="onAction" :pre="props.data.name" />
    </template>
  </metro-widget>
</template>
