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/index.tsx
var CartItems_exports = {};
__export(CartItems_exports, {
  CartItems: () => CartItems
});
module.exports = __toCommonJS(CartItems_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_pisellNumberSelector = __toESM(require("../../../../pro/pisellNumberSelector"));
var import_index = require("./index.less");
var { LineItem } = import_materials.ProductCard;
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, _b, _c, _d, _e, _f, _g, _h;
  return String(
    ((_c = (_b = (_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.product) == null ? void 0 : _b._identity) == null ? void 0 : _c.unique_identification_number) || ((_f = (_e = (_d = item == null ? void 0 : item._extend) == null ? void 0 : _d.product) == null ? void 0 : _e.metadata) == null ? void 0 : _f.unique_identification_number) || ((_g = item == null ? void 0 : item._identity) == null ? void 0 : _g.unique_identification_number) || ((_h = item == null ? void 0 : item.metadata) == null ? void 0 : _h.unique_identification_number) || (item == null ? void 0 : item.product_uid) || (item == null ? void 0 : item.booking_id) || (item == null ? void 0 : item.order_detail_id) || (item == null ? void 0 : item.product_id) || ""
  );
};
function CartItems({
  context,
  sales,
  className,
  productsPerRow,
  showEmpty,
  emptyText
}) {
  var _a, _b, _c, _d, _e, _f;
  const [statusLoading, setStatusLoading] = (0, import_react.useState)(false);
  const [quantityLoadingKeys, setQuantityLoadingKeys] = (0, import_react.useState)({});
  const editingRef = (0, import_react.useRef)(false);
  const cart = context.cart;
  const resolvedSales = (context == null ? void 0 : context.sales) || sales;
  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 safeCols = Math.max(1, Math.floor(productsPerRow || 1));
  const isMultiCol = safeCols > 1;
  const isEmpty = !bookings.length && !items.length;
  const defaultIsFormSubject = ((_f = (_e = (_d = (_c = (_b = (_a = context.booking) == null ? void 0 : _a.getBookingConfig) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.config) == null ? void 0 : _d.basic) == null ? void 0 : _e.appointment_subject) == null ? void 0 : _f.type) === "form";
  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 renderQuantityAction = (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"
    }
  ];
  return /* @__PURE__ */ import_react.default.createElement(
    "section",
    {
      className: [
        "pisell-sale-detail-cart-items",
        isMultiCol ? "pisell-sale-detail-cart-items--multi-col" : "",
        className || ""
      ].filter(Boolean).join(" "),
      style: isMultiCol ? { ["--pisell-cart-cols"]: safeCols } : void 0
    },
    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,
    displayBookings.map((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",
          rightActions: renderQuantityAction(item),
          escapeDom: ".pisell-number-selector-popover",
          dataSource: item,
          statusOptions,
          statusLoading,
          onBookingStatusChange: void 0,
          onAction: () => {
          },
          onDelete: () => handleRemoveItem(item),
          onNote: () => {
          },
          onCard: () => handleEditCartLine(item),
          onPromotion: () => {
          },
          isShowNote: true,
          disabledEdit: true,
          isShowDelete: true,
          isShowAmountFooter: true,
          isShowImage: true,
          maxSpecsCount: 1,
          scenario: "booking2",
          onGift: handleGiftClick,
          isFormSubject: item.isFormSubject ?? defaultIsFormSubject,
          holderOptions: item.holderOptions
        }
      );
    }),
    displayItems.map((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",
          rightActions: renderQuantityAction(item),
          escapeDom: ".pisell-number-selector-popover",
          dataSource: item,
          onAction: () => {
          },
          onDelete: () => handleRemoveItem(item),
          onNote: () => {
          },
          onLike: () => {
          },
          onEditProduct: () => handleEditCartLine(item),
          onCard: () => handleEditCartLine(item),
          onChangeResource: () => handleEditCartLine(item),
          onChangeHolder: () => {
          },
          onAddHolder: () => {
          },
          isShowNote: true,
          isShowPackageNote: true,
          disabledEdit: true,
          isShowChangeResource: false,
          isShowChangeHolder: false,
          isShowDelete: true,
          isShowHolder: false,
          isShowAddHolderButton: false,
          isShowEditProduct: false,
          isShowAmountFooter: true,
          isShowImage: true,
          maxSpecsCount: 1,
          scenario: "booking2",
          onGift: handleGiftClick
        }
      );
    })
  );
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CartItems
});
