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/venueBooking/components/Cart/index.tsx
var Cart_exports = {};
__export(Cart_exports, {
  default: () => Cart
});
module.exports = __toCommonJS(Cart_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_shoppingCart = __toESM(require("../../../shoppingCart"));
var import_subTotal = __toESM(require("../../../subTotal"));
var import_Voucher = __toESM(require("../Voucher"));
var import_Deposit = __toESM(require("../Deposit"));
var import_context = require("../../context");
var import_buildCartHolderParams = require("../../../../utils/buildCartHolderParams");
var import_utils2 = require("../../../appointmentBooking/utils");
var import_index = require("./index.less");
function Cart(props) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const {
    open,
    onCancel,
    onNext,
    items,
    summary,
    embedded = false,
    confirmLoading = false,
    extraContent
  } = props;
  const {
    currentStep,
    runModuleAction,
    refreshViewModel,
    venueBookingModule,
    isAgreeDepositPolicy,
    setIsAgreeDepositPolicy,
    isLogin
  } = (0, import_context.useVenueBookingContext)();
  const engineContext = (0, import_useEngineContext.default)();
  const businessUtils = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.businessUtils;
  const symbol = String(((_e = (_d = (_c = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.getSymbolic) == null ? void 0 : _e.call(_d)) || "$");
  const locale = ((_g = (_f = engineContext == null ? void 0 : engineContext.engine) == null ? void 0 : _f.props) == null ? void 0 : _g.locale) || "en";
  const [holderMap, setHolderMap] = (0, import_react.useState)({});
  const { pisellos, translation } = ((_h = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _h.utils) || {};
  const hasGoodPassApp = !!((_i = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _i.call(businessUtils, "goodpass"));
  const hasDiscountCardApp = !!((_j = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _j.call(businessUtils, "discountcard"));
  const showVoucher = hasGoodPassApp || hasDiscountCardApp;
  (0, import_react.useEffect)(() => {
    var _a2;
    const onHolderChanged = (res) => {
      if ((res == null ? void 0 : res.path) === "holderMap") {
        setHolderMap(res == null ? void 0 : res.value);
      }
    };
    (_a2 = pisellos == null ? void 0 : pisellos.effects) == null ? void 0 : _a2.on("venueBooking_holder:changed", onHolderChanged);
    return () => {
      var _a3;
      (_a3 = pisellos == null ? void 0 : pisellos.effects) == null ? void 0 : _a3.off("venueBooking_holder:changed", onHolderChanged);
    };
  }, []);
  (0, import_react.useEffect)(() => {
    const _holderMap = (venueBookingModule == null ? void 0 : venueBookingModule.getHolderFormMap()) || {};
    setHolderMap(_holderMap);
  }, [venueBookingModule]);
  const isVisible = embedded || open;
  if (!isVisible) return null;
  const totalAmount = (summary == null ? void 0 : summary.total_amount) ?? (summary == null ? void 0 : summary.expect_amount) ?? (summary == null ? void 0 : summary.amount) ?? (summary == null ? void 0 : summary.total) ?? "0.00";
  const cartProducts = (0, import_react.useMemo)(() => {
    return (items || []).map((item) => {
      var _a2, _b2, _c2;
      const holderConfig = (0, import_buildCartHolderParams.getVenueCartHolderConfig)(item);
      const formData = (0, import_buildCartHolderParams.isHolderConfigEnabled)(holderConfig) ? holderMap == null ? void 0 : holderMap[holderConfig == null ? void 0 : holderConfig.resource_id] : {};
      const holderParams = (0, import_buildCartHolderParams.buildCartHolderParams)({
        item,
        holderConfig,
        formData,
        translation,
        enabled: !!((_b2 = (_a2 = item == null ? void 0 : item._origin) == null ? void 0 : _a2.product) == null ? void 0 : _b2.bookingUuid),
        utils: (_c2 = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _c2.utils
      });
      return {
        ...item,
        symbol: (item == null ? void 0 : item.symbol) || symbol,
        is_hide_like: true,
        allowClearHolder: true,
        ...holderParams
      };
    });
  }, [items, symbol, holderMap, translation]);
  const confirmOrderText = currentStep === "checkout" ? String(import_utils.locales.getText("pisell2.venue.action.pay.now") || "立即支付") : String(import_utils.locales.getText("pisell2.venue.action.next") || "下一步");
  const subTotalList = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    const subTotal = Number((summary == null ? void 0 : summary.product_amount) ?? 0);
    const totalTaxFee = Number((summary == null ? void 0 : summary.tax_fee) ?? 0);
    const total = Number((summary == null ? void 0 : summary.total_amount) ?? (summary == null ? void 0 : summary.expect_amount) ?? 0);
    const hasDeposit = !!((_a2 = summary == null ? void 0 : summary.deposit) == null ? void 0 : _a2.hasDeposit);
    const tempOrder = (_b2 = venueBookingModule == null ? void 0 : venueBookingModule.getTempOrder) == null ? void 0 : _b2.call(venueBookingModule);
    const tempSummary = (tempOrder == null ? void 0 : tempOrder.summary) || {};
    const taxTitle = String((tempSummary == null ? void 0 : tempSummary.tax_title) || (summary == null ? void 0 : summary.tax_title) || "GST/Tax");
    const rawTaxRate = Number(tempSummary == null ? void 0 : tempSummary.tax_rate);
    const normalizedTaxRate = Number.isNaN(rawTaxRate) ? 0 : rawTaxRate > 1 ? rawTaxRate / 100 : rawTaxRate;
    const isPriceIncludeTax = Boolean(
      (tempSummary == null ? void 0 : tempSummary.is_price_include_tax) ?? (tempSummary == null ? void 0 : tempSummary.isPriceIncludeTax)
    );
    const surchargeItems = ((summary == null ? void 0 : summary.surcharges) || []).filter((s) => Number(s == null ? void 0 : s.amount) > 0).map((s) => {
      const labelObj = (s == null ? void 0 : s.label) || (s == null ? void 0 : s.name) || {};
      const label = labelObj[locale] || labelObj.en || labelObj.original || (s == null ? void 0 : s.key) || "";
      return {
        key: (s == null ? void 0 : s.key) || `surcharge_${s == null ? void 0 : s.surcharge_id}`,
        label,
        value: Number(s == null ? void 0 : s.amount)
      };
    });
    return [
      // 定金行：SubTotal 组件会将 key=deposit 的项作为顶部 header 项展示（加粗突出）
      {
        key: "deposit",
        value: Number(((_c2 = summary == null ? void 0 : summary.deposit) == null ? void 0 : _c2.total) ?? 0),
        label: import_utils.locales.getText("pisell2.appointment.deposit") || "Deposit",
        hidden: !hasDeposit
      },
      {
        key: "sub_total",
        value: Number.isNaN(subTotal) ? 0 : subTotal
      },
      ...surchargeItems,
      {
        key: "tax",
        value: Number.isNaN(totalTaxFee) ? 0 : totalTaxFee,
        hidden: Number.isNaN(totalTaxFee) ? true : totalTaxFee <= 0,
        tax: {
          title: taxTitle,
          rate: normalizedTaxRate,
          is_price_include_tax: isPriceIncludeTax
        }
      },
      {
        key: "custom_total",
        value: Number.isNaN(total) ? 0 : total,
        label: import_utils.locales.getText("pisell2.event.total") || "合计",
        // 无定金时合计行加粗；有定金时定金行已作为 header 突出显示
        bold: !hasDeposit
      }
    ];
  }, [summary, locale, venueBookingModule]);
  const isVenueBookingCartItem = (target) => {
    if (!target || typeof target !== "object") return false;
    if ((target == null ? void 0 : target.start_date) && (target == null ? void 0 : target.end_date)) return true;
    const identity = String((target == null ? void 0 : target.identity_key) || "");
    if (identity.startsWith("venue:")) return true;
    return false;
  };
  const handleCartChange = async (item, type, sourceItem) => {
    var _a2, _b2, _c2, _d2;
    if (type === "add_holder") {
      const holderConfig = (0, import_buildCartHolderParams.getVenueCartHolderConfig)(item);
      if (!(0, import_buildCartHolderParams.isHolderConfigEnabled)(holderConfig)) return;
      const formId = holderConfig == null ? void 0 : holderConfig.resource_id;
      if (!formId) return;
      const skuRelationFormId = (0, import_buildCartHolderParams.getSkuRelationFormId)(holderMap, formId);
      return (0, import_utils2.openForm)({
        form_id: skuRelationFormId || formId,
        title: import_utils.locales.getText("pisell2.venue.create.form"),
        utils: (_a2 = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a2.utils,
        callback: async (res) => {
          var _a3, _b3, _c3, _d3;
          if ((res == null ? void 0 : res.status) === "success") {
            const { formRecordId, formId: holderFormId } = (0, import_buildCartHolderParams.handleCartHolderFormSuccess)({
              res,
              formId,
              skuRelationFormId,
              utils: (_a3 = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a3.utils,
              module: venueBookingModule
            });
            const customer = (0, import_utils2.getCustomer)((_b3 = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _b3.utils);
            venueBookingModule.setBookingHolder((_d3 = (_c3 = item == null ? void 0 : item._origin) == null ? void 0 : _c3.product) == null ? void 0 : _d3.bookingUuid, {
              customer_id: customer == null ? void 0 : customer.id,
              form_id: holderFormId,
              form_record: [formRecordId]
            });
            await refreshViewModel();
          }
        }
      });
    }
    if (type === "change_holder") {
      const customer = (0, import_utils2.getCustomer)((_b2 = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _b2.utils);
      const holder = (sourceItem == null ? void 0 : sourceItem._origin) || sourceItem;
      const params = !sourceItem ? null : {
        customer_id: customer == null ? void 0 : customer.id,
        form_id: holder == null ? void 0 : holder.form_id,
        form_record: [holder == null ? void 0 : holder.form_record_id]
      };
      venueBookingModule.setBookingHolder((_d2 = (_c2 = item == null ? void 0 : item._origin) == null ? void 0 : _c2.product) == null ? void 0 : _d2.bookingUuid, params);
      await refreshViewModel();
      return;
    }
    if (type !== "delete") return;
    const targetItem = sourceItem && typeof sourceItem === "object" ? sourceItem : item;
    if (currentStep !== "select-venue" && isVenueBookingCartItem(targetItem)) {
      import_antd.message.warning({
        content: String(
          import_utils.locales.getText("pisell2.venue.cart.delete.venue.only.step1") || "请返回第一步后再删除场地商品"
        ),
        duration: 2
      });
      return;
    }
    const productId = (targetItem == null ? void 0 : targetItem.product_id) ?? (targetItem == null ? void 0 : targetItem.id) ?? null;
    const productVariantId = Number((targetItem == null ? void 0 : targetItem.product_variant_id) ?? 0);
    const identityKey = targetItem == null ? void 0 : targetItem.identity_key;
    if (productId === null && Number.isNaN(productVariantId)) return;
    if (typeof identityKey !== "string" || identityKey.length === 0) {
      console.error("[venueBooking] removeProductFromOrder skipped: missing identity_key", {
        item: targetItem
      });
      return;
    }
    try {
      await runModuleAction("removeProductFromOrder", {
        product_id: productId,
        product_variant_id: Number.isNaN(productVariantId) ? 0 : productVariantId,
        identity_key: identityKey
      });
      await refreshViewModel();
    } catch (error) {
      console.error("[venueBooking] removeProductFromOrder failed", { error, item: targetItem });
    }
  };
  (0, import_react.useEffect)(() => {
    if (!isVisible) return;
    refreshViewModel();
  }, [isVisible]);
  const cartListContent = /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-body" }, /* @__PURE__ */ import_react.default.createElement(
    import_shoppingCart.default,
    {
      productParams: {
        products: cartProducts,
        hideAddBtn: true,
        disabledEdit: false,
        isShowNote: false,
        isShowDelete: true,
        isShowPackageNote: false,
        isShowChangeHolder: currentStep === "checkout" ? false : !!isLogin,
        isShowHolder: true,
        isShowAddHolderButton: true
      },
      platform: "h5",
      emptyText: import_utils.locales.getText("pisell2.venue.cart.empty"),
      isOpenGroup: false,
      isHideClearCart: true,
      onChange: handleCartChange
    }
  ));
  const cartSummaryContent = /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, showVoucher ? /* @__PURE__ */ import_react.default.createElement(import_Voucher.default, null) : null, /* @__PURE__ */ import_react.default.createElement(import_subTotal.default, { list: subTotalList, style: { padding: 0 } }, ((_k = summary == null ? void 0 : summary.deposit) == null ? void 0 : _k.hasDeposit) ? /* @__PURE__ */ import_react.default.createElement(
    import_Deposit.default,
    {
      deposit: summary.deposit,
      isAgreePolicy: isAgreeDepositPolicy,
      onChange: setIsAgreeDepositPolicy,
      getProtocol: (id) => {
        var _a2;
        return (_a2 = venueBookingModule == null ? void 0 : venueBookingModule.getProtocol) == null ? void 0 : _a2.call(venueBookingModule, id);
      }
    }
  ) : null), extraContent ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-extra-content" }, extraContent) : null);
  if (embedded) {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, cartListContent, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-embedded-footer" }, cartSummaryContent, /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "primary", block: true, onClick: onNext, loading: confirmLoading }, confirmOrderText)));
  }
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-mask", onClick: onCancel }), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-drawer" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-header", onClick: onCancel }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-venue-booking-cart-handle", "aria-hidden": true })), cartListContent, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-drawer-summary" }, cartSummaryContent), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-footer" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-total" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-total-label" }, import_utils.locales.getText("pisell2.event.total") || "合计"), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-venue-booking-cart-total-amount" }, symbol, Number(totalAmount || 0).toFixed(2))), /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "primary", onClick: onNext, loading: confirmLoading }, currentStep === "checkout" ? confirmOrderText : import_utils.locales.getText("pisell2.event.continue") || "继续"))));
}
