var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/checkout/plugin.tsx
var plugin_exports = {};
__export(plugin_exports, {
  default: () => plugin_default
});
module.exports = __toCommonJS(plugin_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_PaymentModal = __toESM(require("./PaymentModal"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_useLogger = __toESM(require("../../hooks/useLogger"));
var import_model = require("../booking/info/model");
var import_utils = require("../../utils");
var import_payment_modal_utils = require("./payment-modal-utils");
function getPluginOrderId(engineProps) {
  var _a;
  return ((_a = engineProps.order) == null ? void 0 : _a.id) ?? engineProps.order_id ?? engineProps.orderId;
}
function hasPluginOrderId(orderId) {
  return orderId !== void 0 && orderId !== null && String(orderId).trim() !== "";
}
function getPluginBaseSalesModuleName(engineProps, orderId) {
  return engineProps.baseSalesModuleName || (hasPluginOrderId(orderId) ? "baseSales" : "");
}
function getErrorMessage(error) {
  return error instanceof Error ? error.message : String(error || "Unknown error");
}
function getBaseSalesLoadedOrderId(module2) {
  var _a;
  const snapshot = (_a = module2 == null ? void 0 : module2.getOrderSnapshot) == null ? void 0 : _a.call(module2);
  const identity = (snapshot == null ? void 0 : snapshot.identity) || {};
  const tempOrder = (snapshot == null ? void 0 : snapshot.tempOrder) || {};
  return identity.orderId ?? tempOrder.order_id;
}
function getDefinedPluginProps(props) {
  return Object.entries(props).reduce(
    (result, [key, value]) => {
      if (value !== void 0) {
        result[key] = value;
      }
      return result;
    },
    {}
  );
}
var EMPTY_PLUGIN_PROPS = {};
function PaymentModalContent(props) {
  var _a, _b, _c, _d;
  const context = (0, import_useEngineContext.default)();
  const Toast = (0, import_materials.useToast)();
  const logger = (0, import_useLogger.default)();
  const lowcodeProps = ((_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) || EMPTY_PLUGIN_PROPS;
  const engineProps = (0, import_react.useMemo)(
    () => ({
      ...lowcodeProps,
      ...getDefinedPluginProps(props)
    }),
    [
      lowcodeProps,
      props.baseSalesModuleName,
      props.callback,
      props.config,
      props.onCustomerChange,
      props.order,
      props.orderId,
      props.order_id,
      props.paymentResultDisplayMode
    ]
  );
  const orderId = getPluginOrderId(engineProps);
  const baseSalesModuleName = getPluginBaseSalesModuleName(engineProps, orderId);
  const { pisellos, pisellosAllModule, businessUtils } = ((_b = context == null ? void 0 : context.appHelper) == null ? void 0 : _b.utils) || {};
  const { BaseSalesImpl } = pisellosAllModule || {};
  if ((_d = (_c = context == null ? void 0 : context.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.request) {
    import_utils.request.setRequest(context.appHelper.utils.request);
  }
  const initialBaseSalesModule = (0, import_react.useMemo)(() => {
    var _a2;
    if (!baseSalesModuleName) return null;
    return ((_a2 = pisellos == null ? void 0 : pisellos.getModule) == null ? void 0 : _a2.call(pisellos, baseSalesModuleName)) || null;
  }, [baseSalesModuleName, pisellos]);
  const [baseSalesModule, setBaseSalesModule] = (0, import_react.useState)(
    initialBaseSalesModule
  );
  const [isLoadingFallbackModule, setIsLoadingFallbackModule] = (0, import_react.useState)(false);
  const [loadedOrderId, setLoadedOrderId] = (0, import_react.useState)("");
  (0, import_react.useEffect)(() => {
    setBaseSalesModule(initialBaseSalesModule);
  }, [initialBaseSalesModule]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2, _e, _f, _g;
    if (!baseSalesModuleName) {
      (_a2 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _a2.call(logger, {
        metadata: { engineProps },
        title: "打开支付弹窗失败-缺少 baseSalesModuleName 和 orderId"
      });
      (_b2 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _b2.call(Toast, "Missing baseSalesModuleName or orderId");
      (_c2 = engineProps.callback) == null ? void 0 : _c2.call(engineProps, (0, import_payment_modal_utils.createPaymentModalCallbackEvent)({
        type: "error",
        error: "missing_base_sales_module_name",
        payload: { baseSalesModuleName, orderId }
      }));
      return;
    }
    const existingModule = ((_d2 = pisellos == null ? void 0 : pisellos.getModule) == null ? void 0 : _d2.call(pisellos, baseSalesModuleName)) || baseSalesModule;
    if (existingModule) {
      let isCancelled2 = false;
      let hasOpenedPaymentModal2 = false;
      const currentOrderId = getBaseSalesLoadedOrderId(existingModule);
      const shouldReloadOrder = hasPluginOrderId(orderId) && String(currentOrderId || "") !== String(orderId);
      const openWithExistingModule = async () => {
        var _a3;
        if (shouldReloadOrder) {
          setIsLoadingFallbackModule(true);
          await existingModule.loadSalesDetail(orderId);
        }
        if (isCancelled2) return;
        setBaseSalesModule(existingModule);
        setLoadedOrderId(
          String(getBaseSalesLoadedOrderId(existingModule) ?? orderId ?? "")
        );
        window.isPaymentModalPluginOpen = true;
        hasOpenedPaymentModal2 = true;
        (_a3 = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _a3.call(Toast);
        setIsLoadingFallbackModule(false);
      };
      openWithExistingModule().catch((error) => {
        var _a3, _b3, _c3;
        if (isCancelled2) return;
        const message = getErrorMessage(error);
        (_a3 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _a3.call(logger, {
          metadata: { baseSalesModuleName, orderId, error },
          title: "打开支付弹窗失败-切换 BaseSales 订单失败"
        });
        (_b3 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _b3.call(Toast, message);
        (_c3 = engineProps.callback) == null ? void 0 : _c3.call(engineProps, (0, import_payment_modal_utils.createPaymentModalCallbackEvent)({
          type: "error",
          error: "switch_base_sales_order_failed",
          payload: { baseSalesModuleName, orderId, message }
        }));
        setIsLoadingFallbackModule(false);
      });
      return () => {
        isCancelled2 = true;
        if (hasOpenedPaymentModal2) {
          window.isPaymentModalPluginOpen = false;
        }
      };
    }
    if (!hasPluginOrderId(orderId) || !BaseSalesImpl || !(pisellos == null ? void 0 : pisellos.registerModule)) {
      (_e = logger == null ? void 0 : logger.addLog) == null ? void 0 : _e.call(logger, {
        metadata: {
          baseSalesModuleName,
          orderId,
          hasBaseSalesImpl: !!BaseSalesImpl
        },
        title: "打开支付弹窗失败-BaseSales 模块不存在"
      });
      (_f = Toast == null ? void 0 : Toast.error) == null ? void 0 : _f.call(Toast, "BaseSales module not found");
      (_g = engineProps.callback) == null ? void 0 : _g.call(engineProps, (0, import_payment_modal_utils.createPaymentModalCallbackEvent)({
        type: "error",
        error: "base_sales_module_not_found",
        payload: { baseSalesModuleName }
      }));
      return;
    }
    let isCancelled = false;
    let hasOpenedPaymentModal = false;
    const bootstrapFallbackModule = async () => {
      var _a3, _b3, _c3, _d3, _e2;
      setIsLoadingFallbackModule(true);
      try {
        const fallbackModule = new BaseSalesImpl(baseSalesModuleName);
        await pisellos.registerModule(fallbackModule, {
          initialState: {},
          otherParams: {
            cacheId: baseSalesModuleName,
            platform: "shop",
            isFranchisee: (_a3 = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _a3.call(businessUtils, "franchisee")
          }
        });
        await fallbackModule.loadSalesDetail(orderId);
        if (isCancelled) return;
        setBaseSalesModule(fallbackModule);
        setLoadedOrderId(
          String(getBaseSalesLoadedOrderId(fallbackModule) ?? orderId ?? "")
        );
        window.isPaymentModalPluginOpen = true;
        hasOpenedPaymentModal = true;
        (_b3 = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _b3.call(Toast);
      } catch (error) {
        if (isCancelled) return;
        const message = getErrorMessage(error);
        (_c3 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _c3.call(logger, {
          metadata: { baseSalesModuleName, orderId, error },
          title: "打开支付弹窗失败-兜底加载 BaseSales 订单失败"
        });
        (_d3 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _d3.call(Toast, message);
        (_e2 = engineProps.callback) == null ? void 0 : _e2.call(engineProps, (0, import_payment_modal_utils.createPaymentModalCallbackEvent)({
          type: "error",
          error: "fallback_base_sales_load_failed",
          payload: { baseSalesModuleName, orderId, message }
        }));
      } finally {
        if (!isCancelled) {
          setIsLoadingFallbackModule(false);
        }
      }
    };
    bootstrapFallbackModule();
    return () => {
      isCancelled = true;
      if (hasOpenedPaymentModal) {
        window.isPaymentModalPluginOpen = false;
      }
    };
  }, [
    BaseSalesImpl,
    Toast,
    baseSalesModule,
    baseSalesModuleName,
    businessUtils,
    engineProps,
    logger,
    orderId,
    pisellos
  ]);
  if (!baseSalesModuleName || !baseSalesModule || isLoadingFallbackModule) {
    return null;
  }
  return /* @__PURE__ */ import_react.default.createElement(
    import_PaymentModal.default,
    {
      key: `${baseSalesModuleName}-${loadedOrderId}`,
      open: true,
      baseSalesModuleName,
      paymentResultDisplayMode: engineProps.paymentResultDisplayMode || "toast",
      config: engineProps.config,
      onCustomerChange: engineProps.onCustomerChange,
      onClose: (reset, options) => {
        var _a2;
        window.isPaymentModalPluginOpen = false;
        const event = (0, import_payment_modal_utils.normalizePaymentModalCallbackEvent)(
          (options == null ? void 0 : options.event) || (0, import_payment_modal_utils.createPaymentModalCallbackEvent)({
            type: "modal-close",
            reason: reset ? "paid" : "cancel",
            status: reset ? "paid" : "cancelled",
            orderId: (options == null ? void 0 : options.order_id) || orderId,
            reset: reset || false,
            payload: options,
            shouldRefreshOrder: reset === true,
            shouldCloseCaller: reset === true
          })
        );
        (_a2 = engineProps.callback) == null ? void 0 : _a2.call(engineProps, event);
      },
      callback: (result) => {
        var _a2;
        const event = (0, import_payment_modal_utils.normalizePaymentModalCallbackEvent)(result);
        if (event.type === "modal-close") {
          window.isPaymentModalPluginOpen = false;
          return;
        }
        (_a2 = engineProps.callback) == null ? void 0 : _a2.call(engineProps, event);
        if (event.shouldCloseCaller) {
          window.isPaymentModalPluginOpen = false;
        }
      }
    }
  );
}
var PaymentModalPlugin = (0, import_model.Provider)(PaymentModalContent);
var plugin_default = PaymentModalPlugin;
