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_NumericStepper = __toESM(require("../../../../pro/NumericStepper"));
var import_LineItem = __toESM(require("../LineItem"));
var import_useAdjustTimeModal = require("../../hooks/useAdjustTimeModal");
var import_SaleDetailAdjustTimeContext = require("../../context/SaleDetailAdjustTimeContext");
var import_index = require("./index.less");
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 QUANTITY_ESCAPE_DOM = ".pisell-number-selector-popover, .numeric-stepper-keyboard-popover, .numeric-stepper-keyboard-modal";
var STATUS_TRANSITION_ACTIONS = {
  confirmed: "confirm",
  arrived: "arrive",
  started: "start",
  completed: "complete",
  cancelled: "cancel",
  no_show: "no_show"
};
var BOOKING_TERMINAL_STATUSES = ["cancelled", "no_show", "completed"];
var BOOKING_ALLOWED_NEXT_STATUSES = {
  new: ["arrived", "cancelled", "no_show", "completed"],
  confirmed: ["arrived", "cancelled", "no_show"],
  arrived: ["cancelled", "completed"],
  started: ["cancelled", "completed"]
};
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 getBookingScheduleEventId = (item) => {
  return item == null ? void 0 : item.schedule_event_id;
};
var getBookingCurrentStatus = (item) => {
  return String((item == null ? void 0 : item.appointment_status) ?? (item == null ? void 0 : item.status) ?? "").trim();
};
var getAllowedBookingNextStatuses = (currentStatus) => {
  if (BOOKING_TERMINAL_STATUSES.includes(currentStatus)) return [];
  return BOOKING_ALLOWED_NEXT_STATUSES[currentStatus] || [];
};
var voidFn = () => {
};
function CartItems({
  context,
  sales,
  className,
  layout,
  showEmpty,
  emptyText,
  interactionPolicy,
  showBookingItems = true,
  showProductItems = true
}) {
  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 { hasAddTimeForItem, openAdjustTime, adjustTimeModal } = (0, import_useAdjustTimeModal.useAdjustTimeModal)({
    booking: context.booking,
    cartBookings: bookings,
    sales: resolvedSales
  });
  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((layout == null ? void 0 : layout.columns) || 1));
  const isMultiCol = safeCols > 1;
  const containerStyle = isMultiCol ? {
    "--pisell-cart-cols": safeCols
  } : void 0;
  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, item) => {
      const next = status.trim();
      if (!next) {
        import_antd.message.error(
          import_utils.locales.getText("pisell2.sale-detail.status-empty-error")
        );
        return;
      }
      const action = STATUS_TRANSITION_ACTIONS[next];
      if (!action) return;
      const currentStatus = getBookingCurrentStatus(item);
      if (!getAllowedBookingNextStatuses(currentStatus).includes(next)) return;
      const scheduleEventId = getBookingScheduleEventId(item);
      if (scheduleEventId == null || scheduleEventId === "") {
        import_antd.message.error("[SalesSdk] Booking: schedule_event_id 缺失");
        return;
      }
      if (!(resolvedSales == null ? void 0 : resolvedSales.transitionChildBooking)) return;
      setStatusLoading(true);
      try {
        await resolvedSales.transitionChildBooking({
          schedule_event_id: scheduleEventId,
          action
        });
      } catch (e) {
        import_antd.message.error(String((e == null ? void 0 : e.message) ?? e));
      } finally {
        setStatusLoading(false);
      }
    },
    [resolvedSales]
  );
  const getBookingStatusOptions = (0, import_react.useCallback)(
    (item) => {
      const currentStatus = getBookingCurrentStatus(item);
      const allowedNextStatuses = getAllowedBookingNextStatuses(currentStatus);
      return statusOptions.filter(
        (option) => option.key === currentStatus || allowedNextStatuses.includes(option.key)
      );
    },
    [statusOptions]
  );
  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 handleEdit = (0, import_react.useCallback)(
    (item) => {
      if (interactionPolicy == null ? void 0 : interactionPolicy.onEdit) {
        interactionPolicy.onEdit(item);
        return;
      }
      void handleEditCartLine(item);
    },
    [handleEditCartLine, interactionPolicy]
  );
  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_NumericStepper.default,
          {
            min: 1,
            className: "pisell-sale-detail-cart-items__numeric-stepper",
            value: getBookingQuantity(item),
            disabled: Boolean(quantityLoadingKeys[getCartLineKey(item)]),
            onChange: (value) => handleQuantityChange(item, value),
            variant: "capsule",
            size: "middle",
            enableInput: true,
            plusOnlyAtZero: false
          }
        ),
        color: "#667085"
      }
    ],
    [handleQuantityChange, quantityLoadingKeys]
  );
  const cartItemNodes = [
    ...showBookingItems ? displayBookings.map((item) => {
      var _a2, _b2;
      return /* @__PURE__ */ import_react.default.createElement(
        import_LineItem.default,
        {
          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: QUANTITY_ESCAPE_DOM,
          dataSource: item,
          statusOptions: getBookingStatusOptions(item),
          statusLoading,
          statusDisabled: !(resolvedSales == null ? void 0 : resolvedSales.transitionChildBooking) || getBookingScheduleEventId(item) == null || getBookingScheduleEventId(item) === "" || getAllowedBookingNextStatuses(getBookingCurrentStatus(item)).length === 0,
          onBookingStatusChange: handleBookingStatusChange,
          onAction: voidFn,
          onDelete: () => handleRemoveItem(item),
          onNote: voidFn,
          onCard: getCardHandler(item),
          onEdit: handleEdit,
          showAddTime: Boolean(((_b2 = item._extend) == null ? void 0 : _b2.canAddTime) || hasAddTimeForItem(item)),
          onAddTime: openAdjustTime,
          onPromotion: voidFn,
          isShowNote: true,
          disabledEdit: interactionPolicy == null ? void 0 : interactionPolicy.disabledEdit,
          disabledBookingEdit: interactionPolicy == null ? void 0 : interactionPolicy.disabledBookingEdit,
          isShowDelete: interactionPolicy == null ? void 0 : interactionPolicy.isShowDelete,
          isShowAmountFooter: true,
          isShowImage: true,
          maxSpecsCount: 1,
          scenario: "booking2",
          onGift: handleGiftClick,
          isFormSubject: item.isFormSubject ?? defaultIsFormSubject,
          holderOptions: item.holderOptions
        }
      );
    }) : [],
    ...showProductItems ? displayItems.map((item) => {
      var _a2;
      return /* @__PURE__ */ import_react.default.createElement(
        import_LineItem.default,
        {
          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: QUANTITY_ESCAPE_DOM,
          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
        }
      );
    }) : []
  ];
  const isEmpty = !cartItemNodes.some(Boolean);
  const cartItemColumns = Array.from(
    { length: safeCols },
    () => []
  );
  cartItemNodes.forEach((node, index) => {
    cartItemColumns[index % safeCols].push(node);
  });
  if (isEmpty) {
    return null;
  }
  return /* @__PURE__ */ import_react.default.createElement(import_SaleDetailAdjustTimeContext.SaleDetailAdjustTimeContext.Provider, { value: openAdjustTime }, /* @__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: 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 ? cartItemColumns.map((column, index) => /* @__PURE__ */ import_react.default.createElement("div", { key: index, className: "pisell-sale-detail-cart-items__column" }, column)) : cartItemNodes,
    adjustTimeModal
  ));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CartItems
});
