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/plus/saleDetail/components/CartItems/Editable/index.tsx
var Editable_exports = {};
__export(Editable_exports, {
  CartItems: () => CartItems
});
module.exports = __toCommonJS(Editable_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_materials2 = require("@pisell/materials");
var import_pisellNumberSelector = __toESM(require("../../../../../pro/pisellNumberSelector"));
var import_index = require("./index.less");
var { LineItem } = import_materials2.ProductCard;
var voidFn = () => {
};
var STATUS_OPTIONS = [
  {
    key: "new",
    labelKey: "pisell2.sale-detail.status.new",
    color: "#91caff"
  },
  {
    key: "confirmed",
    labelKey: "pisell2.sale-detail.status.confirmed",
    color: "#b7eb8f"
  },
  {
    key: "arrived",
    labelKey: "pisell2.sale-detail.status.arrived",
    color: "#d3adf7"
  },
  {
    key: "started",
    labelKey: "pisell2.sale-detail.status.started",
    color: "#fffb8f"
  },
  {
    key: "cancelled",
    labelKey: "pisell2.sale-detail.status.cancelled",
    color: "#bfbfbf",
    danger: true
  },
  {
    key: "no_show",
    labelKey: "pisell2.sale-detail.status.no_show",
    color: "#ffa39e",
    danger: true
  },
  {
    key: "completed",
    labelKey: "pisell2.sale-detail.status.completed",
    color: "#ffd591"
  }
];
var getBookingQuantity = (item) => {
  var _a, _b;
  return ((_b = (_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.product) == null ? void 0 : _b.num) ?? (item == null ? void 0 : item.num) ?? (item == null ? void 0 : item.number) ?? 1;
};
var getCartLineKey = (item) => {
  var _a;
  return String((_a = item == null ? void 0 : item.metadata) == null ? void 0 : _a.unique_identification_number);
};
var getLineProduct = (item) => {
  var _a;
  return ((_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.product) ?? item;
};
var hasOrderDetailId = (item) => {
  var _a;
  const orderDetailId = (_a = getLineProduct(item)) == null ? void 0 : _a.order_detail_id;
  return orderDetailId !== void 0 && orderDetailId !== null && orderDetailId !== "";
};
var getLineAmount = (item) => {
  const product = getLineProduct(item);
  const quantity = Number(getBookingQuantity(item)) || 1;
  const unitAmount = (product == null ? void 0 : product.selling_price) ?? (product == null ? void 0 : product.original_price) ?? 0;
  const amount = Number(unitAmount);
  return Number.isFinite(amount) ? amount * quantity : 0;
};
function CartItems({
  context,
  sales,
  className,
  layout,
  showEmpty,
  emptyText,
  interactionPolicy
}) {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const [statusLoading, setStatusLoading] = (0, import_react.useState)(false);
  const [quantityLoadingKeys, setQuantityLoadingKeys] = (0, import_react.useState)({});
  const [isSavedExpanded, setIsSavedExpanded] = (0, import_react.useState)(false);
  const editingRef = (0, import_react.useRef)(false);
  const cart = context.cart;
  const resolvedSales = (context == null ? void 0 : context.sales) || sales;
  const currentOrderId = ((_a = resolvedSales == null ? void 0 : resolvedSales.tempOrder) == null ? void 0 : _a.order_id) ?? null;
  const bookings = cart.bookings || [];
  const items = cart.items || [];
  const displayBookings = (0, import_react.useMemo)(() => [...bookings].reverse(), [bookings]);
  const displayItems = (0, import_react.useMemo)(() => [...items].reverse(), [items]);
  const displayNormalBookings = (0, import_react.useMemo)(
    () => displayBookings.filter((item) => !hasOrderDetailId(item)),
    [displayBookings]
  );
  const displaySavedBookings = (0, import_react.useMemo)(
    () => displayBookings.filter(hasOrderDetailId),
    [displayBookings]
  );
  const displayNormalItems = (0, import_react.useMemo)(
    () => displayItems.filter((item) => !hasOrderDetailId(item)),
    [displayItems]
  );
  const displaySavedItems = (0, import_react.useMemo)(
    () => displayItems.filter(hasOrderDetailId),
    [displayItems]
  );
  const safeCols = Math.max(1, Math.floor((layout == null ? void 0 : layout.columns) || 1));
  const isMultiCol = safeCols > 1;
  const containerStyle = isMultiCol ? {
    "--pisell-cart-cols": safeCols
  } : void 0;
  const isEmpty = !bookings.length && !items.length;
  const defaultIsFormSubject = ((_g = (_f = (_e = (_d = (_c = (_b = context.booking) == null ? void 0 : _b.getBookingConfig) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.config) == null ? void 0 : _e.basic) == null ? void 0 : _f.appointment_subject) == null ? void 0 : _g.type) === "form";
  const savedItemsCount = displaySavedBookings.length + displaySavedItems.length;
  const amountSymbol = ((_h = resolvedSales == null ? void 0 : resolvedSales.tempOrder) == null ? void 0 : _h.currency_symbol) || "$";
  const savedItemsTotal = (0, import_react.useMemo)(() => {
    const total = [...displaySavedBookings, ...displaySavedItems].reduce(
      (sum, item) => sum + getLineAmount(item),
      0
    );
    return (0, import_utils.formatAmount)(total, 2, amountSymbol);
  }, [amountSymbol, displaySavedBookings, displaySavedItems]);
  (0, import_react.useEffect)(() => {
    setIsSavedExpanded(false);
  }, [currentOrderId]);
  const statusOptions = (0, import_react.useMemo)(
    () => STATUS_OPTIONS.map((option) => ({
      key: option.key,
      label: import_utils.locales.getText(option.labelKey),
      color: option.color,
      danger: option.danger
    })),
    []
  );
  const handleBookingStatusChange = (0, import_react.useCallback)(
    async (status) => {
      const next = status.trim();
      if (!next) {
        import_antd.message.error(
          import_utils.locales.getText("pisell2.sale-detail.status-empty-error")
        );
        return;
      }
      if (!(resolvedSales == null ? void 0 : resolvedSales.setBookingStatus)) return;
      setStatusLoading(true);
      try {
        await resolvedSales.setBookingStatus(next);
      } catch (e) {
        import_antd.message.error(String((e == null ? void 0 : e.message) ?? e));
      } finally {
        setStatusLoading(false);
      }
    },
    [resolvedSales]
  );
  const handleRemoveItem = (0, import_react.useCallback)(
    async (item) => {
      var _a2;
      const productItem = ((_a2 = item == null ? void 0 : item._extend) == null ? void 0 : _a2.product) ?? item;
      if (!productItem || !cart.removeItem) return;
      try {
        await cart.removeItem(productItem);
      } catch (e) {
        import_antd.message.error(String((e == null ? void 0 : e.message) ?? e));
      }
    },
    [cart.removeItem]
  );
  const handleEditCartLine = (0, import_react.useCallback)(
    async (item) => {
      if (!cart.editCartLine || editingRef.current) return;
      editingRef.current = true;
      try {
        await cart.editCartLine(item);
      } catch (e) {
        import_antd.message.error(String((e == null ? void 0 : e.message) ?? e));
      } finally {
        editingRef.current = false;
      }
    },
    [cart.editCartLine]
  );
  const handleGiftClick = (0, import_react.useCallback)(
    async (item) => {
      if (!cart.selectGiftForItem) return;
      try {
        await cart.selectGiftForItem(item);
      } catch (e) {
        import_antd.message.error(String((e == null ? void 0 : e.message) ?? e));
      }
    },
    [cart.selectGiftForItem]
  );
  const handleQuantityChange = (0, import_react.useCallback)(
    async (item, value) => {
      const quantity = Math.floor(Number(value));
      if (!Number.isFinite(quantity) || quantity < 1) return;
      if (quantity === getBookingQuantity(item)) return;
      if (!cart.updateItemQuantity) {
        import_antd.message.error("[SalesSdk] Cart: updateItemQuantity 未配置");
        return;
      }
      const key = getCartLineKey(item);
      if (!key || quantityLoadingKeys[key]) return;
      setQuantityLoadingKeys((prev) => ({ ...prev, [key]: true }));
      try {
        await cart.updateItemQuantity(item, quantity);
      } catch (e) {
        import_antd.message.error(String((e == null ? void 0 : e.message) ?? e));
      } finally {
        setQuantityLoadingKeys((prev) => {
          const next = { ...prev };
          delete next[key];
          return next;
        });
      }
    },
    [cart.updateItemQuantity, quantityLoadingKeys]
  );
  const getCardHandler = (0, import_react.useCallback)(
    (item) => {
      const cardAction = interactionPolicy == null ? void 0 : interactionPolicy.cardAction;
      if (cardAction === "none") return void 0;
      if (typeof cardAction === "function") {
        return () => cardAction(item);
      }
      if (cardAction !== "edit") return void 0;
      return () => handleEditCartLine(item);
    },
    [handleEditCartLine, interactionPolicy == null ? void 0 : interactionPolicy.cardAction]
  );
  const renderQuantityAction = (0, import_react.useCallback)(
    (item) => [
      {
        key: "update_number",
        text: /* @__PURE__ */ import_react.default.createElement(
          import_pisellNumberSelector.default,
          {
            enablePriceAdjust: true,
            min: 1,
            className: "pisell-sale-detail-cart-items__quantity-selector",
            value: getBookingQuantity(item),
            disabled: Boolean(quantityLoadingKeys[getCartLineKey(item)]),
            onChange: (value) => handleQuantityChange(item, value)
          }
        ),
        color: "#667085"
      }
    ],
    [handleQuantityChange, quantityLoadingKeys]
  );
  const renderBookingItem = (0, import_react.useCallback)(
    (item) => {
      var _a2;
      return /* @__PURE__ */ import_react.default.createElement(
        LineItem,
        {
          key: ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.booking_id,
          itemType: "booking",
          type: "a9",
          isShowBookingHeader: Boolean(item == null ? void 0 : item.booking_id),
          rightActions: (interactionPolicy == null ? void 0 : interactionPolicy.isShowRightActions) ? renderQuantityAction(item) : [],
          escapeDom: ".pisell-number-selector-popover",
          dataSource: item,
          statusOptions,
          statusLoading,
          onBookingStatusChange: void 0,
          onAction: voidFn,
          onDelete: () => handleRemoveItem(item),
          onNote: voidFn,
          onCard: getCardHandler(item),
          onAddTimeProductCard: handleEditCartLine,
          onPromotion: voidFn,
          isShowNote: true,
          disabledEdit: interactionPolicy == null ? void 0 : interactionPolicy.disabledEdit,
          isShowDelete: interactionPolicy == null ? void 0 : interactionPolicy.isShowDelete,
          isShowAmountFooter: true,
          isShowImage: true,
          maxSpecsCount: 1,
          scenario: "booking2",
          onGift: handleGiftClick,
          isFormSubject: item.isFormSubject ?? defaultIsFormSubject,
          holderOptions: item.holderOptions
        }
      );
    },
    [
      defaultIsFormSubject,
      getCardHandler,
      handleGiftClick,
      handleEditCartLine,
      handleRemoveItem,
      interactionPolicy == null ? void 0 : interactionPolicy.disabledEdit,
      interactionPolicy == null ? void 0 : interactionPolicy.isShowDelete,
      interactionPolicy == null ? void 0 : interactionPolicy.isShowRightActions,
      renderQuantityAction,
      statusLoading,
      statusOptions
    ]
  );
  const renderProductItem = (0, import_react.useCallback)(
    (item) => {
      var _a2;
      return /* @__PURE__ */ import_react.default.createElement(
        LineItem,
        {
          key: ((_a2 = item.metadata) == null ? void 0 : _a2.unique_identification_number) || item.order_detail_id || item.product_id,
          itemType: "product",
          type: "a9",
          isShowBookingHeader: false,
          rightActions: (interactionPolicy == null ? void 0 : interactionPolicy.isShowRightActions) ? renderQuantityAction(item) : [],
          escapeDom: ".pisell-number-selector-popover",
          dataSource: item,
          onAction: voidFn,
          onDelete: () => handleRemoveItem(item),
          onNote: voidFn,
          onLike: voidFn,
          onEditProduct: () => handleEditCartLine(item),
          onCard: getCardHandler(item),
          onChangeResource: () => handleEditCartLine(item),
          onChangeHolder: voidFn,
          onAddHolder: voidFn,
          isShowNote: true,
          isShowPackageNote: true,
          disabledEdit: interactionPolicy == null ? void 0 : interactionPolicy.disabledEdit,
          isShowChangeResource: false,
          isShowChangeHolder: false,
          isShowDelete: interactionPolicy == null ? void 0 : interactionPolicy.isShowDelete,
          isShowHolder: false,
          isShowAddHolderButton: false,
          isShowEditProduct: false,
          isShowAmountFooter: true,
          isShowImage: true,
          maxSpecsCount: 1,
          scenario: "booking2",
          onGift: handleGiftClick
        }
      );
    },
    [
      getCardHandler,
      handleEditCartLine,
      handleGiftClick,
      handleRemoveItem,
      interactionPolicy == null ? void 0 : interactionPolicy.disabledEdit,
      interactionPolicy == null ? void 0 : interactionPolicy.isShowDelete,
      interactionPolicy == null ? void 0 : interactionPolicy.isShowRightActions,
      renderQuantityAction
    ]
  );
  const buildItemNodes = (0, import_react.useCallback)(
    (bookingList, itemList) => [
      ...bookingList.map(renderBookingItem),
      ...itemList.map(renderProductItem)
    ],
    [renderBookingItem, renderProductItem]
  );
  const cartItemNodes = buildItemNodes(displayNormalBookings, displayNormalItems);
  const savedItemNodes = buildItemNodes(displaySavedBookings, displaySavedItems);
  const savedItemColumns = Array.from(
    { length: safeCols },
    () => []
  );
  savedItemNodes.forEach((node, index) => {
    savedItemColumns[index % safeCols].push(node);
  });
  const savedItemsContent = isMultiCol ? savedItemColumns.map((column, index) => /* @__PURE__ */ import_react.default.createElement("div", { key: index, className: "pisell-sale-detail-cart-items__column" }, column)) : savedItemNodes;
  const renderSavedItemsGroup = () => {
    if (!savedItemsCount) return null;
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-sale-detail-cart-items__saved" }, /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: "pisell-sale-detail-cart-items__saved-header",
        onClick: () => setIsSavedExpanded((expanded) => !expanded)
      },
      /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-cart-items__saved-title" }, import_utils.locales.getText("pisell2.text.shopping-cart.save.items")(
        savedItemsCount
      )),
      /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-cart-items__saved-summary" }, savedItemsTotal),
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.Iconfont,
        {
          type: "pisell2-chevron-down",
          className: "pisell-sale-detail-cart-items__saved-switch",
          style: {
            transform: isSavedExpanded ? "rotate(180deg)" : "rotate(0deg)"
          }
        }
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: [
          "pisell-sale-detail-cart-items__saved-content",
          isMultiCol ? "pisell-sale-detail-cart-items__saved-content--multi-col" : "",
          isSavedExpanded ? "is-expanded" : ""
        ].filter(Boolean).join(" "),
        style: isMultiCol ? containerStyle : void 0
      },
      savedItemsContent
    ));
  };
  const cartItemColumns = Array.from(
    { length: safeCols },
    () => []
  );
  cartItemNodes.forEach((node, index) => {
    cartItemColumns[index % safeCols].push(node);
  });
  return /* @__PURE__ */ import_react.default.createElement(
    "section",
    {
      className: [
        "pisell-sale-detail-cart-items",
        "pisell-sale-detail-cart-items--editable",
        isMultiCol ? "pisell-sale-detail-cart-items--multi-col" : "",
        className || ""
      ].filter(Boolean).join(" "),
      style: containerStyle
    },
    isEmpty && showEmpty ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-sale-detail-cart-items__empty" }, emptyText || import_utils.locales.getText("pisell2.sale-detail.no-selected-items")) : null,
    isMultiCol && cartItemNodes.length ? cartItemColumns.map((column, index) => /* @__PURE__ */ import_react.default.createElement("div", { key: index, className: "pisell-sale-detail-cart-items__column" }, column)) : cartItemNodes,
    renderSavedItemsGroup()
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CartItems
});
