<script setup>
import { shallowRef, onMounted, inject } from "vue";
import { CONST_FILL_NAME_FUNC, CONST_COLUMN_MARK } from "./constants.js";
import { useFocusHub } from "jsview";
const props = defineProps({
  focusBlockName: String,
  style: {
    type: Object,
    default() {
      return {};
    },
  },
  defineColumn: Number,
  defineLine: Number,
});

const fbName = props.focusBlockName; // 以列号作为自己的JsvfocusBlock的name

const fullName = shallowRef("");
const blockRef = shallowRef(null);
const hasFocused = shallowRef(false);

const focusHub = useFocusHub(true); // 获得当前nameSpace的focusHub

const funcFullFilled = inject(CONST_FILL_NAME_FUNC);
const columnMark = inject(CONST_COLUMN_MARK); // 全局行记录器，用于纵向移动时保持列

onMounted(() => {
  const syncName = async () => {
    // 由于vue的mount回调从子到父节点传递,而FocusBlock焦点树要在根节点mount完成后才建立完。所以getFullName是一个异步函数。
    fullName.value = await blockRef.value.getFullName(); // 用名字更新方块内的名称
    funcFullFilled(props.defineLine, props.defineColumn, fullName.value); // 将全名同步给最外层app, 以便于全局跳转
    console.log(`name taken success name=${fullName.value}`);
  };
  syncName();
});

const onFocus = () => {
  const nameSpace = focusHub.getNameSpace(); // 注意: 如果nameSpace为根节点时，获得的NameSpace的String为空字符串
  console.log(`${nameSpace}.${fbName} focused`);
  hasFocused.value = true;
  columnMark.value = props.defineColumn;

  // 用于测试焦点深入处理
  focusHub.setFocus(fbName + "_dep1");
};

const onBlur = () => {
  console.log(`${focusHub.getNameSpace()}.${fbName} blured`);
  hasFocused.value = false;
};

const onSubDep1Focus = () => {
  const nameSpace = focusHub.getNameSpace();
  console.log(`${nameSpace}.${fbName}_dep1 focused`);

  // 用于测试焦点深入处理(第二层)
  focusHub.setFocus(fbName + "_dep2");
};

const onSubDep1Blur = () => {
  const nameSpace = focusHub.getNameSpace();
  console.log(`${nameSpace}.${fbName}_dep1 blured`);
};

const onSubDep2Focus = () => {
  const nameSpace = focusHub.getNameSpace();
  console.log(`${nameSpace}.${fbName}_dep2 focused`);
};

const onSubDep2Blur = () => {
  const nameSpace = focusHub.getNameSpace();
  console.log(`${nameSpace}.${fbName}_dep2 blured`);
};
</script>

<template>
  <jsv-focus-block
    ref="blockRef"
    :name="fbName"
    :onAction="{
      onFocus,
      onBlur,
    }"
  >
    <div
      class="title"
      :style="{
        left: props.style.left,
        backgroundColor: hasFocused ? 'rgba(255,0,0,1)' : 'rgba(0,255,0,1)',
      }"
    >
      {{ fullName }}
    </div>
    <jsv-focus-block
      :name="fbName + '_dep1'"
      :onAction="{
        onFocus: onSubDep1Focus,
        onBlur: onSubDep1Blur,
      }"
    >
      <jsv-focus-block
        :name="fbName + '_dep2'"
        :onAction="{
          onFocus: onSubDep2Focus,
          onBlur: onSubDep2Blur,
        }"
      />
    </jsv-focus-block>
  </jsv-focus-block>
</template>

<style scoped>
.title {
  text-align: center;
  font-size: 14;
  line-height: 50;
  top: 30;
  width: 155;
  height: 50;
}
</style>
