import Taro from "@tarojs/taro";
import apiConfig from "./api";

/** 对象转参数 */
export function objectToQuery(obj: Record<string, any>) {
  return Object.keys(obj)
    .map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(obj[k]))
    .join("&");
}
/** 深度合并 */
function deepMerge<T extends Record<string, any>>(...objects: T[]): T {
  return objects.reduce((prev, obj) => {
    Object.keys(obj).forEach((key) => {
      const prevValue = prev[key];
      const objValue = obj[key];
      if (
        typeof prevValue === "object" &&
        typeof objValue === "object" &&
        prevValue !== null &&
        objValue !== null
      ) {
        //@ts-ignore
        prev[key] = deepMerge(prevValue, objValue);
      } else {
        //@ts-ignore
        prev[key] = objValue;
      }
    });
    return prev;
  }, {} as T);
}

// http规则校验
function urlRegExp(value: string) {
  return /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/.test(value);
}

/** 请求拦截器 */
const HttpRequestInterceptor = () => { };

/** 响应拦截器 */
const HttpResponseInterceptor = () => { };

/** 简单封装 */
export default function request<T>(
  url: string,
  option: Partial<Taro.request.Option> & { params?: any }
): Promise<T> {
  const params = option.params;

  url = urlRegExp(url) ? url : apiConfig.dev + url;

  if (params) {
    url = url + "?" + objectToQuery(params);
  }

  return new Promise((resolve, reject) => {
    Taro.showLoading({
      title: "数据加载中",
      mask: true,
    });

    Taro.request({
      method: "POST",
      ...option,
      url,
      header: deepMerge<any>(
        {
          Authorization: "Bearer " + Taro.getStorageSync("token"),
          "CLIENT-TOC": "Y",
        },
        option?.header ?? {}
      ),
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      },
      complete(err) {
        setTimeout(function () {
          Taro.hideLoading();
        }, 500);
      },
    });
  });
}
