var _excluded = ["type"];
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 _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 _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
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 { productEventScenarios, ProductScene } from "../config";
import { cleanMockup, removeRetentionPopup } from "../../../../component/component.popup.style";
import { destroyModal } from "../../../../component/popupWindow.style";
import { ERRORMESSAGE, EVENT, PROMISE_CALLBACK_CODE } from "../../../../constant";
import AddressProcessor from "../../../../core/component/element/elementProcessor/addressProcessor";
import AuthProcessor from "../../../../core/component/element/elementProcessor/authProcessor";
import PaymentProcessor from "../../../../core/component/element/elementProcessor/paymentProcessor";
import { IElementStatus } from "../../../../foundation";
import { AntomSDKCore } from "../../../../foundation/core";
import { ElementProcessor } from "../../../../foundation/product-processor/element";
import { ServiceProvider } from "../../../../foundation/service";
import { convertPaymentSession } from "../../../../foundation/utils/payment_context_utils";
import { ProductSceneEnum } from "../../../../types";
import { ELEMENT_SPM_MAP } from "../../../../util/spm-map";
import { ElementContainerService } from "../elementContainerService"; // 引入 ElementContainerService
import { IContainerStatus } from "../elementContainerService/containerService";
import { EventCenter as ElementEventCenter } from "../EventCenter/index";
import { oneAccountUpdate, sdkActionUpdate } from "../mock";
import { ElementPaymentEvent, ElementPaymentMethod, ElementType, EventCallbackCode, EXPOSURE_API_EVENT, MountElementType, PaymentStatus } from "../type";
import { checkCanMount, checkCanUpdate, handleRedirect, isLoadErrorPage, safeParse, safeStringify, showToast } from "../util";
var TIMEOUT_DURATION = 16000;
var ElementController = /*#__PURE__*/function () {
  function ElementController(options) {
    _classCallCheck(this, ElementController);
    _defineProperty(this, "options", void 0);
    _defineProperty(this, "elementContainer", void 0);
    _defineProperty(this, "serviceMap", void 0);
    _defineProperty(this, "loading", void 0);
    _defineProperty(this, "elementProcessors", void 0);
    _defineProperty(this, "initTimeout", void 0);
    _defineProperty(this, "elementContainerService", void 0);
    // 新增变量
    _defineProperty(this, "onStatusChangeCallback", void 0);
    // 新增变量
    _defineProperty(this, "submitPayPromise", void 0);
    _defineProperty(this, "elementEventCenter", void 0);
    _defineProperty(this, "onValidateFunc", function (event, target) {
      return new Promise(function (resolve) {
        event.emitAndListen({
          event: ElementPaymentEvent.VALIDATE,
          data: {
            params: {},
            target: target,
            source: ElementPaymentMethod.CONTAINER_ELEMENT
          }
        }, function (result) {
          resolve(result);
        });
      });
    });
    _defineProperty(this, "onValidateAndSubmitPay", function (event, target, params) {
      return new Promise(function (resolve) {
        event.emitAndListen({
          event: ElementPaymentEvent.SUBMIT_PAY,
          data: {
            params: _objectSpread(_objectSpread({}, params), {}, {
              doMain: window.location.hostname
              // sessionResult: this.parseData, 该参数在应用层好像没有使用 TODO
            }),
            target: target,
            source: ElementPaymentMethod.CONTAINER_ELEMENT
          }
        }, function (result) {
          resolve(result);
        });
      });
    });
    this.options = options;
    var _options = options;
    this.onStatusChangeCallback = _options === null || _options === void 0 ? void 0 : _options.onStatusChangeCallback;
    // 初始化 this.elementContainer 的 status 为 INITING
    this.elementContainer = new AntomSDKCore();
    this.elementContainer.registerProcessor(ProductSceneEnum.ELEMENT_PAYMENT, '', new ElementProcessor());
    // 初始化实例 id，监听 onRedirect 事件
    this.elementContainer.init(this.options, ProductSceneEnum.ELEMENT_PAYMENT);
    this.initService();
    this.elementContainerService = new ElementContainerService({
      instanceId: this.elementContainer.getInstanceId()
    });
    // status 设置为 READY
    this.setControllerStatusOrView(IElementStatus.READY);
    this.elementEventCenter = new ElementEventCenter({
      logger: this.elementContainer.getServiceProvider().getService('Log')
    });
  }
  _createClass(ElementController, [{
    key: "initService",
    value: function initService() {
      this.serviceMap = {
        Log: this.elementContainer.getServiceProvider().getService('Log'),
        EventCenter: this.elementContainer.getServiceProvider().getService('EventCenter'),
        Requester: this.elementContainer.getServiceProvider().getService('Requester')
      };
    }
  }, {
    key: "initElementProcessors",
    value: function initElementProcessors(elementType) {
      var processorMap = {
        auth: new AuthProcessor(this.options),
        address: new AddressProcessor(this.options),
        payment: new PaymentProcessor(this.options)
      };
      this.elementProcessors = _objectSpread(_objectSpread({}, this.elementProcessors), {}, _defineProperty({}, elementType, processorMap[elementType]));
      this.elementProcessors[elementType].registerElementContainer(this.elementContainer);
    }
  }, {
    key: "onEventCallback",
    value: function onEventCallback(_ref) {
      var _this$options, _this$options$onEvent;
      var code = _ref.code,
        _ref$message = _ref.message,
        message = _ref$message === void 0 ? '' : _ref$message,
        _ref$result = _ref.result,
        result = _ref$result === void 0 ? undefined : _ref$result;
      this.serviceMap.Log.logInfo({
        title: 'sdk_event_event_callback'
      }, {
        eventCode: safeStringify(code || ''),
        eventMessage: safeStringify(message || '')
      });
      this === null || this === void 0 || (_this$options = this.options) === null || _this$options === void 0 || (_this$options$onEvent = _this$options.onEventCallback) === null || _this$options$onEvent === void 0 || _this$options$onEvent.call(_this$options, {
        code: code,
        message: message,
        result: result
      });
    }
    /**
     * 处理初始化错误的方法
     */
  }, {
    key: "handleInitializationError",
    value: function handleInitializationError() {
      var errorCode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ERRORMESSAGE.SDK_LAUNCH_PAYMENT_APP_ERROR.CALL_APP_URL_ERROR;
      this.changeLoading(false);
      this.setControllerStatusOrView(IElementStatus.READY);
      this.onEventCallback(errorCode);
      this.elementContainerService.getContainerServices().forEach(function (value) {
        value.getContainerElement().remove();
      });
      this.elementContainerService.destroy();
    } // 处理挂载检查失败
  }, {
    key: "handleMountError",
    value: function handleMountError(_ref2) {
      var result = _ref2.result,
        resolve = _ref2.resolve;
      var errorMsg = result.errorMsg,
        error = result.error;
      this.onEventCallback({
        code: EventCallbackCode.SDK_CREATE_COMPONENT_ERROR,
        message: errorMsg
      });
      resolve({
        error: error
      });
    }

    // 清除并设置初始化定时器
  }, {
    key: "clearAndSetInitTimeout",
    value: function clearAndSetInitTimeout(resolve) {
      clearTimeout(this.initTimeout);
      this.initTimeout = null;
      this.initTimeout = this.setInitTimeout(resolve);
    }

    // Clears the pending init timeout to avoid timeout callbacks from stale Element instances.
  }, {
    key: "clearInitTimeout",
    value: function clearInitTimeout() {
      clearTimeout(this.initTimeout);
      this.initTimeout = null;
    }

    // Clears mount-related heartbeat events to avoid stale heartbeat reporting after abnormal exit.
  }, {
    key: "clearEvents",
    value: function clearEvents(reason) {
      var _this$elementEventCen, _this$elementEventCen2;
      // antlog examples: actionName=mount_end&msg=destroy, actionName=mount_end&msg=webLaunch
      (_this$elementEventCen = (_this$elementEventCen2 = this.elementEventCenter).cancelByPrefix) === null || _this$elementEventCen === void 0 || _this$elementEventCen.call(_this$elementEventCen2, 'mount', {
        msg: reason
      });
    }

    // 设置初始化超时定时器
  }, {
    key: "setInitTimeout",
    value: function setInitTimeout(resolve) {
      var _this = this;
      return setTimeout(function () {
        clearTimeout(_this.initTimeout);
        _this.initTimeout = null;
        _this.handleInitializationError(ERRORMESSAGE.SDK_LAUNCH_PAYMENT_APP_ERROR.LOAD_APP_TIME_OUT);
        _this.serviceMap.Log.logInfo({
          title: 'sdk_event_web_app_timeout'
        });
        resolve({
          error: ERRORMESSAGE.INITIALIZE_TIMEOUT.WEB
        });
      }, TIMEOUT_DURATION);
    }

    // 初始化并挂载元素处理器
  }, {
    key: "initializeAndMountProcessor",
    value: function initializeAndMountProcessor(type, selector, options) {
      this.initElementProcessors(type);
      // 创建 iframe，拉起应用页面，同时监听全局的数据更新和获取事件
      this.elementContainerService.mount({
        type: type,
        selector: selector,
        processor: this.elementProcessors[type],
        options: options
      });
      this.elementProcessors[type].registerEventCenter(this.elementContainerService.getEventService(type));
      // 渲染后instance已变更，更新埋点源数据，修复埋点没有sessionData的问题
      var newInstanceId = this.elementContainerService.getContainerService(type).getInstanceId();
      var paymentContext = this.elementContainer.getPaymentContext();
      ServiceProvider.getInstance(newInstanceId).update(paymentContext);
      // 更新埋点service
      this.serviceMap.Log = ServiceProvider.getInstance(newInstanceId).getService('Log');
      this.elementProcessors[type].beforeMount();
    }
    // 处理业务流程启动失败
  }, {
    key: "handleStartBizFlowError",
    value: function handleStartBizFlowError(error, readyCallback) {
      readyCallback({
        error: _objectSpread(_objectSpread({}, ERRORMESSAGE.PARAM_INVALID), {}, {
          context: JSON.stringify(error)
        })
      });
      this.onEventCallback({
        code: EventCallbackCode.SDK_CREATEPAYMENT_PARAMETER_ERROR,
        message: (error === null || error === void 0 ? void 0 : error.message) || 'Initialization parameter exception.'
      });
      clearTimeout(this.initTimeout);
      this.initTimeout = null;
      this.changeLoading(false);
    }
  }, {
    key: "mount",
    value: function mount(renderOptions, sdkSelector) {
      var _this2 = this;
      // 此处的 id 是 sessionData && 分割的前3位
      var _convertPaymentSessio = convertPaymentSession(this.options.sessionData),
        sessionData = _convertPaymentSessio.id;
      var startEventId = this.elementEventCenter.registerEvent(EXPOSURE_API_EVENT.MOUNT, sessionData);
      return new Promise(function (resolve) {
        var checkMountResult = checkCanMount({
          sdkSelector: sdkSelector,
          status: _this2.elementContainer.getStatus(),
          containerService: _this2.elementContainerService.getContainerService(renderOptions.type)
        });
        var readyCallback = function readyCallback(payload) {
          _this2.elementEventCenter.endEvent(startEventId, {
            msg: safeStringify(payload)
          });
          resolve(_objectSpread({}, payload || {}));
        };
        if (!checkMountResult.success) {
          _this2.handleMountError({
            result: checkMountResult,
            resolve: readyCallback
          });
          return;
        }
        _this2.clearAndSetInitTimeout(readyCallback);
        // 回调 loading 的 onStartLoading
        _this2.changeLoading(true);
        try {
          var startBizFlowData = {
            paymentSession: _this2.options.sessionData,
            displayInfo: _objectSpread(_objectSpread({}, renderOptions), {}, {
              appendAliasContainerId: true
            })
          };
          // status 设置为 IN_BIZ_FLOW
          _this2.setControllerStatusOrView(IElementStatus.IN_BIZ_FLOW);
          _this2.elementContainer.startBizFlow(startBizFlowData);
          // 创建 iframe 加载应用页面
          _this2.initializeAndMountProcessor(renderOptions.type, sdkSelector, renderOptions);
          // 监听应用页面 onLaunch 事件，请求 sdkAction.query 接口的数据，请求完成后处理数据异常情况或发送 renderComponent 事件及数据给应用层渲染页面内容
          _this2.sendRequestAndWaitWebLaunch(renderOptions, readyCallback);
          // 监听事件
          _this2.addEventListener(readyCallback);
          _this2.serviceMap.EventCenter.addIFrame(_this2.elementContainerService.getContainerService(renderOptions.type).getContainerService().getWebApp());
        } catch (error) {
          _this2.handleStartBizFlowError(error, readyCallback);
        }
      });
    }
  }, {
    key: "validateFields",
    value: (
    /**
     * 25/09/08 新增商户主动校验api
     * @returns {Promise<{isValid: boolean}>}
     */
    function () {
      var _validateFields = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
        var startEventId, result, _this$elementProcesso, _validateResult$data, validateResult;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              startEventId = this.elementEventCenter.registerEvent(EXPOSURE_API_EVENT.VALIDATAFIELDS);
              result = {
                isValid: false
              };
              _context.prev = 2;
              if (!(this.initTimeout || !((_this$elementProcesso = this.elementProcessors) !== null && _this$elementProcesso !== void 0 && _this$elementProcesso[ElementType.payment]))) {
                _context.next = 5;
                break;
              }
              return _context.abrupt("return", result);
            case 5:
              _context.next = 7;
              return this.onValidateFunc(this.elementProcessors[ElementType.payment].eventCenter, ElementPaymentMethod.PAYMENT_ELEMENT);
            case 7:
              validateResult = _context.sent;
              result = (_validateResult$data = validateResult.data) !== null && _validateResult$data !== void 0 ? _validateResult$data : {
                isValid: false
              };
              return _context.abrupt("return", result);
            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](2);
              return _context.abrupt("return", result);
            case 15:
              _context.prev = 15;
              this.elementEventCenter.endEvent(startEventId, result);
              return _context.finish(15);
            case 18:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[2, 12, 15, 18]]);
      }));
      function validateFields() {
        return _validateFields.apply(this, arguments);
      }
      return validateFields;
    }())
  }, {
    key: "submitPayment",
    value: function () {
      var _submitPayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(submitParams) {
        var _this3 = this;
        var startEventId, res, logParams, recordResult, _recordResult, _recordResult2, _recordResult3, _recordResult4, _recordResult5, _logParams;
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              startEventId = this.elementEventCenter.registerEvent(EXPOSURE_API_EVENT.SUBMITPAYMENT);
              if (!(this.elementContainer.getStatus() !== IElementStatus.IN_BIZ_FLOW)) {
                _context4.next = 6;
                break;
              }
              res = {
                error: _objectSpread(_objectSpread({}, ERRORMESSAGE.UI_STATE_ERROR), {}, {
                  needChangeSessionForRetry: false
                }),
                status: PaymentStatus.FAIL
              };
              logParams = {
                eventCode: PaymentStatus.FAIL,
                errorName: ERRORMESSAGE.UI_STATE_ERROR.code,
                needChangeSessionForRetry: false,
                msg: safeStringify(res)
              };
              this.elementEventCenter.endEvent(startEventId, logParams);
              return _context4.abrupt("return", Promise.resolve(res));
            case 6:
              this.changeLoading(true);
              recordResult = null;
              _context4.prev = 8;
              _context4.next = 11;
              return new Promise( /*#__PURE__*/function () {
                var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(resolve) {
                  var that, recordResultCallback, params, processStep, _submitParams$handleA, _yield$_this3$onValid2, _data, errorString, errorResult;
                  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
                    while (1) switch (_context3.prev = _context3.next) {
                      case 0:
                        recordResultCallback = function _recordResultCallback(result) {
                          if (result instanceof Object) {
                            var _result$error, _that$elementProcesso, _result$error2;
                            var needChangeSessionForRetry = typeof (result === null || result === void 0 || (_result$error = result.error) === null || _result$error === void 0 ? void 0 : _result$error.needChangeSessionForRetry) === 'undefined' ? (_that$elementProcesso = that.elementProcessors[ElementType.payment]) === null || _that$elementProcesso === void 0 || (_that$elementProcesso = _that$elementProcesso.obtainDataRes) === null || _that$elementProcesso === void 0 || (_that$elementProcesso = _that$elementProcesso.originActionQueryResult) === null || _that$elementProcesso === void 0 ? void 0 : _that$elementProcesso.notSupportRetryPayForSameSession : result === null || result === void 0 || (_result$error2 = result.error) === null || _result$error2 === void 0 ? void 0 : _result$error2.needChangeSessionForRetry;
                            if (result !== null && result !== void 0 && result.error) {
                              result.error.needChangeSessionForRetry = needChangeSessionForRetry;
                            }
                          }
                          recordResult = result;
                          resolve(recordResult);
                        };
                        that = _this3;
                        _context3.prev = 2;
                        _this3.submitPayPromise = recordResultCallback;
                        params = {}; // 统一处理逻辑
                        processStep = /*#__PURE__*/function () {
                          var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(elementType, method) {
                            var _yield$_this3$onValid, data;
                            return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                              while (1) switch (_context2.prev = _context2.next) {
                                case 0:
                                  if (_this3.elementProcessors[elementType]) {
                                    _context2.next = 2;
                                    break;
                                  }
                                  return _context2.abrupt("return", true);
                                case 2:
                                  _context2.next = 4;
                                  return _this3.onValidateAndSubmitPay(_this3.elementProcessors[elementType].eventCenter, method);
                                case 4:
                                  _yield$_this3$onValid = _context2.sent;
                                  data = _yield$_this3$onValid.data;
                                  params.shipping = data === null || data === void 0 ? void 0 : data.data;
                                  if (data !== null && data !== void 0 && data.success) {
                                    _context2.next = 11;
                                    break;
                                  }
                                  // TODO 先快速修复类型, 这里结构和标准返回不一致 @马杰
                                  recordResult = data;
                                  recordResultCallback(recordResult);
                                  return _context2.abrupt("return", false);
                                case 11:
                                  return _context2.abrupt("return", true);
                                case 12:
                                case "end":
                                  return _context2.stop();
                              }
                            }, _callee2);
                          }));
                          return function processStep(_x3, _x4) {
                            return _ref4.apply(this, arguments);
                          };
                        }(); // 按顺序处理步骤
                        _context3.next = 8;
                        return processStep(ElementType.auth, ElementPaymentMethod.AUTH_ELEMENT);
                      case 8:
                        if (_context3.sent) {
                          _context3.next = 10;
                          break;
                        }
                        return _context3.abrupt("return");
                      case 10:
                        _context3.next = 12;
                        return processStep(ElementType.address, ElementPaymentMethod.ADDRESS_ELEMENT);
                      case 12:
                        if (_context3.sent) {
                          _context3.next = 14;
                          break;
                        }
                        return _context3.abrupt("return");
                      case 14:
                        if (!_this3.elementProcessors[ElementType.payment]) {
                          _context3.next = 21;
                          break;
                        }
                        _context3.next = 17;
                        return _this3.onValidateAndSubmitPay(_this3.elementProcessors[ElementType.payment].eventCenter, ElementPaymentMethod.PAYMENT_ELEMENT, _objectSpread(_objectSpread({}, params), {}, {
                          handleActions: (_submitParams$handleA = submitParams === null || submitParams === void 0 ? void 0 : submitParams.handleActions) !== null && _submitParams$handleA !== void 0 ? _submitParams$handleA : true,
                          shipping: submitParams === null || submitParams === void 0 ? void 0 : submitParams.shippingInfo
                        }));
                      case 17:
                        _yield$_this3$onValid2 = _context3.sent;
                        _data = _yield$_this3$onValid2.data;
                        // TODO 先快速修复类型, 这里结构和标准返回不一致 @马杰
                        // TODO checkout 返回的错误未包含 status 和 message @马杰 @薛浩
                        recordResult = _data;
                        recordResultCallback(recordResult);
                      case 21:
                        _context3.next = 30;
                        break;
                      case 23:
                        _context3.prev = 23;
                        _context3.t0 = _context3["catch"](2);
                        // 修复error为{}空对象的问题，上报stack&message
                        errorString = JSON.stringify(_context3.t0, Object.getOwnPropertyNames(_context3.t0));
                        errorResult = {
                          error: _objectSpread(_objectSpread({}, ERRORMESSAGE.ERR_DATA_STRUCT_UNRECOGNIZED), {}, {
                            context: errorString
                          }),
                          status: PaymentStatus.FAIL
                        };
                        _this3.serviceMap.Log.logError({
                          title: ELEMENT_SPM_MAP.sdk_element_missKeyData
                        }, {
                          msg: JSON.stringify(errorResult)
                        });
                        recordResult = errorResult;
                        recordResultCallback(errorResult);
                      case 30:
                      case "end":
                        return _context3.stop();
                    }
                  }, _callee3, null, [[2, 23]]);
                }));
                return function (_x2) {
                  return _ref3.apply(this, arguments);
                };
              }());
            case 11:
              return _context4.abrupt("return", _context4.sent);
            case 12:
              _context4.prev = 12;
              _logParams = {
                eventCode: (_recordResult = recordResult) === null || _recordResult === void 0 ? void 0 : _recordResult.status,
                errorName: (_recordResult2 = recordResult) === null || _recordResult2 === void 0 || (_recordResult2 = _recordResult2.error) === null || _recordResult2 === void 0 ? void 0 : _recordResult2.code,
                errormessage: (_recordResult3 = recordResult) === null || _recordResult3 === void 0 || (_recordResult3 = _recordResult3.error) === null || _recordResult3 === void 0 ? void 0 : _recordResult3.message,
                needChangeSessionForRetry: (_recordResult4 = recordResult) === null || _recordResult4 === void 0 || (_recordResult4 = _recordResult4.error) === null || _recordResult4 === void 0 ? void 0 : _recordResult4.needChangeSessionForRetry,
                rpcTraceId: (_recordResult5 = recordResult) === null || _recordResult5 === void 0 || (_recordResult5 = _recordResult5.error) === null || _recordResult5 === void 0 ? void 0 : _recordResult5.traceId,
                msg: safeStringify(recordResult)
              };
              this.elementEventCenter.endEvent(startEventId, _logParams);
              this.changeLoading(false);
              return _context4.finish(12);
            case 17:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this, [[8,, 12, 17]]);
      }));
      function submitPayment(_x) {
        return _submitPayment.apply(this, arguments);
      }
      return submitPayment;
    }()
  }, {
    key: "changeLoading",
    value: function changeLoading(loading) {
      if (loading) {
        var _this$options$loading;
        if ((_this$options$loading = this.options.loading) !== null && _this$options$loading !== void 0 && _this$options$loading.onStartLoading && !this.loading) {
          var _this$options$loading2, _this$options$loading3;
          this.loading = true;
          (_this$options$loading2 = this.options.loading) === null || _this$options$loading2 === void 0 || (_this$options$loading3 = _this$options$loading2.onStartLoading) === null || _this$options$loading3 === void 0 || _this$options$loading3.call(_this$options$loading2);
        }
      } else {
        var _this$options$loading4;
        if ((_this$options$loading4 = this.options.loading) !== null && _this$options$loading4 !== void 0 && _this$options$loading4.onEndLoading && this.loading) {
          var _this$options$loading5, _this$options$loading6;
          (_this$options$loading5 = this.options.loading) === null || _this$options$loading5 === void 0 || (_this$options$loading6 = _this$options$loading5.onEndLoading) === null || _this$options$loading6 === void 0 || _this$options$loading6.call(_this$options$loading5);
        }
        this.loading = false;
      }
    }
  }, {
    key: "addEventListener",
    value: function addEventListener(renderCallback) {
      var _this4 = this;
      this.serviceMap.EventCenter.listen(ElementPaymentEvent.ON_EVENT_CALLBACK, function (data) {
        var _this4$onEventCallbac;
        (_this4$onEventCallbac = _this4.onEventCallback) === null || _this4$onEventCallbac === void 0 || _this4$onEventCallbac.call(_this4, data);
      });
      this.serviceMap.EventCenter.listen(EVENT.sizeChanged.name, function (data) {
        clearTimeout(_this4.initTimeout);
        _this4.initTimeout = null;
        if (_this4.elementContainerService.getContainerService(data.source)) {
          renderCallback();
          _this4.elementContainerService.getContainerService(data.source).switchContainerStatus(IContainerStatus.IN_BIZ_FLOW);
        }
        _this4.changeLoading(false);
        // 遍历containerService中的所有container查看是否所有状态都是IN_BIZ_FLOW
        // const allContainersInBizFlow = Object.values(this.elementContainerService.getContainerServices()).every(
        //   (containerService) => containerService.getContainerStatus() === IContainerStatus.IN_BIZ_FLOW,
        // );
        // if (allContainersInBizFlow) {
        //   this.setControllerStatusOrView(IContainerStatus.IN_BIZ_FLOW);
        // }
      });
      this.serviceMap.EventCenter.listen(EVENT.redirect.name, function (data) {
        var onEventCallback = _this4.onEventCallback.bind(_this4);
        handleRedirect(data, false, onEventCallback);
      });
      this.serviceMap.EventCenter.listen(EVENT.destroy.name, function () {
        _this4.changeLoading(false);
        _this4.setControllerStatusOrView(IElementStatus.READY);
        _this4.destroyHandle();
      });
      this.serviceMap.EventCenter.listen(EVENT.webAppReady.name, function (data) {
        clearTimeout(_this4.initTimeout);
        _this4.initTimeout = null;
        if (_this4.elementContainerService.getContainerService(data.source)) {
          renderCallback();
          _this4.elementContainerService.getContainerService(data.source).switchContainerStatus(IContainerStatus.IN_BIZ_FLOW);
        }
        _this4.changeLoading(false);
      });
      this.serviceMap.EventCenter.listen(EVENT.showToast.name, function (data) {
        showToast(data);
      });
      this.serviceMap.EventCenter.listen(EVENT.messageForward.name, function (data) {
        var source = MountElementType[data.source];
        var target = MountElementType[data.target];
        if (_this4.elementProcessors[source] && _this4.elementProcessors[target]) {
          _this4.elementProcessors[target].eventCenter.dispatchToApp({
            event: data.event,
            data: data
          });
        }
      });
      this.serviceMap.EventCenter.listen(EVENT.submitPromiseCallback.name, function (data) {
        var _this4$submitPayPromi;
        (_this4$submitPayPromi = _this4.submitPayPromise) === null || _this4$submitPayPromi === void 0 || _this4$submitPayPromi.call(_this4, data);
      });
    }
  }, {
    key: "sendRequestAndWaitWebLaunch",
    value: function () {
      var _sendRequestAndWaitWebLaunch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(renderOptions, readyCallback) {
        var _this5 = this;
        var type, options, containerService, _yield$Promise$all, _yield$Promise$all2, _, obtainDataResult, errorResult;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              type = renderOptions.type, options = _objectWithoutProperties(renderOptions, _excluded);
              _context5.prev = 1;
              containerService = this.elementContainerService.getContainerService(type);
              if (containerService) {
                _context5.next = 7;
                break;
              }
              this.handleInitializationError(ERRORMESSAGE.SDK_LAUNCH_PAYMENT_APP_ERROR.CONTAINER_NOT_EXIST);
              // 容器服务不存在，直接返回
              readyCallback({
                error: ERRORMESSAGE.UI_STATE_ERROR
              });
              return _context5.abrupt("return");
            case 7:
              _context5.next = 9;
              return Promise.all([containerService.createWebLaunchPromise(),
              // 监听 onLaunch 事件
              this.elementProcessors[type].obtainData() // 请求 sdkAction.query 的数据，connect 还会请求 account.query
              ]);
            case 9:
              _yield$Promise$all = _context5.sent;
              _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
              _ = _yield$Promise$all2[0];
              obtainDataResult = _yield$Promise$all2[1];
              this.serviceMap.Log.logInfo({
                title: 'sdk_event_webAppOnLaunch'
              });
              // 应用页面加载完成且接口请求完成，状态设置为 READY
              containerService === null || containerService === void 0 || containerService.switchContainerStatus(IContainerStatus.READY);
              // 处理接口数据异常情况，直接回调，结束流程
              errorResult = this.getErrorFromResponse(obtainDataResult);
              if (errorResult) {
                // 仅结束resolve，传出回调码
                readyCallback(errorResult);
              }
              // 页面加载和数据状态 READY 后，SDK 向应用层发送 renderComponent 事件，传递应用层渲染必须的数据
              if (this.areAllContainersReady()) {
                this.elementContainerService.getContainerServices().forEach(function (_, key) {
                  _this5.sendReady(key, options);
                });
              }
              _context5.next = 26;
              break;
            case 20:
              _context5.prev = 20;
              _context5.t0 = _context5["catch"](1);
              this.handleInitializationError();
              // Fix: when request processing enters the catch path (excluding success=false business responses),
              // stale timeout and heartbeat events must be cleared to avoid duplicate error callbacks.
              this.clearInitTimeout();
              this.clearEvents('webLaunch');
              readyCallback({
                error: _objectSpread(_objectSpread({}, ERRORMESSAGE.INITIALIZE_TIMEOUT.API), {}, {
                  traceId: _context5.t0 === null || _context5.t0 === void 0 ? void 0 : _context5.t0.traceId
                })
              });
            case 26:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this, [[1, 20]]);
      }));
      function sendRequestAndWaitWebLaunch(_x5, _x6) {
        return _sendRequestAndWaitWebLaunch.apply(this, arguments);
      }
      return sendRequestAndWaitWebLaunch;
    }()
  }, {
    key: "getErrorFromResponse",
    value: function getErrorFromResponse(response) {
      if (isLoadErrorPage(response === null || response === void 0 ? void 0 : response.originActionQueryResult)) {
        var _response$originActio = response.originActionQueryResult,
          traceId = _response$originActio.traceId,
          errorCode = _response$originActio.errorCode,
          errorMessage = _response$originActio.errorMessage;
        var error = {
          code: errorCode,
          message: errorMessage || ERRORMESSAGE.ERR_DATA_STRUCT_UNRECOGNIZED.message
        };
        if (!errorCode) {
          error = _objectSpread({}, ERRORMESSAGE.ERR_DATA_STRUCT_UNRECOGNIZED);
        }
        if (PROMISE_CALLBACK_CODE[errorCode]) {
          var _PROMISE_CALLBACK_COD;
          error = {
            code: PROMISE_CALLBACK_CODE[errorCode].code,
            message: ((_PROMISE_CALLBACK_COD = PROMISE_CALLBACK_CODE[errorCode]) === null || _PROMISE_CALLBACK_COD === void 0 ? void 0 : _PROMISE_CALLBACK_COD.message) || errorMessage
          };
        } else {
          this.serviceMap.Log.logError({
            title: ELEMENT_SPM_MAP.sdk_element_missKeyData
          }, {
            rpcTraceId: traceId
          });
        }
        return {
          error: _objectSpread(_objectSpread({}, error), {}, {
            traceId: traceId !== null && traceId !== void 0 ? traceId : ''
          })
        };
      }
      return null;
    }
  }, {
    key: "areAllContainersReady",
    value: function areAllContainersReady() {
      var container = this.elementContainerService.getContainerServices();
      return _toConsumableArray(container.values()).every(function (service) {
        return service.getContainerStatus() === IContainerStatus.READY;
      });
    }
  }, {
    key: "sendReady",
    value: function sendReady(type, options) {
      var _this$elementProcesso2, _paymentSessionObj$co, _paymentSessionObj$pa, _paymentResult$origin;
      var paymentResult = (_this$elementProcesso2 = this.elementProcessors[ElementType.payment]) === null || _this$elementProcesso2 === void 0 ? void 0 : _this$elementProcesso2.getObtainDataRes();
      var paymentContext = this.elementContainer.getPaymentContext();
      var paymentSessionObj = paymentContext.paymentSessionObj;
      var isConnect = ((_paymentSessionObj$co = paymentSessionObj.connectFactor) === null || _paymentSessionObj$co === void 0 ? void 0 : _paymentSessionObj$co.enableConnect) && ((_paymentSessionObj$pa = paymentSessionObj.paymentSessionConfig) === null || _paymentSessionObj$pa === void 0 ? void 0 : _paymentSessionObj$pa.productScene) === ProductSceneEnum.ELEMENT_PAYMENT;
      if (!(paymentResult !== null && paymentResult !== void 0 && (_paymentResult$origin = paymentResult.originActionQueryResult) !== null && _paymentResult$origin !== void 0 && _paymentResult$origin.success) && isConnect) {
        var _this$onEventCallback;
        clearTimeout(this.initTimeout);
        this.changeLoading(false);
        this.initTimeout = null;
        (_this$onEventCallback = this.onEventCallback) === null || _this$onEventCallback === void 0 || _this$onEventCallback.call(this, {
          code: EventCallbackCode.SDK_CREATE_COMPONENT_ERROR,
          message: 'Component initialization exception.'
        });
        this.destroy();
        return;
      }
      var params = _objectSpread(_objectSpread({}, options), {}, {
        originActionQueryResult: paymentResult === null || paymentResult === void 0 ? void 0 : paymentResult.originActionQueryResult,
        originOneAccountQueryResult: paymentResult === null || paymentResult === void 0 ? void 0 : paymentResult.originOneAccountQueryResult,
        paymentSessionData: paymentContext === null || paymentContext === void 0 ? void 0 : paymentContext.paymentSessionId,
        sessionResult: (paymentContext === null || paymentContext === void 0 ? void 0 : paymentContext.paymentSessionObj) || {}
      });
      this.elementProcessors[type].onReady(params);
    }
  }, {
    key: "updatePayment",
    value: function () {
      var _updatePayment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(paymentSessionData) {
        var _this6 = this;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              return _context7.abrupt("return", new Promise( /*#__PURE__*/function () {
                var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(resolve) {
                  var prePaymentSessionData, data, LOCAL_MOCK;
                  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
                    while (1) switch (_context6.prev = _context6.next) {
                      case 0:
                        if (checkCanUpdate({
                          status: _this6.elementContainer.getStatus(),
                          paymentContainerService: _this6.elementContainerService.getContainerService(ElementType.payment),
                          newPaymentSessionData: paymentSessionData,
                          oldPaymentSessionData: _this6.options.sessionData
                        })) {
                          _context6.next = 2;
                          break;
                        }
                        return _context6.abrupt("return", resolve(false));
                      case 2:
                        prePaymentSessionData = _this6.elementContainer.getPaymentContext().paymentSession;
                        _this6.elementContainer.updatePaymentSessionData(paymentSessionData);
                        // 1、数据获取
                        _context6.next = 6;
                        return _this6.elementProcessors[ElementType.payment].obtainData();
                      case 6:
                        data = _context6.sent;
                        LOCAL_MOCK = window.location.href.indexOf('LOCAL_MOCK=1') !== -1; // 2、发送update消息
                        Object.values(_this6.elementProcessors).forEach(function (processor) {
                          processor.update({
                            data: {
                              originActionQueryResult: LOCAL_MOCK ? sdkActionUpdate : data.originActionQueryResult,
                              originOneAccountQueryResult: LOCAL_MOCK ? oneAccountUpdate : data.originOneAccountQueryResult
                            },
                            paymentSessionData: paymentSessionData
                          });
                        });
                        // 3、返回更新结果
                        _this6.serviceMap.EventCenter.listen(EVENT.updated.name, function (data) {
                          // 若更新不成功，还原core.paymentContext信息
                          if (!data.success) {
                            _this6.elementContainer.updatePaymentSessionData(prePaymentSessionData);
                          }
                          return resolve(data.success || false);
                        });
                      case 10:
                      case "end":
                        return _context6.stop();
                    }
                  }, _callee6);
                }));
                return function (_x8) {
                  return _ref5.apply(this, arguments);
                };
              }()));
            case 1:
            case "end":
              return _context7.stop();
          }
        }, _callee7);
      }));
      function updatePayment(_x7) {
        return _updatePayment.apply(this, arguments);
      }
      return updatePayment;
    }()
  }, {
    key: "destroyHandle",
    value: function destroyHandle() {
      // Fix: when a failed mount is destroyed and a new mount succeeds within the 16s timeout window,
      // clear stale timeout and heartbeat events from the destroyed instance.
      this.clearEvents('destroy');
      this.clearInitTimeout();
      this.elementContainer.destroy();
      cleanMockup();
      removeRetentionPopup();
      try {
        destroyModal();
      } catch (error) {}
      this.serviceMap.EventCenter.cleanIFrames();
      this.elementContainerService.destroy();
    }
  }, {
    key: "destroy",
    value: function destroy() {
      var startEventId = this.elementEventCenter.registerEvent(EXPOSURE_API_EVENT.DESTORY);
      try {
        this.destroyHandle();
        this.setControllerStatusOrView(IElementStatus.DESTROYED);
      } finally {
        this.elementEventCenter.endEvent(startEventId);
      }
    }
  }, {
    key: "setControllerStatusOrView",
    value: function setControllerStatusOrView(status) {
      var _this$onStatusChangeC;
      var _status = this.elementContainer.getStatus();
      if (status === _status) return;
      (_this$onStatusChangeC = this.onStatusChangeCallback) === null || _this$onStatusChangeC === void 0 || _this$onStatusChangeC.call(this, "\u72B6\u6001\u7531 ".concat(_status, " \u53D8\u66F4\u4E3A ").concat(status));
      this.elementContainer.setStatus(status);
    }
  }, {
    key: "on",
    value: function on(event, callback) {
      if (!this.isEventAllowed(event)) {
        return console.error("Event \"".concat(event, "\" is not allowed."));
      }
      this.serviceMap.EventCenter.listen(event, function (data) {
        callback === null || callback === void 0 || callback(data);
      });
    }
  }, {
    key: "isEventAllowed",
    value: function isEventAllowed(event) {
      var _safeParse;
      // 获取当前业务场景
      var _convertPaymentSessio2 = convertPaymentSession(this.options.sessionData),
        paymentSessionObj = _convertPaymentSessio2.data;
      var isExpressCheckout = ((_safeParse = safeParse(paymentSessionObj === null || paymentSessionObj === void 0 ? void 0 : paymentSessionObj.extendInfo)) === null || _safeParse === void 0 ? void 0 : _safeParse.expressCheckout) === 'true';
      var productScene = isExpressCheckout ? ProductScene.EXPRESS_CHECKOUT : ProductScene.ELEMENT_PAYMENT;
      // 查找对应的产品场景
      var scenario = productEventScenarios.find(function (s) {
        return s.eventName === productScene;
      });
      // 检查场景存在且事件名称在支持的事件列表中
      return scenario !== undefined && scenario.supportedEvents.includes(event);
    }
  }]);
  return ElementController;
}();
export default ElementController;