import { onMounted, ref, type Ref } from "vue";
import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";

export interface ISimpleDataLoader<T, P> extends ILoaderCommon<P> {
  content: Ref<T|null>;
  getLastParams: () => P | undefined;
}

/**
 * 说明：
 * * 简单数据加载器组合式代码。
 * @param loader 数据加载函数
 * @param loadWhenMounted 是否在挂载时自动加载数据
 * @param emptyIfArrayEmpty 如果数组为空是否显示空状态
 * @param showGlobalLoading 是否显示全局加载提示
 */
export function useSimpleDataLoader<T, P = any>(
  loader: (params?: P) => Promise<T>,
  loadWhenMounted = true,
  emptyIfArrayEmpty = true,
  showGlobalLoading = false,
)  : ISimpleDataLoader<T, P>
 {

  const content = ref<T|null>(null) as Ref<T|null>;
  const loadStatus = ref<LoaderLoadType>('loading');
  const loadError = ref('');

  let lastParams: P | undefined;

  async function loadData(params?: P) {
    if (params)
      lastParams = params;
    loadStatus.value = 'loading';
    if (showGlobalLoading)
      uni.showLoading({ title: '加载中...' });

    try {
      const res = (await loader(params ?? lastParams)) as T;
      content.value = res;
      if (Array.isArray(res) && emptyIfArrayEmpty && (res as any[]).length === 0)
        loadStatus.value = 'nomore';
      else
        loadStatus.value = 'finished';
      loadError.value = '';
    } catch(e) {
      loadError.value = '' + e;
      loadStatus.value = 'error';
      console.log(e);
      
    } finally {
      if (showGlobalLoading)
        uni.hideLoading();
    }
  }

  onMounted(() => {
    if (loadWhenMounted) {
      setTimeout(() => {
        loadData();
      }, (0.5 + Math.random()) * 500);
    }
  })

  return {
    content,
    loadStatus,
    loadError,
    loadData,
    getLastParams: () => lastParams,
  }
}