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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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 { redirect } from "../../../util/redirect";
import { v4 as uuid } from 'uuid';
import { EnvironmentEnum, MessageName } from "../../../types";
import { queryParse } from "../../../util";
import { LogConfig, Logger } from "../../../util/logger";
var CKP_PAYMENT_PAGE_HOST = {
  DEV: 'https://dev.page.alipay.net',
  TEST: 'https://test.page.alipay.net',
  PRE: 'https://pre.ac.alipay.com',
  PROD: 'https://checkout.antom.com'
};

// for local development

var CKP_PAGE_ADDRESS = '/page/antom-web-checkout-v2/checkout-page/pages/payment/index.html';
var CKP_PAGE_NEW_ADDRESS = '/checkout-page/pages/payment/index.html';
export var getCKPPageAddress = function getCKPPageAddress(env) {
  switch (env) {
    case 'dev':
      return "".concat(CKP_PAYMENT_PAGE_HOST.DEV).concat(CKP_PAGE_ADDRESS);
    case 'sit':
      return "".concat(CKP_PAYMENT_PAGE_HOST.TEST).concat(CKP_PAGE_ADDRESS);
    case 'pre':
      return "".concat(CKP_PAYMENT_PAGE_HOST.PRE).concat(CKP_PAGE_ADDRESS);
    case 'prod':
    case 'sandbox':
    case 'light_sandbox':
      return "".concat(CKP_PAYMENT_PAGE_HOST.PROD).concat(CKP_PAGE_NEW_ADDRESS);
    default:
      // for local development, e.g. http://localhost:5173/checkout-page/src/pages/payment/index.html
      return env;
  }
};
export var AMSCheckoutPage = /*#__PURE__*/function () {
  function AMSCheckoutPage(options) {
    var _this = this;
    _classCallCheck(this, AMSCheckoutPage);
    _defineProperty(this, "logger", void 0);
    _defineProperty(this, "_instanceId", void 0);
    _defineProperty(this, "iframe", void 0);
    _defineProperty(this, "originOptions", void 0);
    _defineProperty(this, "APP_IFRAME_ID", 'antom-checkout-page-sub-page-iframe');
    _defineProperty(this, "eventListener", void 0);
    _defineProperty(this, "generateIframeSrc", function (sessionData) {
      var env = _this.originOptions.environment || 'prod';
      var session = sessionData || '';
      var lang = _this.originOptions.locale || 'en_US';
      var ckpPageAddress = getCKPPageAddress(env);
      console.log('[antom-web-sdk] <antom-checkout-page>  generateIframeSrc', _this.originOptions, env, session, lang, ckpPageAddress);

      // 先获取去除的 query 参数的 url
      var url = ckpPageAddress.split('?')[0];
      var queryObj = queryParse(ckpPageAddress);
      queryObj.sessionData = session;
      queryObj.lang = lang;
      queryObj.mode = 'embed';
      if (env === 'sandbox') {
        queryObj.shadow = 'true';
      }
      Object.keys(queryObj).forEach(function (key) {
        url += "".concat(url.includes('?') ? '&' : '?').concat(key, "=").concat(encodeURIComponent(queryObj[key]));
      });
      return url;
    });
    _defineProperty(this, "eventListenerWrapper", function (event) {
      var dataObj = JSON.parse(event.data) || {};
      var code = dataObj.code,
        message = dataObj.message,
        result = dataObj.result;
      var _ref = (dataObj === null || dataObj === void 0 ? void 0 : dataObj.context) || {
          event: '',
          data: {}
        },
        eventCode = _ref.event,
        data = _ref.data;
      if (eventCode && eventCode !== null && eventCode !== void 0 && eventCode.startsWith('getDomain')) {
        var _window, _window2;
        var hostname = (_window = window) === null || _window === void 0 || (_window = _window.location) === null || _window === void 0 ? void 0 : _window.hostname;
        _this.logger.logInfo({
          code: 'a3753.b146681',
          msg: hostname
        }).send();
        var content = _objectSpread(_objectSpread({}, dataObj === null || dataObj === void 0 ? void 0 : dataObj.context), {}, {
          data: {
            doMain: (_window2 = window) === null || _window2 === void 0 || (_window2 = _window2.location) === null || _window2 === void 0 ? void 0 : _window2.hostname
          },
          event: 'appEventCallback'
        });
        _this.dispatchToApp(content);
      }
      if (code && code.startsWith('SDK_PAYMENT')) {
        var _this$eventListener;
        console.log('[antom-web-sdk] <antom-checkout-page>  eventListenerWrapper', event, message, result);
        (_this$eventListener = _this.eventListener) === null || _this$eventListener === void 0 || _this$eventListener.call(_this, {
          code: code,
          message: message,
          result: result
        });
      }
      if (eventCode && eventCode !== null && eventCode !== void 0 && eventCode.startsWith('onRedirect')) {
        var _this$eventListener2;
        (_this$eventListener2 = _this.eventListener) === null || _this$eventListener2 === void 0 || _this$eventListener2.call(_this, {
          code: code,
          message: message,
          result: result
        });
        redirect(data).then(function () {
          var content = _objectSpread(_objectSpread({}, dataObj === null || dataObj === void 0 ? void 0 : dataObj.context), {}, {
            event: 'appEventCallback'
          });
          _this.dispatchToApp(content);
        });
      }
    });
    _defineProperty(this, "addListener", function () {
      window.addEventListener('message', _this.eventListenerWrapper);
    });
    _defineProperty(this, "removeListener", function () {
      window.removeEventListener('message', _this.eventListenerWrapper);
    });
    _defineProperty(this, "dispatchToApp", function (payloadContext) {
      var _this$iframe;
      var data = {
        name: MessageName.SDK_TO_APP,
        context: payloadContext
      };
      (_this$iframe = _this.iframe) === null || _this$iframe === void 0 || (_this$iframe = _this$iframe.contentWindow) === null || _this$iframe === void 0 || _this$iframe.postMessage(JSON.stringify(data), '*');
    });
    options.environment = options.environment || EnvironmentEnum.prod;
    this._instanceId = uuid();
    this.iframe = null;
    this.originOptions = options;
    this.eventListener = options.onEventCallback;
    this.logger = new Logger(LogConfig, ![EnvironmentEnum.prod, EnvironmentEnum.sandbox].includes(options === null || options === void 0 ? void 0 : options.environment));
    Logger.setInstance(this.logger);
    this.logger.setMedta({
      instanceId: this._instanceId
    });
    this.logger.initTracker();
    this.logger.setComponentStartTime(Date.now());
    this.logger.setTrackId(this._instanceId);
    this.logger.logInfo({
      title: 'NEW_AMSSDK_BY_MECHANT',
      msg: "".concat(options === null || options === void 0 ? void 0 : options.environment, "_").concat(options === null || options === void 0 ? void 0 : options.locale)
    }).send();
  }
  _createClass(AMSCheckoutPage, [{
    key: "mountComponent",
    value:
    /**
     * 挂载组件
     */
    function mountComponent(params, selector) {
      if (params.sessionData === undefined || params.sessionData === '' || typeof params.sessionData !== 'string') {
        this.logger.logError({
          title: 'event_important_error',
          msg: 'PARAMS_ERROR_INVALID_SESSION_DATA'
        });
        console.error('[antom-web-sdk] <antom-checkout-page>  mountComponent: sessionData is required and must be a string');
        throw new Error('PARAMS_ERROR_INVALID_SESSION_DATA');
      }
      if (document.querySelector(this.APP_IFRAME_ID)) {
        this.logger.logError({
          title: 'event_important_error',
          msg: 'PARAMS_ERROR_ALREADY_MOUNTED'
        });
        console.error('[antom-web-sdk] <antom-checkout-page>  mountComponent: already mounted, please unmount first');
        throw new Error('PARAMS_ERROR_ALREADY_MOUNTED');
      }
      this.addListener();
      var ckpPageAddress = this.generateIframeSrc(params.sessionData);
      var iframe = document.createElement('iframe');
      iframe.id = this.APP_IFRAME_ID;
      iframe.src = ckpPageAddress;
      // iframe设置支持第三方支付
      iframe.allow = 'payment';
      iframe.width = '100%';
      iframe.height = '100%';
      iframe.style.border = 'none';
      var wrapper = document.querySelector(selector);
      if (wrapper) {
        wrapper.innerHTML = '';
        wrapper.appendChild(iframe);
        this.iframe = iframe;
      } else {
        this.logger.logError({
          title: 'event_important_error',
          msg: 'PARAMS_ERROR_INVALID_SELECTOR'
        });
        console.error('[antom-web-sdk] <antom-checkout-page>  mountComponent: invalid selector');
        this.removeListener();
        throw new Error('PARAMS_ERROR_INVALID_SELECTOR');
      }
      return Promise.resolve();
    }

    /**
     * 卸载组件
     */
  }, {
    key: "unmount",
    value: function unmount() {
      this.removeListener();
      var iframe = document.getElementById(this.APP_IFRAME_ID);
      if (iframe) {
        iframe.remove();
      }
      return;
    }
  }]);
  return AMSCheckoutPage;
}();