<!--
 * @Author: ChenChanghua
 * @Date: 2023-03-09 16:27:38
 * @Description: file content
-->

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

const props = defineProps({
  data: Object,
  query: 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: 90,
      height: 90,
      marginRight: 10,
      marginBottom: 10,
      content: i,
      color: randomColor(),
    });
  }
  return data;
};
const onFocus = (rect) => {
  //获得焦点时需要做就近移动的处理, 因此需要通过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);
</script>

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