<script lang="ts">
  export default {
    inheritAttrs: true,
  };
</script>
<script lang="ts" setup>
  import { ref, watchEffect, computed, unref, watch, reactive } from 'vue';
  import { Select, Spin } from 'ant-design-vue';
  import { isFunction } from '/@/utils/is';
  import { useRuleFormItem } from '/@/hooks/component/useFormItem';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { get, omit } from 'lodash-es';
  import { LoadingOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PaginationResult } from '/#/axios';
  import { useDebounceFn } from '@vueuse/core';

  type OptionsItem = { label: string; value: string; disabled?: boolean };

  type Pagination = Record<'page' | 'pageSize', number>;

  const emit = defineEmits(['options-change', 'change']);
  const props = withDefaults(
    defineProps<{
      value?: Recordable | number | string;
      numberToString?: boolean;
      api?: (arg?: Recordable) => Promise<PaginationResult<OptionsItem>>;
      params?: Recordable;
      resultField?: string;
      labelField?: string;
      valueField?: string;
      immediate?: boolean;
      pagenation?: Pagination;
      queryEmptyDataAgin?: boolean;
    }>(),
    {
      resultField: '',
      labelField: 'label',
      valueField: 'value',
      immediate: true,
      queryEmptyDataAgin: true,
      pagenation: () => ({ page: 1, pageSize: 10 }),
    }
  );

  const OptionsItem = (_, { attrs }: { attrs: { vNode: any } }) => attrs.vNode;

  const options = ref<OptionsItem[]>([]);
  const pagination = reactive(Object.assign({ total: 0, page: 1, pageSize: 10 }, props.pagenation));
  const scrollLoading = ref(false);
  const lock = ref(false);
  const loading = ref(false);
  const isFirstLoad = ref(true);
  const emitData = ref<any[]>([]);
  const attrs = useAttrs();
  const { t } = useI18n();

  // Embedded in the form, just use the hook binding to perform form verification
  const [state] = useRuleFormItem(props, 'value', 'change', emitData);

  const getOptions = computed(() => {
    const { labelField, valueField, numberToString } = props;

    return unref(options).reduce((prev, next: Recordable) => {
      if (next) {
        const value = get(next, valueField);
        prev.push({
          label: next[labelField],
          value: numberToString ? `${value}` : value,
          ...omit(next, [labelField, valueField]),
        });
      }
      return prev;
    }, [] as OptionsItem[]);
  });

  watchEffect(() => {
    props.immediate && isFirstLoad.value && fetch();
  });

  watch(
    () => props.params,
    () => {
      !unref(isFirstLoad) && fetch();
    },
    { deep: true }
  );

  async function fetch() {
    const api = props.api;
    if (!api || !isFunction(api)) return;
    try {
      !unref(getOptions).length ? (loading.value = true) : (scrollLoading.value = true);
      lock.value = true;
      const { total, items } = await api({
        ...props.params,
        page: pagination.page,
        pageSize: pagination.pageSize,
      });

      pagination.total = total;
      if (Array.isArray(items)) {
        options.value = [...options.value, ...items];
        emitChange();
        return;
      }
      if (props.resultField) {
        options.value = [...options.value, ...(get(items, props.resultField) || [])];
      }
      emitChange();
    } catch (error) {
      pagination.page = Math.ceil(unref(getOptions).length / pagination.pageSize);
      console.warn(error);
    } finally {
      isFirstLoad.value = false;
      loading.value = false;
      scrollLoading.value = false;
      lock.value = false;
    }
  }

  async function handleFetch() {
    if (!props.immediate && unref(isFirstLoad)) {
      await fetch();
      isFirstLoad.value = false;
    }
  }

  function emitChange() {
    emit('options-change', unref(getOptions));
  }

  function handleChange(_, ...args) {
    emitData.value = args;
  }

  async function handlePopupScroll(event: MouseEvent) {
    const { scrollHeight, scrollTop, clientHeight } = event.target as HTMLDivElement;
    if (scrollTop + clientHeight >= scrollHeight) {
      if (unref(getOptions).length < pagination.total && !unref(lock)) {
        pagination.page = pagination.page + 1;
        await fetch();
      }
    }
  }

  const debounceHandlePopupScroll = useDebounceFn(handlePopupScroll, 100);
</script>

<template>
  <Select
    @dropdownVisibleChange="handleFetch"
    v-bind="attrs"
    @change="handleChange"
    :options="getOptions"
    v-model:value="state"
    @popup-scroll="debounceHandlePopupScroll"
  >
    <template #[item]="data" v-for="item in Object.keys($slots)">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
    <template #suffixIcon v-if="loading">
      <LoadingOutlined spin />
    </template>
    <template #notFoundContent v-if="loading">
      <span>
        <LoadingOutlined spin class="mr-1" />
        {{ t('component.form.apiSelectNotFound') }}
      </span>
    </template>
    <template #dropdownRender="{ menuNode }">
      <OptionsItem :vNode="menuNode" />
      <div v-show="scrollLoading" class="flex justify-center">
        <Spin size="small" />
      </div>
    </template>
  </Select>
</template>
