<script setup>
import { MetroWidget, VERTICAL, useFocusHub, METRO_WIDGET_CONST } from "jsview";
import WidgetItem from "./WidgetItem.vue";
import { onMounted, ref, shallowRef } from "vue";

const props = defineProps({
  data: Object,
  onAction: Object,
  onItemEdge: Function,
});

const focusHub = useFocusHub();
const mwWidget2 = ref(null);

const provideData = () => {
  const data = [];
  for (let i = 0; i < 1; i++) {
    data.push({
      width: 500,
      height: 170,
      name: "3级嵌套_" + i + props.data.index,
      marginBottom: 10,
      index: i,
    });
  }
  return data;
};

const measures = (item) => {
  return {
    width: item.width,
    height: item.height,
    marginRight: item.marginRight,
    marginBottom: item.marginBottom,
    itemSlide: METRO_WIDGET_CONST.ITEM_SLIDE.ACT_FOCUS_RECT_EVENT,
  };
};

onMounted(() => {});

const widgetRef = shallowRef();
const onFocus = (rect) => {
  if (rect) {
    //多层嵌套时需要将子的edge信息加上
    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;
    }
    widgetRef.value?.setEnterFocusRect({
      direction: rect.direction,
      rect: rectInfo,
    });
  }
  focusHub.setFocus("mwWidget2" + props.data.index);
};
const onWidgetEdge = (info) => {
  props.onItemEdge(info);
};

props.onAction.register("onFocus", onFocus);
</script>

<template>
  <metro-widget
    ref="widgetRef"
    :name="'mwWidget2' + props.data.index"
    :top="0"
    :left="0"
    :width="660"
    :height="600"
    :provideData="provideData"
    :padding="{ left: 30, right: 30 }"
    :direction="VERTICAL"
    :measures="measures"
    :onEdge="onWidgetEdge"
  >
    <!-- 重要代码: 为了实现焦点就近移动, 需要传递onItemEdge回调 -->
    <template #renderItem="{ data, onAction, onItemEdge }">
      <widget-item :data="data" :onAction="onAction" :onItemEdge="onItemEdge" />
    </template>
  </metro-widget>
</template>
