import { request as _request } from "../wx/network";

const shareRequestCache = new Map<string, IRequestData<any>>();

export function createRequest(option: IRequestCreateConfig) {
  const { baseURL } = option;

  return async <R, T>(config: IRequestConfig<R, T>) => {
    let { url, data, params, header, meta, transform = (params: any) => params, shareRequest, ..._config } = config;

    if (config.method === 'GET') {
      data = params;
    } else if (params) {
      const query = Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
      url += `?${query.join('&')}`
    }

    const key = url;
    if (shareRequest && shareRequestCache.has(key)) {
      return shareRequestCache.get(key) as unknown as PromiseLike<IRequestData<T>>;
    }

    header ??= {};
    header['Authorization'] = meta?.ignoreToken ? '' : await option.token?.() ?? '';
    header['patientId'] = wx.getStorageSync('patientId') ?? '';
    header['doctorId'] = wx.getStorageSync('doctorId') ?? '';

    const promise = _request<IRequestData<T>>({
      url: /https?\:\/\//.test(url) ? url : `${baseURL}${url}`,
      header, data, ..._config,
    }).then(response => {
      if (response.statusCode === 200) {
        if (response.data.code === 200 && response.data.success !== false) {
          const data = Array.isArray(response.data.rows) && response.data.total != null
            ? { data: response.data.rows, total: response.data.total }
            : response.data.data
          return transform({ data: data as any, header: response.header });
        }
        throw { errMsg: response.data.msg || `app:${response.data.code}`, errno: `060202${response.data.code}` }
      }
      throw { errMsg: `${response.errMsg}:${response.statusCode}`, errno: `060201${response.statusCode}` }
    });

    if (shareRequest) shareRequestCache.set(key, <any>promise);

    return promise;
  }
}
