import serviceConfig from "../config/service";
import { getCurrentWebviewToken } from "./webview-token";

let loadingCount = 0;

function isAbsoluteUrl(url) {
  return /^https?:\/\//i.test(url || "");
}

function buildRequestUrl(url) {
  if (isAbsoluteUrl(url)) {
    return url;
  }

  return serviceConfig.BASE_URL + url;
}

function showGlobalLoading(options) {
  if (!options || !options.showLoading) {
    return false;
  }

  loadingCount += 1;

  if (loadingCount === 1) {
    uni.showLoading({
      title: options.loadingText || "加载中",
      mask: options.loadingMask !== false,
    });
  }

  return true;
}

function hideGlobalLoading(shouldHide) {
  if (!shouldHide) {
    return;
  }

  loadingCount = Math.max(0, loadingCount - 1);

  if (loadingCount === 0) {
    uni.hideLoading();
  }
}

export default function request(options) {
  const method = options.method || "GET";
  const defaultContentType =
    method === "POST"
      ? "application/x-www-form-urlencoded; charset=UTF-8"
      : "application/json";
  const token = getCurrentWebviewToken();
  const requestHeader = Object.assign(
    {
      "Content-Type": defaultContentType,
      "Form-type": "gzh",
    },
    options.header || {},
  );

  if (token) {
    const bearerToken = "Bearer " + token;
    requestHeader["Authori-zation"] = bearerToken;
    requestHeader.Authorization = bearerToken;
  }
  const shouldHandleLoading = showGlobalLoading(options);

  return new Promise(function (resolve, reject) {
    uni.request({
      url: buildRequestUrl(options.url),
      method: method,
      data: options.data || {},
      header: requestHeader,
      timeout: serviceConfig.TIMEOUT,
      success: function (response) {
        const statusCode = response.statusCode || 0;
        if (statusCode >= 200 && statusCode < 300) {
          resolve(response.data);
          return;
        }

        reject({
          statusCode: statusCode,
          message: (response.data && response.data.message) || "接口请求失败",
          raw: response,
        });
      },
      fail: function (error) {
        reject({
          statusCode: 0,
          message: error.errMsg || "网络异常",
          raw: error,
        });
      },
      complete: function () {
        hideGlobalLoading(shouldHandleLoading);
      },
    });
  });
}
