<script setup lang="ts">
import { computed, ref, unref, watch, watchEffect } from 'vue';
import { basicApiSelectProps } from './props';
import type { ApiTreeSelectProps } from './type';
const props = withDefaults(defineProps<ApiTreeSelectProps>(), {
  immediate: true,
  resultFeild: 'data'
});
const basicProps = ref(basicApiSelectProps);
const options = ref([]);
const modelVlaue = defineModel<Array<string | number> | string | number | null>();
const isFirstReq = ref(false);
const bindValue = computed(() => {
  return {
    ...props,
    ...basicProps
  };
});

async function fetchApi() {
  const res = await props.api();
  options.value = res[props.resultFeild];
}
watchEffect(() => {
  if (unref(bindValue).immediate) {
    fetchApi();
  }
});
watch(
  () => modelVlaue.value,
  () => {
    // console.log(modelVlaue.value);
  }
);
function handleFocus() {
  if (!unref(bindValue).immediate && !unref(isFirstReq)) {
    fetchApi();
    isFirstReq.value = true;
  }
}
function handleScroll(e: Event) {
  const currentTarget = e.currentTarget as HTMLElement;
  if (currentTarget.scrollTop + currentTarget.offsetHeight >= currentTarget.scrollHeight) {
    // console.log('到底了');
  }
}
</script>

<template>
  <NTreeSelect
    v-bind="bindValue"
    v-model:value="modelVlaue"
    :options="options"
    :label-field="labelFeild"
    :key-field="valueFeild"
    @focus="handleFocus"
    @scroll="handleScroll"
  ></NTreeSelect>
</template>

<style scoped></style>
