<script setup>
import { shallowRef, computed, inject } from "vue";
const props = defineProps({
  style: Object,
  itemClick: Function,
  itemFocus: Function,
  data: Object,
  query: Object,
  onAction: Object,
});

let focused = shallowRef(false);
const touchModeSwitcherRef = inject("touchModeSwitcherRef");

const foucsStyle = computed(() => {
  return {
    width: props.style.width,
    height: props.style.height,
  };
});

const itemStyle = computed(() => {
  return {
    width: props.style.width - 10,
    height: props.style.height - 10,
    backgroundColor: props.style.backgroundColor,
    color: props.style.color,
  };
});

const modeChangeCallback = (mode) => {
  if (mode == 2) {
    focused.value = false;
  } else {
    focused.value = true;
  }
};

const onFocus = () => {
  //为了避免每个item都注册回调, 这里onFocus时注册, onBlur时注销
  touchModeSwitcherRef.value.registerCallback(modeChangeCallback);
  if (touchModeSwitcherRef.value.getInteractiveMode() == 1) {
    focused.value = true;
  }
  if (props.itemFocus) {
    props.itemFocus(props.data);
  }
};

const onBlur = () => {
  touchModeSwitcherRef.value.unregisterCallback(modeChangeCallback);
  focused.value = false;
};

const onClick = () => {
  if (props.itemClick) {
    props?.itemClick(props.query.id, props.data);
  }
};

props.onAction.register("onFocus", onFocus);
props.onAction.register("onBlur", onBlur);
props.onAction.register("onClick", onClick);
</script>

<template>
  <div>
    <div class="focus" :style="foucsStyle" v-if="focused" />
    <div class="item" :style="itemStyle">
      <slot></slot>
    </div>
  </div>
</template>

<style scoped>
.focus {
  top: -5;
  left: -5;
  background-color: #0000ff;
}

.item {
  text-align: center;
  font-size: 30;
}
</style>
