// api/request.ts
import { requestInterceptor } from './interceptors/request';
import { responseInterceptor } from './interceptors/response';
import type { IRequestOptions, ICreateClientConfig } from './types';
import { REQUEST_TIMEOUT } from './config';
import { t } from '@/utils/i18n'

export function createRequestClient(cfg: ICreateClientConfig) {
  const baseURL = cfg.baseURL;
  const timeout = cfg.timeout ?? REQUEST_TIMEOUT;
  let reqCount= 0

  async function request<T = any>(options: IRequestOptions): Promise<T> {
    // 组装 final options
    const final: UniApp.RequestOptions = {
      ...options,
      url: (options.url || '').startsWith('http') ? options.url : `${baseURL}${options.url}`,
      timeout,
      header: options.header || {},
    };

    // 运行请求拦截器，修改 headers 等
    const intercepted = requestInterceptor(final as IRequestOptions);

    // 全局处理请求 loading
    const loading = cfg.loading ?? true  // 接口请求参数不传loading，默认显示loading
    if (loading) {
      uni.showLoading({ mask: true })
      reqCount++
    }

    return new Promise((resolve, reject) => {
      uni.request({
        ...intercepted,
        complete() {
          // 请求完成关闭 loading
          loading && reqCount--
          reqCount <= 0 && uni.hideLoading()
        },
        success(res: any) {
          // 委托给响应拦截器处理
          responseInterceptor(res)
            .then((r) => {
              resolve(r as any);
            })
            .catch((err) => {
              reject(err);
            });
        },
        fail(err: any) {
          uni.showToast({ title: t('global.networkConnectionError'), icon: 'none' });
          reject(err);
        },
      } as any);
    });
  }

  return { request };
}
