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

export interface ISimplePageContentLoader<T, P> extends ILoaderCommon<P> {
  content: Ref<T|null>;
}

/**
 * 说明：
 * * 简单页面内容加载器组合式代码。
 * @param loader 数据加载函数
 * @param options 选项
 */
export function useSimplePageContentLoader<T, P = any>(
  loader: (params?: P) => Promise<T>,
  options?: {
    immediate?: boolean;
  }
)  : ISimplePageContentLoader<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';
    try {
      const res = (await loader(params ?? lastParams)) as T;
      content.value = res;
      loadStatus.value = 'finished';
      loadError.value = '';
    } catch(e) {
      loadError.value = '' + e;
      loadStatus.value = 'error';
    }
  }

  onMounted(() => {
    if (options?.immediate)
      loadData();
  });

  return {
    content,
    loadStatus,
    loadError,
    loadData,
  }
}