<template>
  <ActionMenus
      v-if="!store.child.value"
      class="menus"
      :menus="store.menus as any"
      :active-key="store.activeMenuKey.value"
      dire="column"
  />
  <scene-menus
      v-if="store.child.value"
      @back="store.child.value = null"
      :menus="store.child.value as MenuRaw[]"
      :level="level + 1"
  />
</template>

<script lang="ts" setup>
import ActionMenus from "@/components/group-button/index.vue";
import {generateMixMenus, MenuRaw, menus, findMenuByKey} from './menus'
import {joinActions} from './actions'
import {computed, onMounted, onUnmounted, watchEffect} from "vue";
import {disabledMap} from "@/hook";

const props = withDefaults(
  defineProps<{ menus?: MenuRaw[], level?: number }>(),
  {level: 1}
)
const emit = defineEmits<{
  (e: 'back'): void,
  (e: 'enterChild'): void,
  (e: 'leaveChild'): void,
}>();
const backMenu = {
  icon: "return",
  text: "",
  key: "back",
  onClick: () => emit("back")
}

const menusMix = computed(() =>
  props.level === 1 ? menus : [backMenu, ...props.menus]
)
const store = generateMixMenus(
  'children',
  m => m,
  menusMix.value
)

watchEffect((onCleanup) => {
  const menu = store.activeMenuKey.value && findMenuByKey(store.activeMenuKey.value)
  if (store.child && menu?.onClick) {
    const leaveHook = menu.onClick()
    leaveHook && onCleanup(leaveHook)
  } else {
    onCleanup(() => {})
  }
})

if (props.level === 1) {
  watchEffect(() => {
    disabledMap.photo = !store.child.value?.length
  })
  watchEffect(() => {
    if (store.child.value) {
      emit('enterChild')
    } else {
      emit('leaveChild')
    }
  })
}

onUnmounted(joinActions(store.itemActiveKey));
onMounted(() => {
  if (props.level > 1) {
    const defaultMenu = props.menus.find(menu => {
      if (typeof menu.defaultSelect === 'function') {
        return menu.defaultSelect()
      } else {
        return menu.defaultSelect
      }
    })
    console.log(defaultMenu)
    store.itemActiveKey.value = defaultMenu?.key
    // store.activeMenuKey.value =
  }
})
</script>
<script lang="ts"> export default {name: 'scene-menus'}</script>

<style lang="scss" scoped>
.menus {
  position: absolute;
  left: var(--boundMargin);
  top: 50%;
  transform: translateY(-50%);
  z-index: 2;
}
</style>
