<template>
  <ul>
    <li
      v-for="node in items"
      :key="node.id"
    >
      <a-tree-select-nodes-mobile
        v-model="selected"
        :node="node"
        :parent-id="node.id"
        :default-open="defaultOpen"
      />
    </li>
  </ul>
</template>

<script setup lang="ts">

import ATreeSelectNodesMobile
  from "#adata-ui/components/elements/tree-select-mobile/components/ATreeSelectNodesMobile.vue";

type Item = {
  id: number
  name: string
  children?: Item[]
}

interface Props {
  items: Item[]
  defaultValue?: number[]
  defaultOpen?: boolean
}

type Emits = {
  (e: 'updateSelectedNames', items: { id: number, name: string }[]): void
  (e: 'updateSelected', data: number[]): void
}


const props = (withDefaults(defineProps<Props>(), {
  defaultValue: () => [],
  defaultOpen: false
}))


const emits = defineEmits<Emits>()


const selected = defineModel()
watch(selected, () => {
  emits('updateSelected', selected.value)
}, {deep: true})
const getId = (items: Item[], ids: number[]): { id: number, name: string }[] => {
  const result: { id: number, name: string }[] = [];

  const search = (item: Item) => {
    if (ids.includes(item.id)) {
      result.push({id: item.id, name: item.name});
    }

    if (item.children?.length) {
      item.children.forEach(child => search(child));
    }
  };

  items.forEach(item => search(item));

  return result;
};

const selectedIdName = computed<{ id: number, name: string }[]>(() => {
  return getId(props.items, selected.value)
})

watch(selectedIdName, () => {
  emits('updateSelectedNames', selectedIdName.value)
}, {immediate: true, deep: true})

</script>
