<script setup>
import {
  HORIZONTAL,
  useFocusHub,
  getTextWidth,
  FixPositionSlide,
  ListWidget,
  SeamlessSlide,
  METRO_WIDGET_CONST
} from "jsview";
import FoldableItem from "./FoldableItem.vue";
import redCircle from "./assets/redCircle.png";
import { ref, provide, onMounted } from "vue";
import CreepFocus from "./CreepFocus.vue";

const randomColor = () => {
  let randomColor = Math.round(Math.random() * 2 ** 24).toString(16);
  return (
    "#" + new Array(6 - randomColor.length).fill("0").join("") + randomColor
  );
};
// const slideType = new FixPositionSlide();
const slideType = new SeamlessSlide({ startPercent: .5, endPercent: .5});

const focusHub = useFocusHub();

const creepFocus = ref(null);
const showFocus = ref(true);
let currentFocusRect = {};
let expandItemCount = 0;
const focusFrameController = {
  onFocusChange: (rect, focusIndex, doAnim) => {
    creepFocus.value?.changeRect(rect, doAnim);
    currentFocusRect = rect;
  },
  onItemSizeChange: (ifExpand) => {
    if (ifExpand) {
      expandItemCount++;
    } else {
      expandItemCount--;
    }
    if (expandItemCount <= 0) {
      showFocus.value = true;
      expandItemCount = 0;
    }  else {
      showFocus.value = false;
    }
  }
};
provide("focusFrameController", focusFrameController);

//<<<<<<< 创建数据
const contentData = [
  "推荐",
  "电视剧",
  "电影",
  "云影院",
  "综艺",
  "儿童",
  "动漫",
  "游戏",
  "纪录片",
  "体育",
  "知识",
  "导航",
];
const SizeObj = {
  fontSize: 40,
};
const data = [];
const getChildTabList = (textSize, childTextSize, contentText) => {
  const list = [];
  // 3-5个
  const number = Math.round(Math.random() * 2 + 3);
  for (let i = 0; i < number; ++i) {
    list.push({
      width: (i == number - 1 ? textSize : childTextSize) + 60,
      height: 65,
      marginRight: i == number - 1 ? 0 : 10,
      color: randomColor(),
      content: contentText + (i == number - 1 ? "" : "_" + i),
    });
  }
  return list;
};
for (let i = 0; i < 12; ++i) {
  const textSize = getTextWidth(contentData[i], SizeObj);
  const childTextSize = getTextWidth(contentData[i] + "_0", SizeObj);
  const childList = getChildTabList(textSize, childTextSize, contentData[i]);
  let totalWidth = 0;
  childList.forEach((item) => {
    totalWidth += item.width + item.marginRight;
  });
  const initFocus = Math.round(Math.random() * (childList.length - 1));

  data.push({
    width: textSize + 60,
    height: 65,
    color: randomColor(),
    content: contentData[i],
    marginRight: 10,
    name: "item_" + i, // focus name
    expandWhenFocus: contentData[i] == "云影院" || contentData[i] == "综艺",
    childTab: {
      width: totalWidth, //4个item + 3个gap
      list: childList,
    },
    initFocus,
  });
}
const provideData = () => {
  return data;
};
// >>>>>>

const getDetaileInfo = () => {
  let str = "";
  for (let item of data) {
    str += `${item.content}共有${item.childTab.list.length}个子tab, 展开后的默认焦点为${item.initFocus}\n`;
  }
  return str;
};

const measures = (item) => {
  return {
    width: item.width,
    height: item.height,
    marginRight: item.marginRight,
    itemSlide: item.expandWhenFocus ? METRO_WIDGET_CONST.ITEM_SLIDE.DISABLE : METRO_WIDGET_CONST.ITEM_SLIDE.ACT_ITEM_FOCUS
  };
};

const widgetRef = ref();
onMounted(() => {
  provide("parentWidget", widgetRef);
  focusHub.setFocus("myWidget");
});

const onFocusRectChange = () => {
  //展开时的滑动不需要更新焦点大小
  if (showFocus.value) {
    const curFocusIndex = widgetRef.value.getCurrentFocusIndex();
    const rect = widgetRef.value.getTemplatePosition(curFocusIndex);
    focusFrameController.onFocusChange(rect, curFocusIndex);
  }
};

const onAllResizeDone = () => {
  console.log("onAllResizeDone");
};
</script>

<template>
  <div :style="{ width: 1280, height: 720, backgroundColor: '#007788' }">
    <div
      :style="{
        textAlign: 'center',
        fontSize: 30,
        lineHeight: 50,
        color: '#ffffff',
        left: 140,
        top: 20,
        width: 1000,
        height: 50,
        backgroundColor: 'rgba(27,38,151,0.8)',
      }"
    >
      爬行样式的焦点示例
    </div>
    <list-widget
      ref="widgetRef"
      name="myWidget"
      :onFocusRectChange="onFocusRectChange"
      :onAllItemResizeDone="onAllResizeDone"
      :top="100"
      :left="40"
      :width="1200"
      :height="110"
      :slideSetting="slideType"
      :direction="HORIZONTAL"
      :provideData="provideData"
      :measures="measures"
      :padding="{ left: 20, right: 20, top: 20, height: 20 }"
    >
      <template #renderItem="{ data, onAction, query, onItemEdge }">
        <foldable-item
          :data="data"
          :onAction="onAction"
          :query="query"
          :onItemEdge="onItemEdge"
        />
      </template>
      <template #background>
        <creep-focus
          v-if="showFocus"
          ref="creepFocus"
          :imgUrl="redCircle"
          :initLeft="currentFocusRect?.left"
          :initTop="currentFocusRect?.top"
          :initWidth="currentFocusRect?.width"
          :initHeight="currentFocusRect?.height"
          id="main"
        >
        </creep-focus>
      </template>
    </list-widget>
  </div>

  <div
    :style="{
      left: 100,
      top: 250,
      width: 1280,
      height: 400,
      fontSize: 25,
      color: '#FFFFFF',
    }"
  >
    OK键展开, 返回键折叠.
    展开后的默认焦点的位置和展开前相同(第一个和最后一个除外)
  </div>
  <div
    :style="{
      left: 100,
      top: 300,
      width: 1280,
      height: 400,
      fontSize: 20,
      color: '#FFFFFF',
    }"
  >
    {{ getDetaileInfo() }}
  </div>
</template>
