<script setup>
import { HORIZONTAL, 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 < 10; i++) {
    data.push({
      width: (i + props.data.index) % 2 == 0 ? 90 : 180,
      height: 90,
      marginRight: 10,
      marginBottom: 10,
      content: i,
      color: randomColor(),
    });
  }
  return data;
};
const onFocus = (rect) => {
  /** 重要代码: 参数rect为父MetroWidget传递的, 焦点过来的区域
   *  因此需要调用setEnterFocusRect来设置焦点进入区域, 以寻找最近的焦点
   */
  //多层嵌套时, EnterFocusRect需要根据子的信息设置
  if (rect) {
    let rectInfo = {
      x: 0,
      y: 0,
      width: 0,
      height: 0,
    };
    let curRect = rect;
    while (curRect) {
      let { x, y, width, height } = curRect.rect;
      rectInfo.x += x;
      rectInfo.y += y;
      rectInfo.width = width;
      rectInfo.height = height;
      curRect = curRect.childEdgeInfo;
    }
    mwRef.value?.setEnterFocusRect({
      direction: rect.direction,
      rect: rectInfo,
    });
  }

  // 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);
</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"
    :name="data.name"
    :top="50"
    :width="data.width"
    :height="data.height"
    :provideData="provideData"
    :direction="HORIZONTAL"
    :padding="{
      left: 30,
      right: 30,
      top: 10,
      bottom: 10,
    }"
    :measures="measures"
    :onEdge="onItemEdge"
    :sendFocusRectEvent="true"
  >
    <template #renderItem="{ data, onAction }">
      <item :data="data" :onAction="onAction" />
    </template>
  </metro-widget>
</template>
