<script setup>
import { inject } from "vue"
import BaseBlock from "./BaseBlock.vue";
import { CONST_MAX_COLUMN } from "./constants.js"
import { useFocusHub } from "jsview";

const props = defineProps({
  defineLine: Number,
});

const focusHubWithNs = useFocusHub(true); // 获取当前NameSpace的focusHub

const columnMark = inject("BasicFocusAppColMark"); // 全局行记录器, 读取当前列

// 构建子 BaseBlock 的设置信息
let childBlockInfo = [];
for (let i = 0 ; i < CONST_MAX_COLUMN; i++) {
    childBlockInfo.push({
        column: i,
        focusBlockName: "C" + i,
    });
}

const onKeyDown = (ev) => {
  // 子节点未处理的按键事件会流向此节点
  let keyUsed = true;
  let focusColumn = columnMark.value;
  switch (ev.keyCode) {

    case 37: // Left
      focusColumn--;
      break;
    case 39: // Right
      focusColumn++;
      break;
    default:
      keyUsed = false;
  }

  if (keyUsed) {
    // 收到了左右键的处理

    // 防止运动越界
    if (focusColumn < 0) {
        focusColumn = 0;
    } else if (focusColumn >= CONST_MAX_COLUMN) {
        focusColumn = CONST_MAX_COLUMN - 1;
    }

    // 因为获取的focusHub为含NameSpace的对象, 并且此节点和BaseBlock在同一级别(同一个NameSpace), 所以可以使用不带 NameSpace 的 name 进行focus
    console.log(`Do focus to sub name=${childBlockInfo[focusColumn].focusBlockName}`)
    focusHubWithNs.setFocus(childBlockInfo[focusColumn].focusBlockName);
  }

  return keyUsed; // 非左右键信息, 通过返回false交给上级JsvFocusBlock处理
};

</script>

<template>
  <!-- 模拟最后子节点内部的root节点 -->
  <jsv-focus-block
      :onAction="{
        onKeyDown,
      }">
      <base-block v-for="item in childBlockInfo" :key="item.column" 
        :focusBlockName="item.focusBlockName"
        :style="{ left: 30 + 165 * item.column }" 
        :defineColumn="item.column"
        :defineLine="props.defineLine"
      />
  </jsv-focus-block>
</template>

<style scoped lang="scss">

</style>