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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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 { ERRORMESSAGE } from "../../../constant";
import { IElementStatus } from "../../../foundation";
import { getIframeUrl } from "../../../plugin/component/cashierApp";
import { DisplayTypeEnum, eventCodeEnum, RedirectType, TargetEnum, terminalTypeEnum } from "../../../types";
import { device } from "../../../util/index";
import CallApp from "../../../util/intl-callapp/es/main";
import { getComponentSign, parseSessionData } from "../index";
import { ELEMENT_ENVIRONMENT, EventCallbackCode } from "./type";
export var formatElementOption = function formatElementOption(options) {
  var environment = options.environment;
  return _objectSpread(_objectSpread({}, options), {}, {
    environment: (environment || ELEMENT_ENVIRONMENT.PROD).toLocaleLowerCase()
  });
};
export var validateElementOption = function validateElementOption(options) {
  var errors = [];
  if (!options.sessionData) {
    console.error('sessionData is empty, please check new AMSElement params.');
    errors.push({
      field: 'sessionData',
      message: 'sessionData is empty'
    });
  }
  if (errors.length > 0) {
    var _options$onEventCallb;
    options === null || options === void 0 || (_options$onEventCallb = options.onEventCallback) === null || _options$onEventCallb === void 0 || _options$onEventCallb.call(options, {
      code: EventCallbackCode.SDK_CREATE_COMPONENT_ERROR,
      message: 'sessionData is empty'
    });
  }
  return {
    isValid: errors.length === 0,
    errors: errors
  };
};

/**
 * 校验渲染条件
 * 1.校验当前 sdkSelector 结点是否存在
 * 2.校验当前 Element 的状态是否能够渲染
 * 3.校验当前 type 类型 Elment 是否已经执行过 mount
 */
export function checkCanMount(_ref) {
  var sdkSelector = _ref.sdkSelector,
    containerService = _ref.containerService,
    status = _ref.status;
  // 校验当前 sdkSelector 结点是否存在
  var element = document.querySelector(sdkSelector);
  if (!element) {
    console.error("Element with selector ".concat(sdkSelector, " not found."));
    return {
      success: false,
      errorMsg: "Element with selector ".concat(sdkSelector, " not found."),
      error: {
        code: ERRORMESSAGE.PARAM_INVALID.code,
        message: "Element with selector ".concat(sdkSelector, " not found.")
      }
    };
  }
  if (status === IElementStatus.DESTROYED) {
    return {
      success: false,
      errorMsg: "Creating components in the destroyed state is forbidden.",
      error: {
        code: ERRORMESSAGE.UI_STATE_ERROR.code,
        message: "Creating components in the destroyed state is forbidden."
      }
    };
  }
  if (status === IElementStatus.READY) {
    return {
      success: true
    };
  }
  if (containerService) {
    return {
      success: false,
      errorMsg: "SDK status error.",
      error: {
        code: ERRORMESSAGE.UI_STATE_ERROR.code,
        message: "SDK status error."
      }
    };
  }
  return {
    success: true
  };
}
export function checkCanUpdate(_ref2) {
  var _oldParseData$connect, _newParseData$connect;
  var status = _ref2.status,
    paymentContainerService = _ref2.paymentContainerService,
    newPaymentSessionData = _ref2.newPaymentSessionData,
    oldPaymentSessionData = _ref2.oldPaymentSessionData;
  // 检查当前容器的状态是否为 IElementStatus.IN_BIZ_FLOW
  if (status !== IElementStatus.IN_BIZ_FLOW) {
    return false;
  }

  // 检查支付容器服务是否存在
  if (!paymentContainerService) {
    return false;
  }
  // 检查update前后的connect状态是否相同
  var _parseSessionData = parseSessionData(oldPaymentSessionData),
    _parseSessionData2 = _slicedToArray(_parseSessionData, 1),
    oldParseData = _parseSessionData2[0];
  var _parseSessionData3 = parseSessionData(newPaymentSessionData),
    _parseSessionData4 = _slicedToArray(_parseSessionData3, 1),
    newParseData = _parseSessionData4[0];
  if (!(oldParseData !== null && oldParseData !== void 0 && oldParseData.connectFactor) || !(newParseData !== null && newParseData !== void 0 && newParseData.connectFactor)) {
    return false;
  }
  if ((oldParseData === null || oldParseData === void 0 || (_oldParseData$connect = oldParseData.connectFactor) === null || _oldParseData$connect === void 0 ? void 0 : _oldParseData$connect.enableConnect) !== (newParseData === null || newParseData === void 0 || (_newParseData$connect = newParseData.connectFactor) === null || _newParseData$connect === void 0 ? void 0 : _newParseData$connect.enableConnect)) {
    return false;
  }
  return true;
}
export function generateIframeSrc(_ref3) {
  var _paymentSessionObj$pa, _paymentSessionObj$pa2;
  var paymentSessionObj = _ref3.paymentSessionObj,
    paymentSession = _ref3.paymentSession,
    instanceId = _ref3.instanceId,
    environment = _ref3.environment,
    appVersion = _ref3.appVersion,
    analytics = _ref3.analytics,
    locale = _ref3.locale,
    pageUrl = _ref3.pageUrl,
    link = _ref3.link;
  var componentSign = getComponentSign(paymentSessionObj);
  var productSceneVersion = (paymentSessionObj === null || paymentSessionObj === void 0 || (_paymentSessionObj$pa = paymentSessionObj.paymentSessionConfig) === null || _paymentSessionObj$pa === void 0 ? void 0 : _paymentSessionObj$pa.productSceneVersion) || '';
  var productScene = (paymentSessionObj === null || paymentSessionObj === void 0 || (_paymentSessionObj$pa2 = paymentSessionObj.paymentSessionConfig) === null || _paymentSessionObj$pa2 === void 0 ? void 0 : _paymentSessionObj$pa2.productScene) || '';
  var extendInfo = (paymentSessionObj === null || paymentSessionObj === void 0 ? void 0 : paymentSessionObj.extendInfo) || '';
  var mid = paymentSessionObj === null || paymentSessionObj === void 0 ? void 0 : paymentSessionObj.clientId;
  var hostSign = (paymentSession || '').split('&&')[1] || '';
  var baseUrl = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, ELEMENT_ENVIRONMENT.DEV, 'http://page.alipay.net/page/antom-web-checkout-v2'), ELEMENT_ENVIRONMENT.TEST, 'http://page.test.alipay.net/page/antom-web-checkout-v2'), ELEMENT_ENVIRONMENT.SIT, 'http://page.test.alipay.net/page/antom-web-checkout-v2'), ELEMENT_ENVIRONMENT.PRE, 'https://pre.ac.alipay.com/page/antom-web-checkout-v2'), ELEMENT_ENVIRONMENT.SANDBOX, 'https://checkout.antom.com'), ELEMENT_ENVIRONMENT.PROD, 'https://checkout.antom.com');
  var _env = (environment === null || environment === void 0 ? void 0 : environment.toLocaleUpperCase()) || ELEMENT_ENVIRONMENT.DEV;
  if (!link) {
    link = "".concat(baseUrl[_env]).concat(pageUrl);
  }
  var _getIframeUrl = getIframeUrl({
      renderDisplayType: DisplayTypeEnum.inline,
      componentSign: componentSign,
      analytics: analytics,
      productScene: productScene,
      productSceneVersion: productSceneVersion,
      environment: environment,
      appVersion: appVersion,
      extendInfo: extendInfo,
      locale: locale,
      instanceId: instanceId,
      hostSign: hostSign,
      mid: mid,
      elementLink: link // TODO Connect本地调试link
    }),
    path = _getIframeUrl.path,
    locationSearch = _getIframeUrl.locationSearch;
  console.log('[debug] generateIframeSrc', path, locationSearch);
  return "".concat(path, "?").concat(locationSearch);
}
export function handleRedirect(data) {
  var _data$isDestroy, _data$isCallApp, _data$callAppDetectSu;
  var fromFastSdk = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var eventCallback = arguments.length > 2 ? arguments[2] : undefined;
  console.log('local payment sdk new element redirect arg ----', this);
  var _data = typeof data === 'string' ? {
    normalUrl: data
  } : _objectSpread(_objectSpread({}, data), {}, {
    applinkUrl: (data === null || data === void 0 ? void 0 : data.applinkUrl) || '',
    schemeUrl: (data === null || data === void 0 ? void 0 : data.schemeUrl) || '',
    normalUrl: (data === null || data === void 0 ? void 0 : data.normalUrl) || '',
    target: data === null || data === void 0 ? void 0 : data.target,
    isDestroy: (_data$isDestroy = data === null || data === void 0 ? void 0 : data.isDestroy) !== null && _data$isDestroy !== void 0 ? _data$isDestroy : true,
    isCallApp: (_data$isCallApp = data === null || data === void 0 ? void 0 : data.isCallApp) !== null && _data$isCallApp !== void 0 ? _data$isCallApp : false,
    callAppDetectSuccessDelay: (_data$callAppDetectSu = data === null || data === void 0 ? void 0 : data.callAppDetectSuccessDelay) !== null && _data$callAppDetectSu !== void 0 ? _data$callAppDetectSu : 2000
  });
  // const logParams = {
  //   applinkUrl: data?.applinkUrl || '',
  //   schemeUrl: data?.schemeUrl || '',
  //   normalUrl: data?.normalUrl || '',
  //   target: data?.target,
  //   isDestroy: data?.isDestroy ?? true,
  //   isCallApp: data?.isCallApp ?? false,
  //   callAppDetectSuccessDelay: data?.callAppDetectSuccessDelay ?? 2000,
  // };
  // this.AMSSDK.logger
  //   .logInfo(
  //     {
  //       title: 'sdk_event_call_url_start',
  //     },
  //     {
  //       redirectInfo: JSON.stringify(logParams),
  //     },
  //   )
  //   .send();
  var successCallback = function successCallback(type, url, durationInSeconds) {
    // TODO
    eventCallback({
      code: eventCodeEnum.SDK_CALL_URL_SUCCESS,
      message: "Successfully opened the app,".concat(type, ": ").concat(url)
    });
    var extra = {
      redirectInfo: JSON.stringify(_data),
      openType: type,
      url: url,
      fromFastSdk: fromFastSdk
    };
    if (durationInSeconds) {
      extra['durationInSeconds'] = durationInSeconds;
    }
    //   this.AMSSDK.logger
    //     .logInfo(
    //       {
    //         title: 'sdk_event_call_url_success',
    //       },
    //       extra,
    //     )
    //     .send();
  };
  var failCallback = function failCallback(type, url, durationInSeconds) {
    eventCallback({
      code: eventCodeEnum.SDK_LAUNCH_PAYMENT_APP_ERROR,
      message: "Failed to open app,applinkUrl: ".concat(_data === null || _data === void 0 ? void 0 : _data.applinkUrl, " schemeUrl: ").concat(_data === null || _data === void 0 ? void 0 : _data.schemeUrl, " normalUrl: ").concat(_data === null || _data === void 0 ? void 0 : _data.normalUrl)
    });
    var extra = {
      redirectInfo: JSON.stringify(_data),
      openType: type,
      url: url,
      fromFastSdk: fromFastSdk
    };
    if (durationInSeconds) {
      extra['durationInSeconds'] = durationInSeconds;
    }
    //   this.AMSSDK.logger
    //     .logInfo(
    //       {
    //         title: 'sdk_error_call_url_failed',
    //       },
    //       extra,
    //     )
    //     .send();
  };

  // 支持 target: _blank，新开tab页打开
  if (_data.target === TargetEnum.BLANK) {
    if (!_data.normalUrl) return failCallback(RedirectType.NormalUrl, '');
    successCallback(RedirectType.NormalUrl, _data.normalUrl);
    window.open(_data.normalUrl);
    return;
  }
  if (_data.target === TargetEnum.REPLACE && !(_data !== null && _data !== void 0 && _data.applinkUrl) && !(_data !== null && _data !== void 0 && _data.schemeUrl)) {
    if (!_data.normalUrl) return failCallback(RedirectType.NormalUrl, '');
    successCallback(RedirectType.NormalUrl, _data.normalUrl);
    window.location.replace(_data.normalUrl);
    return;
  }
  // TODO 销毁iframe和全局loading
  // if (_data?.isDestroy) this.cleanContainer();
  // 唤端
  if (_data !== null && _data !== void 0 && _data.isCallApp && _data !== null && _data !== void 0 && _data.schemeUrl) {
    var startCallAppTime = new Date();
    var detectSuccessDelay = typeof (data === null || data === void 0 ? void 0 : data.callAppDetectSuccessDelay) === 'number' ? data.callAppDetectSuccessDelay : 5000;
    redirect({
      schemeUrl: _data === null || _data === void 0 ? void 0 : _data.schemeUrl,
      callAppJudgeTime: detectSuccessDelay
    }).then(function () {
      var endCallAppTime = new Date();
      var durationInMilliseconds = endCallAppTime.getTime() - startCallAppTime.getTime();
      var durationInSeconds = durationInMilliseconds / 1000;
      successCallback(RedirectType.SchemeUrl, _data === null || _data === void 0 ? void 0 : _data.schemeUrl, durationInSeconds);
    }).catch(function () {
      var endCallAppTime = new Date();
      var durationInMilliseconds = endCallAppTime.getTime() - startCallAppTime.getTime();
      var durationInSeconds = durationInMilliseconds / 1000;
      failCallback(RedirectType.SchemeUrl, _data.schemeUrl, durationInSeconds);
    });
    return;
  }
  redirect({
    applinkUrl: _data === null || _data === void 0 ? void 0 : _data.applinkUrl,
    schemeUrl: _data === null || _data === void 0 ? void 0 : _data.schemeUrl,
    normalUrl: _data === null || _data === void 0 ? void 0 : _data.normalUrl
  }).then(function () {
    successCallback(RedirectType.NormalUrl, _data === null || _data === void 0 ? void 0 : _data.normalUrl);
  }).catch(function () {
    failCallback(RedirectType.NormalUrl, _data === null || _data === void 0 ? void 0 : _data.normalUrl);
  });
}
export function redirect(data) {
  return new Promise(function (resolve, reject) {
    var terminalType = device.isMobile ? terminalTypeEnum.WAP : terminalTypeEnum.WEB;
    var isWeb = terminalType === terminalTypeEnum.WEB;
    var normalUrl = (data === null || data === void 0 ? void 0 : data.normalUrl) || '';
    var schemeUrl = (data === null || data === void 0 ? void 0 : data.schemeUrl) || '';
    var applinkUrl = (data === null || data === void 0 ? void 0 : data.applinkUrl) || '';
    var callAppJudgeTime = (data === null || data === void 0 ? void 0 : data.callAppJudgeTime) || '';
    var jumpFunc = function jumpFunc() {
      if (normalUrl) {
        resolve();
        window.location.href = normalUrl;
        return;
      }
      reject(ERRORMESSAGE.SDK_LAUNCH_PAYMENT_APP_ERROR.CALL_APP_URL_ERROR);
    };
    var callAppFunc = function callAppFunc() {
      if (!schemeUrl && !applinkUrl) {
        jumpFunc();
        return;
      }
      var config = {
        fallback: function fallback() {
          jumpFunc();
        },
        successCb: function successCb() {
          resolve();
        },
        delay: 0
      };
      if (callAppJudgeTime) {
        config['resultJudgmentTime'] = callAppJudgeTime;
      }
      try {
        var callLib = new CallApp(config);
        callLib.open({
          scheme: schemeUrl,
          link: applinkUrl
        });
      } catch (error) {
        jumpFunc();
      }
    };
    if (isWeb) {
      jumpFunc();
    } else {
      callAppFunc();
    }
  });
}
export function showToast() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var callback = arguments.length > 1 ? arguments[1] : undefined;
  var createNode = function createNode() {
    var tag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div';
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var children = arguments.length > 2 ? arguments[2] : undefined;
    var node = document.createElement(tag);
    Object.keys(props).forEach(function (key) {
      if (key === 'style') {
        Object.keys(props[key]).forEach(function (styleKey) {
          node.style[styleKey] = props[key][styleKey];
        });
      } else {
        node.setAttribute(key, props[key]);
      }
    });
    if (typeof children === 'string') node.textContent = children;
    return node;
  };
  var defaultOptions = {
    position: 'bottom-right',
    backgroundColor: 'rgba(0, 0, 0, 0.80)',
    color: '#ffffff',
    padding: '20px 16px',
    borderRadius: '8px',
    fontSize: '14px',
    zIndex: 9999,
    width: '148px',
    duration: 2000
  };
  var defaultIcon = {
    SUCCESS: 'https://cdn.marmot-cloud.com/storage/2024/07/10/10b191d6-0b0a-4bd9-96cc-310b7f2a8530.svg',
    FAIL: 'https://cdn.marmot-cloud.com/storage/2024/11/08/4ae27343-61d2-4a07-b323-c951c7711b40.svg'
  };
  var config = _objectSpread(_objectSpread({}, defaultOptions), options);
  var container = document.getElementById('antom_toast-container');
  if (!container) {
    container = createNode('div', {
      style: {
        position: 'fixed',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        pointerEvents: 'none'
      },
      id: 'antom_toast-container'
    });
    document.body.appendChild(container);
  } else {
    container.innerHTML = '';
  }
  switch (config.position) {
    case 'top-left':
      container.style.top = '20px';
      container.style.left = '20px';
      break;
    case 'top-right':
      container.style.top = '20px';
      container.style.right = '20px';
      break;
    case 'bottom-left':
      container.style.bottom = '20px';
      container.style.left = '20px';
      break;
    case 'bottom-right':
    default:
      container.style.bottom = '0';
      container.style.right = '0';
      container.style.top = '0';
      container.style.left = '0';
      break;
  }
  var toast = createNode('div', {
    style: {
      backgroundColor: config.backgroundColor,
      color: config.color,
      padding: config.padding,
      borderRadius: config.borderRadius,
      fontSize: config.fontSize,
      opacity: '0',
      transition: 'opacity 0.3s ease-in-out',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'column',
      width: config.width,
      boxSizing: 'border-box'
    }
  });
  if (config.icon) {
    var icon = createNode('img', {
      style: {
        width: '40px',
        height: '40px'
      },
      src: config.icon ? defaultIcon[config.icon] : ''
    });
    toast.appendChild(icon);
  }
  var text = createNode('span', {
    style: {
      textAlign: 'center',
      marginTop: '12px',
      lineHeight: '20px',
      fontFamily: 'Noto Sans',
      fontWeight: 400,
      fontSize: '14px'
    }
  }, config.message);
  toast.appendChild(text);
  container.appendChild(toast);
  setTimeout(function () {
    toast.style.opacity = '1';
  }, 10);
  setTimeout(function () {
    toast.style.opacity = '0';
    setTimeout(function () {
      var _container;
      (_container = container) === null || _container === void 0 || _container.remove();
      callback && callback();
    }, 300);
  }, config.duration);
}
export var isElementMobile = function isElementMobile() {
  var userAgentInfo = navigator.userAgent;
  // webview 容器
  if (userAgentInfo.includes('AlipayWebViewClient')) {
    return true;
  }
  var agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPod', 'iPad'];
  return agents.some(function (agent) {
    return userAgentInfo.includes(agent);
  });
};

/**
 * @description judge whether the device is a pad, by userAgent and screen aspect ratio, but not accurate
 */
export var isElementPad = function isElementPad() {
  var userAgent = navigator.userAgent.toLowerCase();
  var width = window.screen.width;
  var height = window.screen.height;
  var aspectRatio = Math.min(width, height) / Math.max(width, height);
  var userAgentCheck = /ipad|tablet|(android(?!.*mobile))/i.test(userAgent);
  var screenCheck = aspectRatio > 0.5 && aspectRatio < 0.75 && width >= 768 && height >= 1024;
  return userAgentCheck || screenCheck;
};
export var isElementPC = function isElementPC() {
  return !isElementMobile();
};

/**
 * 判断是否需要加载错误页
 * @param {CashierSdkActionQueryResult} params
 * @returns {boolean} - 是否需要加载错误页
 */
export var isLoadErrorPage = function isLoadErrorPage(params) {
  var success = params.success,
    paymentMethods = params.paymentMethods,
    savedPaymentMethods = params.savedPaymentMethods,
    orderAmountView = params.orderAmountView,
    paymentAmountView = params.paymentAmountView;

  // 校验是否存在支付方式
  var hasValidPaymentMethods = paymentMethods && Array.isArray(paymentMethods) && paymentMethods.length > 0 || savedPaymentMethods && Array.isArray(savedPaymentMethods) && savedPaymentMethods.length > 0;

  // 金额存在性校验
  var hasAmountViews = !!orderAmountView && !!paymentAmountView;

  // 错误条件判断（满足任意条件即需要展示错误页）
  return !success ||
  // 接口请求失败
  !hasValidPaymentMethods ||
  // 无有效支付方式
  !hasAmountViews // 缺少金额展示
  ;
};
export var safeStringify = function safeStringify(payload) {
  var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  if (!payload) return defaultValue;
  try {
    return JSON.stringify(payload) || defaultValue;
  } catch (e) {
    console.error('JSON.stringify failed:', e);
    return defaultValue;
  }
};
export var safeParse = function safeParse(payload) {
  var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!payload) return defaultValue;
  try {
    return JSON.parse(payload) || defaultValue;
  } catch (e) {
    console.error('JSON.parse failed:', e);
    return defaultValue;
  }
};