<!--
 * @Author: ChenChanghua
 * @Date: 2023-03-08 14:52:08
 * @Description: file content
-->
<script setup>
import { MetroWidget, HORIZONTAL, useFocusHub, EdgeDirection } from "jsview";
import ControlItem from "./ControlItem.vue";
import { ref } from "vue";

const widget = ref();
const props = defineProps({
  number: Number,
  widgetHandler: Object,
});

const focusHub = useFocusHub();

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 = [];
  const c = Math.ceil(props.number / 10);
  for (let i = 0; i < c; ++i) {
    data.push({
      width: 200,
      height: 50,
      marginRight: 10,
      color: randomColor(),
      content: i * 10 + "-" + Math.min((i + 1) * 10 - 1, props.number -1),
      start: i * 10,
      end: Math.min((i + 1) * 10 - 1, props.number - 1),
    });
  }
  return data;
};

const measures = (data) => {
  return {
    width: data.width,
    height: data.height,
    marginRight: data.marginRight,
    marginBottom: data.marginBottom,
  };
};

// callbacks
const onEdge = (edgeInfo) => {
  if (edgeInfo.direction == EdgeDirection.top) {
    focusHub.setFocus("mainMw");
  }
};

const onBlur = () => {
  if (!firstLock) {
    props.widgetHandler.widget.value?.setFocusId(targetFocus, false, false);
  }
  firstLock = false;
};

let targetFocus = 0;
const controlCallback = (data) => {
  if (firstLock) {
    firstLock = false;
    return;
  }
  props.widgetHandler.widget.value?.slideTo(data.start * 100);
  targetFocus = data.start;
};

let firstLock = false;
const setFocusId = (id) => {
  targetFocus = id;
  firstLock = true;
  widget.value.setEnterFocusId(Math.floor(id / 10));
};

defineExpose({
  setFocusId,
});
</script>

<template>
  <metro-widget
    ref="widget"
    name="myController"
    :left="50"
    :top="200"
    :width="1000"
    :height="50"
    :provideData="provideData"
    :direction="HORIZONTAL"
    :measures="measures"
    :onEdge="onEdge"
    :onBlur="onBlur"
  >
    <template #renderItem="{ data, onAction }">
      <control-item
        :data="data"
        :onAction="onAction"
        :controlCallback="controlCallback"
      />
    </template>
  </metro-widget>
</template>
