<script lang="ts" setup>
import type { TreeOption, TreeNodeProps, RenderTreePart } from 'naive-ui'

const props = defineProps({
  data: {
    type: Array<TreeOption>,
    required: true,
  },
  keyField: {
    type: String,
    default: 'id',
  },
  labelField: {
    type: String,
    default: 'label',
  },
  showSearch: {
    type: Boolean,
    default: false,
  },
  defaultCheckedKeys: {
    type: Array<string | number>,
    default: () => [],
  },
  nodeProps: {
    type: Function as TreeNodeProps,
    default: undefined,
  },
  renderSuffix: {
    type: Function as RenderTreePart,
    default: undefined,
  },
})

const searchValue = ref<string>('')

const checkedKeys = defineModel<Array<string | number>>('checked')
const updateChecked = (keys: Array<string | number>) => {
  // console.log(keys, '====')
  checkedKeys.value = keys
}

// watch(
//   () => props.defaultCheckedKeys,
//   val => {
//     nextTick(() => {
//       console.log(val, '-----')

//       updateChecked(val)
//     })
//   }
// )
// updateChecked(props.defaultCheckedKeys)
</script>

<template>
  <div class="flex flex-col w-h-full">
    <n-input
      v-if="showSearch"
      v-model:value="searchValue"
      placeholder="搜索"
      clearable
    ></n-input>
    <n-scrollbar class="w-full flex-1">
      <n-tree
        class="w-full"
        block-line
        :data="data"
        :pattern="searchValue"
        :checked-keys="checkedKeys"
        checkable
        cascade
        checked-on-click
        default-expand-all
        :key-field="keyField"
        :label-field="labelField"
        @update:checked-keys="updateChecked"
        :node-props="nodeProps"
        :render-suffix="renderSuffix"
      />
      <!-- :default-checked-keys="defaultCheckedKeys" -->
    </n-scrollbar>
  </div>
</template>

<style lang="scss" scoped></style>
