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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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); }
/**
 * Copyright (c) 2022 International Business Group, Ant Group. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, and/or distribute the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 1. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE; and
 * 2. If applicable, the use of the Software is also subject to the terms and conditions of any non-disclosure agreement signed by you and the relevant Ant Group entity.
 */
import { getProxyCostTime } from "../../loader/utils/proxyPerformance";
import { marmotMap, sdkVersion, v2AppMarmotMap } from "../../config/index";
import { ComponentSignEnum, ComponentSignEnumV2 } from "../../types";
import { isDebugLog } from "../../util/debug";
import { queryParse, serialize } from "../../util/index";
import { Logger } from "../../util/logger";
import { getLastAppVersion, getMatchAppVersion, setLastAppVersion } from "../../util/upgrade";
export var getAppVersion = function getAppVersion(_extendInfo, productScene, mid) {
  var sendLog = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  try {
    var appVersion = getMatchAppVersion(_extendInfo, {
      sdkVersion: sdkVersion,
      productScene: productScene,
      mid: mid
    });
    if (sendLog) {
      var _Logger$getInstance;
      (_Logger$getInstance = Logger.getInstance()) === null || _Logger$getInstance === void 0 || _Logger$getInstance.logInfo({
        title: 'sdk_event_appUpgradeInfo'
      }, {
        appUpgradeVersion: appVersion,
        processResult: appVersion ? true : false,
        isPreload: _extendInfo ? false : true,
        config: _extendInfo,
        productScene: productScene,
        merchantId: mid
      });
    }

    // 没有匹配到版本，查询上次的加载版本
    if (!appVersion) {
      appVersion = getLastAppVersion(sdkVersion + productScene);
      return appVersion;
    }
    // 不为空时代表是有sessionData，因此要保存当前版本
    if (_extendInfo) {
      setLastAppVersion(sdkVersion + productScene, appVersion);
    }
    return appVersion;
  } catch (error) {
    return '';
  }
};
export var getFinalProductSceneVersion = function getFinalProductSceneVersion(componentSign, productSceneVersion) {
  var _signSupportMap;
  var signSupportMap = (_signSupportMap = {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_signSupportMap, 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(_signSupportMap, ComponentSignEnum.ELEMENT_ADDRESS, ['1.0']), ComponentSignEnum.CHECKOUT_PAYMENT, ['1.0.0']), ComponentSignEnum.AUTO_DEBIT_APM, ['1.0']));
  var supportProductSceneVersion = signSupportMap[componentSign] || [];
  // 从左到右，从旧到新
  var isSupport = supportProductSceneVersion.find(function (it) {
    return it === productSceneVersion;
  });
  var finalProductSceneVersion = supportProductSceneVersion[supportProductSceneVersion.length - 1];
  return isSupport ? productSceneVersion : finalProductSceneVersion;
};
export var getAppPath = function getAppPath() {
  var environment = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'prod';
  var appVersion = arguments.length > 1 ? arguments[1] : undefined;
  var componentSign = arguments.length > 2 ? arguments[2] : undefined;
  var productScene = arguments.length > 3 ? arguments[3] : undefined;
  var productSceneVersion = arguments.length > 4 ? arguments[4] : undefined;
  var extendInfo = arguments.length > 5 ? arguments[5] : undefined;
  var mid = arguments.length > 6 ? arguments[6] : undefined;
  var sendLog = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
  var elementLink = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : '';
  var _ref = queryParse() || {},
    urlTestHost = _ref.host;
  var upgradeAppVersion = getAppVersion(extendInfo, productScene, mid, sendLog);
  var finalAppVersion = upgradeAppVersion || appVersion;
  // 当有升级版本时，更新到全局字段
  if (upgradeAppVersion) {
    var _Logger$getInstance2;
    (_Logger$getInstance2 = Logger.getInstance()) === null || _Logger$getInstance2 === void 0 || _Logger$getInstance2.setMedta({
      webAppVersion: finalAppVersion
    });
  }
  if (isDebugLog()) {
    console.log('appUpgrade#getAppPath#finalAppVersion', finalAppVersion);
    console.log('appUpgrade#getAppPath#extendInfo', extendInfo, mid);
  }
  var finalProductSceneVersion = getFinalProductSceneVersion(componentSign, productSceneVersion);
  // only for test while testurl?host=https://xxxxx.test.html
  // 目前所有的elementProcessor中都会传入elementLink, 理论上Element场景该函数都会在这里直接返回
  if (elementLink) {
    return elementLink;
  }
  if (urlTestHost && !['sandbox', 'light_sandbox', 'prod'].includes(environment)) {
    return urlTestHost;
  }
  // 地址应用特殊处理
  if (componentSign === ComponentSignEnum.ELEMENT_ADDRESS) {
    return "".concat(v2AppMarmotMap[environment], "/element-address/pages/address/index.html");
  }
  // element应用特殊处理
  if (_toConsumableArray(Object.values(ComponentSignEnumV2)).includes(componentSign)) {
    // element又分为express_checkout模式和普通模式, express_checkout 模式在扩展参数是返回expressCheckout=true
    var isExpressCheckout = false;
    try {
      // expressCheckout可能出现string(false) JSON.parse再转一次
      isExpressCheckout = JSON.parse(JSON.parse(extendInfo).expressCheckout);
    } catch (error) {
      // 遇到JSON解析错误，默认false
    }
    if (isExpressCheckout) {
      // express_checkout模式走单独映射
      return "".concat(v2AppMarmotMap[environment], "/elements/pages/express_checkout/index.html");
    } else {
      return "".concat(v2AppMarmotMap[environment], "/elements/pages/").concat(productScene.toLowerCase(), "/index.html");
    }
  }
  return "".concat(marmotMap[environment], "/").concat(componentSign, "/").concat(finalProductSceneVersion, "/index.html");
};
export var getAppDomain = function getAppDomain(domainParams) {
  var environment = domainParams.environment,
    appVersion = domainParams.appVersion,
    componentSign = domainParams.componentSign,
    productScene = domainParams.productScene,
    productSceneVersion = domainParams.productSceneVersion,
    extendInfo = domainParams.extendInfo,
    mid = domainParams.mid,
    elementLink = domainParams.elementLink;
  var reg = /^https?:\/\/([^/<>\s]+\.?)*/;
  var macth = reg.exec(getAppPath(environment, appVersion, componentSign, productScene, productSceneVersion, extendInfo, mid, false, elementLink));
  return macth && macth[0] || '';
};
export var getIframeUrl = function getIframeUrl(iframeParams) {
  var componentSign = iframeParams.componentSign,
    _iframeParams$analyti = iframeParams.analytics,
    analytics = _iframeParams$analyti === void 0 ? {
      enabled: true
    } : _iframeParams$analyti,
    productScene = iframeParams.productScene,
    productSceneVersion = iframeParams.productSceneVersion,
    environment = iframeParams.environment,
    appVersion = iframeParams.appVersion,
    extendInfo = iframeParams.extendInfo,
    locale = iframeParams.locale,
    instanceId = iframeParams.instanceId,
    renderDisplayType = iframeParams.renderDisplayType,
    _iframeParams$isPrelo = iframeParams.isPreload,
    isPreload = _iframeParams$isPrelo === void 0 ? '' : _iframeParams$isPrelo,
    _iframeParams$hostSig = iframeParams.hostSign,
    hostSign = _iframeParams$hostSig === void 0 ? '' : _iframeParams$hostSig,
    _iframeParams$mid = iframeParams.mid,
    mid = _iframeParams$mid === void 0 ? '' : _iframeParams$mid,
    _iframeParams$element = iframeParams.elementLink,
    elementLink = _iframeParams$element === void 0 ? '' : _iframeParams$element;
  var path = getAppPath(environment, appVersion, componentSign, productScene, productSceneVersion, extendInfo || '', mid, true, elementLink);
  var appMatched = getMatchAppVersion(extendInfo, {
    sdkVersion: sdkVersion,
    productScene: productScene,
    mid: mid
  }) ? 'true' : 'false';
  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 = Object.assign({}, {
    displayType: renderDisplayType,
    locale: locale,
    instanceId: instanceId,
    appMatched: appMatched,
    analyticsEnabled: (analytics === null || analytics === void 0 ? void 0 : analytics.enabled) === false ? 'false' : 'true',
    sdkVersion: sdkVersion,
    refUrl: window.location.href,
    _componentStartTime: "".concat(Date.now()),
    _proxyCostTime: "".concat(getProxyCostTime(productScene)),
    isPreload: isPreload || '',
    hostSign: hostSign || ''
  });
  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', appMatched);
    console.log('appUpgrade#getIframeUrl#url', path, locationSearch);
  }
  return {
    path: path,
    locationSearch: locationSearch
  };
};

/**
 * @description Create iframe
 */
export var createIframe = function createIframe(mode, platform) {
  var getIframeId = function getIframeId() {
    var IdMap = {
      dropin: "ams-checkout-dropin-".concat(platform),
      component: "ams-checkout-component-".concat(platform)
    };
    return IdMap[mode] || 'ams-checkout-component';
  };
  var iframe = document.createElement('iframe');
  var iframeId = getIframeId();
  var none = '0';
  var width = '100%';
  iframe.id = iframeId;
  iframe.style.height = none;
  iframe.style.width = width;
  iframe.style.border = none;
  iframe.style.opacity = none;
  iframe.style.overflow = 'hidden';
  // iframe设置支持第三方支付
  iframe.allow = 'payment';
  return iframe;
};
export var createPreloadIframe = function createPreloadIframe(channelType, version) {
  var id = "ams-checkout-component-".concat(channelType, "-").concat(version);
  var iframe = document.createElement('iframe');
  var iframeId = id;
  var none = '1px';
  var width = '1px';
  iframe.id = iframeId;
  iframe.style.height = none;
  iframe.style.width = width;
  iframe.style.border = none;
  iframe.style.opacity = '0';
  iframe.style.overflow = 'hidden';
  return iframe;
};