<template>
  <a-spin :spinning="treeState.loading">
    <div v-if="!formConfig?.schema">
      <ns-form ref="formElRef" v-bind="formConfig" :model="formModel" @finish="formFinish" />
    </div>
    <ns-tree v-if="treeData?.length" v-bind="getBindValue" v-model:selectedKeys="selectedKeys">
      <template #[item]="data" v-for="(item, index) in Object.keys($slots)" :key="index">
        <slot :name="item" v-bind="data || {}"></slot>
      </template>
    </ns-tree>
  </a-spin>
</template>
<script lang="ts" setup>
  import { computed, reactive, ref, unref, useAttrs } from 'vue';
  import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
  import { useApi } from '/nerv-lib/use/use-api';
  import { AxiosRequestConfig } from 'axios';
  import { get } from 'lodash-es';
  import { useRoute } from 'vue-router';
  import { isEmpty } from 'lodash-es';
  import { treeProps, treeFormProps } from '/nerv-lib/component/tree/props';
  const formElRef = ref();
  defineOptions({
    name: 'NsTreeApi',
  });
  const props = defineProps(treeProps);
  const treeData = ref<TreeDataItem[]>([]);
  const selectedKeys = ref(props.defaultSelectedKeys || []);
  const { httpRequest } = useApi();
  const requestConfig: AxiosRequestConfig = { method: 'get' };
  const route = useRoute();
  const attrs = useAttrs();
  const formModel = reactive({});
  const treeState = reactive({
    loading: true,
  });
  const formConfig = computed(() => {
    return {
      ...treeFormProps,
      ...props.formConfig,
    };
  });
  const formFinish = () => {
    getData();
  };
  const getBindValue = computed(() => ({
    ...attrs,
    ...props,
    treeData: treeData.value,
  }));
  const setLoading = (loading: boolean) => {
    treeState.loading = loading;
  };
  const httpPrams = computed(() => {
    return { ...route.params, ...route.query, ...props.defaultParams };
  });

  const getData = () => {
    const { api, transform, resultField } = props;
    treeData.value = [];
    if (!api) return;
    setLoading(true);
    httpRequest({
      api,
      params: httpPrams,
      pathParams: { ...route.params, ...route.query },
      requestConfig,
    })
      .then((res) => {
        treeData.value = transform(get(res, resultField));
      })
      .finally(() => {
        setLoading(false);
      });
  };

  getData();
</script>
<style lang="less" scoped></style>
