<script setup lang="ts">
import { ref } from 'vue';
import type { TreeOption } from 'naive-ui';

defineOptions({
  name: 'MenuTree'
});

const props = withDefaults(defineProps<{ menuOptions: Array<TreeOption>; showCascade?: boolean }>(), {
  showCascade: false
});

const checkedKeys = defineModel<Array<string | number>>('checkedKeys', { default: () => [] });
const cascade = defineModel<boolean>('cascade', { default: false });

const menuExpand = ref(false); // 展开/折叠
const menuNodeAll = ref(false); // 全选/全不选

function updateCheckedKeys(keys: number[]) {
  checkedKeys.value = keys;
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(checked: boolean) {
  if (checked) {
    checkedKeys.value = props.menuOptions.map((node): number => node.id as number); // 获取所有节点的 key
  } else {
    checkedKeys.value = []; // 清空选中节点
  }
}
</script>

<template>
  <div class="mt-5px w-full">
    <NCheckbox v-model:checked="menuExpand">展开/折叠</NCheckbox>
    <NCheckbox v-model:checked="menuNodeAll" @update:checked="handleCheckedTreeNodeAll">全选/全不选</NCheckbox>
    <NCheckbox v-if="showCascade" v-model:checked="cascade">父子联动</NCheckbox>
    <NTree
      class="mt-10px border b-rd-8px p-5px"
      block-line
      key-field="id"
      multiple
      :cascade="cascade"
      checkable
      :data="menuOptions"
      :checked-keys="checkedKeys"
      :default-expand-all="menuExpand"
      @update:checked-keys="updateCheckedKeys"
    />
  </div>
</template>

<style scoped>

</style>
