const env = __VITE_ENV__;

export const API_CONTEXT_CACHE_KEY = "ykt_team_api_context";

export const CORP_API_BASE_URL_MAP = {
  wwa54dfba0b5441ef1: "https://crm.gykqyy.com/ykt/",
  wpLgjyawAAxKtBH5GVT5DVhLefg246Ag: "https://hlwyy.6thhosp.com:4443/",

};

export const CORP_ID_ALIAS_MAP = {
  "wpLgjyawAAeRkCPQMp9-z5q-xEzK64nA": "wwa54dfba0b5441ef1",
};

function normalizeBaseUrl(url) {
  return String(url || "").replace(/\/+$/, "");
}

function getDefaultBaseUrl() {
  return normalizeBaseUrl(env.MP_API_BASE_URL);
}

export function normalizeCorpId(corpId) {
  const normalizedCorpId = String(corpId || "").trim();
  return CORP_ID_ALIAS_MAP[normalizedCorpId] || normalizedCorpId;
}

export function normalizeCorpIdFields(value) {
  if (Array.isArray(value)) {
    return value.map((item) => normalizeCorpIdFields(item));
  }
  if (!value || typeof value !== "object") {
    return value;
  }
  return Object.keys(value).reduce((acc, key) => {
    acc[key] = key === "corpId"
      ? normalizeCorpId(value[key])
      : normalizeCorpIdFields(value[key]);
    return acc;
  }, {});
}

function readCachedContext() {
  if (typeof uni === "undefined" || typeof uni.getStorageSync !== "function") {
    return null;
  }
  try {
    const cached = uni.getStorageSync(API_CONTEXT_CACHE_KEY);
    if (!cached || typeof cached !== "object" || !cached.baseUrl) return null;
    const context = {
      corpId: normalizeCorpId(cached.corpId),
      baseUrl: normalizeBaseUrl(cached.baseUrl),
    };
    if (context.corpId !== (cached.corpId || "")) {
      writeCachedContext(context);
    }
    return context;
  } catch (error) {
    return null;
  }
}

function writeCachedContext(context) {
  if (typeof uni === "undefined" || typeof uni.setStorageSync !== "function") {
    return;
  }
  try {
    uni.setStorageSync(API_CONTEXT_CACHE_KEY, {
      corpId: normalizeCorpId(context.corpId),
      baseUrl: normalizeBaseUrl(context.baseUrl),
    });
  } catch (error) {
    // 缓存失败不能阻断接口请求。
  }
}

function createContext(corpId, baseUrl) {
  return {
    corpId: normalizeCorpId(corpId),
    baseUrl: normalizeBaseUrl(baseUrl),
  };
}

function safeDecode(value) {
  try {
    return decodeURIComponent(value);
  } catch (error) {
    return value;
  }
}

function parseQueryString(queryString) {
  return String(queryString || "")
    .replace(/^[^?]*\?/, "")
    .split("&")
    .reduce((acc, item) => {
      if (!item) return acc;
      const [key, ...valueParts] = item.split("=");
      if (!key) return acc;
      acc[safeDecode(key)] = safeDecode(valueParts.join("=") || "");
      return acc;
    }, {});
}

export function getCorpIdFromAppOptions(options = {}) {
  const query = options.query || options || {};
  const corpId = query.corpId || query.corpid || query.corp_id;
  if (corpId) return normalizeCorpId(corpId);

  if (typeof query.q === "string") {
    const qParams = parseQueryString(safeDecode(query.q));
    const qCorpId = qParams.corpId || qParams.corpid || qParams.corp_id;
    if (qCorpId) return normalizeCorpId(qCorpId);
  }

  return "";
}

export function initApiContextFromAppOptions(options = {}) {
  const corpId = getCorpIdFromAppOptions(options);
  if (!corpId) return null;
  return resolveApiContext(corpId);
}

export function resolveApiContext(corpId) {
  const normalizedCorpId = normalizeCorpId(corpId);

  if (normalizedCorpId) {
    const configuredBaseUrl = CORP_API_BASE_URL_MAP[normalizedCorpId];
    const context = createContext(
      normalizedCorpId,
      configuredBaseUrl || getDefaultBaseUrl()
    );
    writeCachedContext(context);
    return context;
  }

  const cachedContext = readCachedContext();
  if (cachedContext) return cachedContext;

  const context = createContext("", getDefaultBaseUrl());
  writeCachedContext(context);
  return context;
}

export function getApiBaseUrlByCorpId(corpId) {
  return resolveApiContext(corpId).baseUrl;
}

export function getDefaultUploadUrl() {
  return `${getDefaultBaseUrl()}/upload`;
}

export function buildApiUrl(path, corpId) {
  const { baseUrl } = resolveApiContext(corpId);
  const normalizedPath = String(path || "").replace(/^\/+/, "");
  return normalizedPath ? `${baseUrl}/${normalizedPath}` : baseUrl;
}
