<template>
  <ns-tree v-bind="getBindValue">
    <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
  </ns-tree>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
  import { http } from '/nerv-lib/util/http';
  import { get } from 'lodash-es';

  export default defineComponent({
    name: 'NsTreeApi',
    props: {
      api: {
        type: String,
        required: true,
      },
      params: {
        type: Object,
      },
      transform: {
        type: Function,
        default: null,
      },
      resultField: {
        type: String,
        default: 'data.data',
      },
      defaultExpandAll: {
        type: Boolean,
        default: true,
      },
      blockNode: {
        type: Boolean,
        default: true,
      },
    },
    setup(props, { attrs }) {
      const treeData = ref<TreeDataItem[]>([]);
      const getBindValue = computed(() => ({
        ...attrs,
        ...props,
        treeData: treeData.value,
      }));

      const getData = () => {
        const { params, transform, resultField } = props;
        treeData.value = [];
        http.get(props.api, unref(params)).then((res) => {
          let data = [];
          if (resultField) {
            data = get(res, resultField);
          }
          if (transform) {
            treeData.value = transform(data);
          }
        });
      };

      getData();

      return {
        treeData,
        getBindValue,
      };
    },
  });
</script>
<style lang="less" scoped></style>
