function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { marmotMap, sdkVersion, v2AppMarmotMap } from "../../config";
import { AUTO_DEBIT_PAGE_URL } from "../../constant/auto-debit";
import { ESP_PAGE_NAME } from "../../constant/easysafepay";
import { ComponentSignEnum, ProductSceneEnum } from "../../types";
import { queryParse, serialize } from "../../util";
import { isDebugLog } from "../../util/debug";
import { compareVersion } from "../../util/versionCompare";

/**
 * Tell the SDK which version of the Web App to load.
 * Sent by server inside paymentSession.
 */

/**
 * Tell the SDK which Web App URL to load.
 * Sent by server inside paymentSession.
 */

export var getWebAppUrlInfo = function getWebAppUrlInfo(params) {
  var environment = params.environment,
    sdkMetaData = params.sdkMetaData,
    productScene = params.productScene,
    productSceneVersion = params.productSceneVersion,
    paymentMethodCategoryType = params.paymentMethodCategoryType,
    query = params.query,
    isPreload = params.isPreload,
    v2Url = params.v2Url;
  var path = getAppPath(environment, sdkMetaData, productScene, productSceneVersion, paymentMethodCategoryType, v2Url);
  var _queryParse = queryParse(),
    _sandbox = _queryParse._sandbox,
    _light_sandbox = _queryParse._light_sandbox,
    _queryParse$requestHo = _queryParse.requestHost,
    requestHost = _queryParse$requestHo === void 0 ? '' : _queryParse$requestHo,
    _queryParse$groupId = _queryParse.groupId,
    groupId = _queryParse$groupId === void 0 ? '' : _queryParse$groupId,
    LOCAL_MOCK = _queryParse.LOCAL_MOCK,
    _displayType = _queryParse._displayType;
  var urlParams = {};
  for (var key in query) {
    urlParams[key] = '' + query[key];
  }
  // 如果是preload模式，添加一个preload的query参数
  if (isPreload) {
    urlParams['isPreload'] = 'true';
  }
  urlParams.appMatched = sdkMetaData.webAppVersion ? 'true' : 'false';
  urlParams.sdkVersion = sdkMetaData.sdkVersion;
  urlParams.refUrl = window.location.href;
  urlParams._componentStartTime = "".concat(Date.now());
  if (LOCAL_MOCK) urlParams.LOCAL_MOCK = LOCAL_MOCK;
  if (requestHost) urlParams.requestHost = requestHost;
  if (groupId) urlParams.groupId = groupId;
  if (environment === 'light_sandbox' || _light_sandbox === 'true') urlParams.sandbox = 'true';
  if (environment === 'sandbox' || _sandbox === 'true') urlParams.shadow = 'true';
  if (_displayType) urlParams.displayType = _displayType;
  var locationSearch = serialize(urlParams);
  if (isDebugLog()) {
    console.log('appUpgrade#getIframeUrl#appMatched', urlParams.appMatched);
    console.log('appUpgrade#getIframeUrl#url', path, locationSearch);
  }
  return {
    path: path,
    locationSearch: locationSearch
  };
};
export var getWebAppV2Url = function getWebAppV2Url(params) {
  var productScene = params.productScene,
    isPreload = params.isPreload,
    environment = params.environment;
  var v2Url = isPreload ? getLocalCheckoutUrl(productScene, environment) : defaultCheckoutUrl(productScene, environment);
  var info = getWebAppUrlInfo(_objectSpread(_objectSpread({}, params), {}, {
    v2Url: v2Url
  }));
  if (!isPreload && v2Url && info.path) {
    console.log('[web-sdk] save web app, url: ', info.path);
    saveLocalCheckoutUrl(productScene, info.path);
  }
  var webAppUrl;
  if (info.path.indexOf('?') !== -1) {
    webAppUrl = "".concat(info.path, "&").concat(info.locationSearch);
  } else {
    webAppUrl = "".concat(info.path, "?").concat(info.locationSearch);
  }
  console.log('[web-sdk] web app, url: ', webAppUrl);
  return webAppUrl;
};
export var getWebAppUrl = function getWebAppUrl(params) {
  var info = getWebAppUrlInfo(params);
  var webAppUrl;
  if (info.path.indexOf('?') !== -1) {
    webAppUrl = "".concat(info.path, "&").concat(info.locationSearch);
  } else {
    webAppUrl = "".concat(info.path, "?").concat(info.locationSearch);
  }
  return webAppUrl;
};
var getAppPath = function getAppPath() {
  var environment = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'prod';
  var sdkMetaData = arguments.length > 1 ? arguments[1] : undefined;
  var productScene = arguments.length > 2 ? arguments[2] : undefined;
  var productSceneVersion = arguments.length > 3 ? arguments[3] : undefined;
  var paymentMethodCategoryType = arguments.length > 4 ? arguments[4] : undefined;
  var v2Url = arguments.length > 5 ? arguments[5] : undefined;
  var _ref = queryParse() || {},
    urlTestHost = _ref.host;
  // only for test while testurl?host=https://xxxxx.test.html
  if (urlTestHost && !['sandbox', 'light_sandbox', 'prod'].includes(environment)) {
    return urlTestHost;
  }
  var validProductSceneVersion = getValidProductSceneVersion(sdkMetaData.productScene, productSceneVersion, paymentMethodCategoryType);
  var productSceneWithPaymentMethodCategoryType = "".concat(sdkMetaData.productScene, "_").concat(paymentMethodCategoryType);
  if (productSceneWithPaymentMethodCategoryType === ComponentSignEnum.AUTO_DEBIT_APM) {
    return "".concat(v2AppMarmotMap[environment]).concat(AUTO_DEBIT_PAGE_URL.TRUSTLY);
  }
  switch (productScene) {
    case ProductSceneEnum.EASY_PAY:
      return v2Url !== null && v2Url !== void 0 ? v2Url : defaultCheckoutUrl(productScene, environment);
    default:
      return "".concat(marmotMap[environment], "/").concat(productSceneWithPaymentMethodCategoryType, "/").concat(validProductSceneVersion, "/index.html");
  }
};
export var parseWebAppMatchConfig = function parseWebAppMatchConfig(extendInfo) {
  if (!extendInfo) {
    return [];
  }
  try {
    var _extendInfoJson$sdkUp;
    var extendInfoJson = JSON.parse(extendInfo);
    return extendInfoJson === null || extendInfoJson === void 0 || (_extendInfoJson$sdkUp = extendInfoJson.sdkUpgradeInfo) === null || _extendInfoJson$sdkUp === void 0 ? void 0 : _extendInfoJson$sdkUp.versions;
  } catch (error) {
    console.error('Parse the config for Web app failed#', error);
    return [];
  }
};
export var parseWebAppUrlMatchConfig = function parseWebAppUrlMatchConfig(extendInfo) {
  if (!extendInfo) {
    return [];
  }
  try {
    var extendInfoJson = JSON.parse(extendInfo);
    return extendInfoJson === null || extendInfoJson === void 0 ? void 0 : extendInfoJson.checkoutInfo;
  } catch (error) {
    console.error('Parse the url config for Web app failed#', error);
    return [];
  }
};
var getValidProductSceneVersion = function getValidProductSceneVersion(productScene, productSceneVer, paymentMethodCategoryType) {
  var _supportMapping;
  var supportMapping = (_supportMapping = {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_supportMapping, ComponentSignEnum.NONE, ['']), ComponentSignEnum.AUTO_DEBIT_WALLET, ['1.0']), ComponentSignEnum.AUTO_DEBIT_PAY_WALLET, ['']), ComponentSignEnum.CASHIER_PAYMENT_BANK, ['1.0']), ComponentSignEnum.CASHIER_PAYMENT_CARD, ['1.0']), ComponentSignEnum.CASHIER_PAYMENT_APM, ['1.0']), ComponentSignEnum.EASY_PAY_WALLET, ['1.0', '2.0']), ComponentSignEnum.EASY_PAY_APM, ['2.0']), ComponentSignEnum.VAULTING_CARD, ['1.0']), ComponentSignEnum.ELEMENT_PAYMENT, ['1.0']), _defineProperty(_defineProperty(_defineProperty(_supportMapping, ComponentSignEnum.ELEMENT_ADDRESS, ['1.0']), ComponentSignEnum.CHECKOUT_PAYMENT, ['1.0']), ComponentSignEnum.AUTO_DEBIT_APM, ['1.0']));
  var targetVersions = supportMapping[productScene + '_' + paymentMethodCategoryType];
  if (!targetVersions) {
    return '';
  }
  // 从左到右，从旧到新
  var isSupport = targetVersions.find(function (it) {
    return it === productSceneVer;
  });
  var latestVersion = targetVersions[targetVersions.length - 1];
  return isSupport ? productSceneVer : latestVersion;
};
var KEY_CHECKOUT_URL = "web_url_";

/**
 * Save the current checkout URL to localStorage for the specified product scene.
 *
 * @param productScene - The product scene for which the checkout URL should be saved.
 */
export var saveLocalCheckoutUrl = function saveLocalCheckoutUrl(productScene, url) {
  var key = KEY_CHECKOUT_URL + productScene;
  localStorage.setItem(key, url);
};

/**
 * 获取从外部动态下发的V2AppUrl.
 *
 * @param config - sessionData解析来的checkoutInfo列表.
 */
export var getMatchedWebAppV2Url = function getMatchedWebAppV2Url(productScene) {
  var mid = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var configs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  var env = arguments.length > 3 ? arguments[3] : undefined;
  switch (productScene) {
    case ProductSceneEnum.EASY_PAY:
      return matchEasySafePayV2Url({
        configs: configs,
        mid: mid,
        env: env,
        pageName: ESP_PAGE_NAME.SDK_PORTAL
      });
    default:
      return defaultCheckoutUrl(productScene, env);
  }
};

/**
 * 获取ESP从sessionData.checkoutInfo内动态下发的Url.
 */
export var matchEasySafePayV2Url = function matchEasySafePayV2Url(params) {
  var _params$configs = params.configs,
    configs = _params$configs === void 0 ? [] : _params$configs,
    _params$mid = params.mid,
    mid = _params$mid === void 0 ? '' : _params$mid,
    env = params.env,
    pageName = params.pageName;
  var matchURLByMid = function matchURLByMid() {
    var sortedConfigs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var targetConfigEntry = sortedConfigs.find(function (configEntry) {
      var _configEntry$mids;
      var isMatchMid = !!(configEntry !== null && configEntry !== void 0 && (_configEntry$mids = configEntry.mids) !== null && _configEntry$mids !== void 0 && _configEntry$mids.includes(mid));
      var isMatchVersion = compareVersion(sdkVersion, configEntry.minSDKVersion) >= 0;
      if (isMatchMid && isMatchVersion) {
        return configEntry;
      }
    });
    return targetConfigEntry;
  };
  var matchURLBySDKVersion = function matchURLBySDKVersion() {
    var sortedConfigs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var targetConfigEntry = sortedConfigs.find(function (configEntry) {
      var isCommonConfig = (configEntry === null || configEntry === void 0 ? void 0 : configEntry.mids) === undefined;
      var isMatchVersion = compareVersion(sdkVersion, configEntry.minSDKVersion) >= 0;
      if (isCommonConfig && isMatchVersion) {
        return configEntry;
      }
    });
    return targetConfigEntry;
  };
  var matchConfig = function matchConfig() {
    // 按SDK版本降排序
    var sortedConfig = configs.sort(function (a, b) {
      return compareVersion(b.minSDKVersion, a.minSDKVersion);
    });

    // 匹配仅针对部分商户生效(mid),且符合版本号的URL
    var matchedURLByMid = matchURLByMid(sortedConfig);
    if (matchedURLByMid) return matchedURLByMid;

    // 匹配对所有商户生效(无mid),且符合版本号的URL
    var matchedURLBySDKVersion = matchURLBySDKVersion(sortedConfig);
    if (matchedURLBySDKVersion) return matchedURLBySDKVersion;
  };
  var defaultEspUrl = getDefaultEasySafePayPageUrl(pageName, env);

  // 匹配config
  var config = matchConfig();
  if (!config) return defaultEspUrl;

  // 根据pageName匹配URL
  if (pageName === ESP_PAGE_NAME.SDK_PORTAL) return (config === null || config === void 0 ? void 0 : config.url) || defaultEspUrl;
  if (pageName === ESP_PAGE_NAME.DOUBLE_FA) return (config === null || config === void 0 ? void 0 : config.doubleFa) || defaultEspUrl;
  return defaultEspUrl;
};

/**
 * Retrieve the saved checkout URL from localStorage for the specified product scene.
 * If no url is found, a default checkout url string is returned.
 *
 * @param productScene - The product scene for which the checkout URL should be retrieved.
 */
export var getLocalCheckoutUrl = function getLocalCheckoutUrl(productScene, environment) {
  var key = KEY_CHECKOUT_URL + productScene;
  var previousCheckoutUrl = localStorage.getItem(key);
  return previousCheckoutUrl !== null && previousCheckoutUrl !== void 0 ? previousCheckoutUrl : defaultCheckoutUrl(productScene, environment);
};

/**
 * Provide default checkout URL for the specified product scene.
 * Return URL for 'EASY_PAY' product scene, while for other product scenes, it returns an empty string as they are not currently in use
 *
 * @param productScene - The product scene for which the default checkout URL should be provided.
 */
export var defaultCheckoutUrl = function defaultCheckoutUrl(productScene) {
  var environment = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'prod';
  switch (productScene) {
    case ProductSceneEnum.EASY_PAY:
      return getDefaultEasySafePayPageUrl(ESP_PAGE_NAME.SDK_PORTAL, environment);
    default:
      return '';
  }
};

/**
 * V2应用EasySafePay 热更新兜底URL构建规则
 **/
export var getDefaultEasySafePayPageUrl = function getDefaultEasySafePayPageUrl(pageName, env) {
  // 生成的URL EXAMPLE:
  // const DEFAULT_DOUBLE_FA_URL_MAPPING = {
  //   local: 'http://page.alipay.net/page/antom-web-checkout-v2/easysafepay/pages/double-fa/index.html',
  //   dev: 'http://page.alipay.net/page/antom-web-checkout-v2/easysafepay/pages/double-fa/index.html',
  //   sit: 'http://page.test.alipay.net/page/antom-web-checkout-v2/easysafepay/pages/double-fa/index.html',
  //   pre: 'https://pre.ac.alipay.com/page/antom-web-checkout-v2/easysafepay/pages/double-fa/index.html',
  //   prod: 'https://checkout.antom.com/easysafepay/pages/double-fa/index.html',
  // };
  var environment = env || 'prod';
  return "".concat(v2AppMarmotMap[environment], "/easysafepay/pages/").concat(pageName, "/index.html");
};

/**通过sessionData获取doubleFa,于createComponent时传递给WEB应用*/
//TODO 后续需要构造一个类，专门用于构造&存储web应用url
export var getDoubleFaUrlFromSession = function getDoubleFaUrlFromSession(paymentSessionObj) {
  var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'prod';
  var mid = paymentSessionObj.clientId;
  var extendInfo = paymentSessionObj.extendInfo;
  var configs = parseWebAppUrlMatchConfig(extendInfo);
  var url = matchEasySafePayV2Url({
    configs: configs,
    mid: mid,
    env: env,
    pageName: ESP_PAGE_NAME.DOUBLE_FA
  });
  return url;
};