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/salesSdk/utils/editCartLineBooking.ts
var editCartLineBooking_exports = {};
__export(editCartLineBooking_exports, {
  editCartLineBooking: () => editCartLineBooking
});
module.exports = __toCommonJS(editCartLineBooking_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_buildProductLineUpdates = require("./buildProductLineUpdates");
var import_buildDefaultLoadProductsParams = require("./buildDefaultLoadProductsParams");
var import_mergeCatalogDurationIntoCacheItem = require("./mergeCatalogDurationIntoCacheItem");
var import_mergeBookingsForDisplay = require("./mergeBookingsForDisplay");
var import_identity = require("./identity");
var import_syncBookingLineQuantityByRows = require("./syncBookingLineQuantityByRows");
function findOrderLine(item, tempOrder) {
  var _a, _b, _c;
  const uid = ((_a = item._identity) == null ? void 0 : _a.unique_identification_number) ?? ((_b = item.metadata) == null ? void 0 : _b.unique_identification_number);
  if (!uid || !((_c = tempOrder == null ? void 0 : tempOrder.products) == null ? void 0 : _c.length)) return null;
  return tempOrder.products.find(
    (line) => {
      var _a2;
      return String((_a2 = line.metadata) == null ? void 0 : _a2.unique_identification_number) === String(uid);
    }
  ) ?? null;
}
function findBookingForLine(item, tempOrder) {
  var _a, _b, _c, _d;
  const uid = ((_a = item._identity) == null ? void 0 : _a.unique_identification_number) ?? ((_b = item.metadata) == null ? void 0 : _b.unique_identification_number);
  if (uid && ((_c = tempOrder == null ? void 0 : tempOrder.bookings) == null ? void 0 : _c.length)) {
    const matched = tempOrder.bookings.filter(
      (b) => String(b == null ? void 0 : b.product_uid) === String(uid)
    );
    const childBooking = matched.find(
      (b) => b.parent_id !== 0 && b.parent_id !== null && b.parent_id !== void 0
    );
    if (childBooking) return childBooking;
    if (matched[0]) return matched[0];
  }
  if ((_d = item._extend) == null ? void 0 : _d.booking) {
    return item._extend.booking;
  }
  return null;
}
function findCatalogProduct(productId, catalog) {
  if (productId == null) return void 0;
  return catalog.find((p) => String(p.id) === String(productId));
}
function hasProductResourceMeta(product) {
  var _a;
  const resources = (_a = product == null ? void 0 : product.product_resource) == null ? void 0 : _a.resources;
  return Array.isArray(resources) && resources.some((row) => Number(row == null ? void 0 : row.status) === 1);
}
function toComparablePrice(value) {
  if (value === void 0 || value === null || value === "") return null;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : null;
}
function shouldAllowBookingReprice(input) {
  const { orderLine, updates, bookingPatch } = input;
  if (!bookingPatch) return false;
  const meta = updates.metadata || {};
  const hasTopPrice = updates.selling_price !== void 0 || updates.original_price !== void 0;
  const hasMainMeta = meta.source_product_price !== void 0 || meta.main_product_selling_price !== void 0 || meta.main_product_original_price !== void 0;
  if (!hasTopPrice || !hasMainMeta) return false;
  const nextSelling = toComparablePrice(updates.selling_price);
  const currentSelling = toComparablePrice(orderLine.selling_price);
  const nextOriginal = toComparablePrice(updates.original_price);
  const currentOriginal = toComparablePrice(orderLine.original_price);
  return nextSelling !== null && currentSelling !== null && nextSelling !== currentSelling || nextOriginal !== null && currentOriginal !== null && nextOriginal !== currentOriginal;
}
async function fetchProductDetailForBookingEdit(bookingTicket, params) {
  if (typeof bookingTicket.queryProductDetail === "function") {
    return bookingTicket.queryProductDetail(params);
  }
  if (typeof bookingTicket.loadProductDetail === "function") {
    return bookingTicket.loadProductDetail(params);
  }
  return void 0;
}
async function resolveSourceProductForBookingEdit(input) {
  const { bookingTicket, orderLine, catalog, cartItem, booking } = input;
  const catalogItem = findCatalogProduct(orderLine.product_id, catalog);
  const cartView = cartItem;
  let merged = {
    ...catalogItem || {},
    id: (catalogItem == null ? void 0 : catalogItem.id) ?? orderLine.product_id,
    title: (catalogItem == null ? void 0 : catalogItem.title) ?? cartView.title ?? ""
  };
  if (!merged.product_resource && cartView.product_resource) {
    merged.product_resource = cartView.product_resource;
  }
  if (!merged.capacity && cartView.capacity) {
    merged.capacity = cartView.capacity;
  }
  if (hasProductResourceMeta(merged)) {
    return merged;
  }
  const scheduleDate = booking.start_date != null ? String(booking.start_date) : (0, import_dayjs.default)().format("YYYY-MM-DD");
  const startTime = booking.start_time != null ? String(booking.start_time) : (0, import_dayjs.default)().format("HH:mm");
  try {
    const detail = await fetchProductDetailForBookingEdit(bookingTicket, {
      product_id: Number(orderLine.product_id),
      schedule_date: scheduleDate,
      schedule_datetime: `${scheduleDate} ${startTime}:00`
    });
    if (detail) {
      merged = {
        ...merged,
        ...detail,
        id: detail.id ?? merged.id ?? orderLine.product_id,
        title: detail.title ?? merged.title ?? cartView.title ?? ""
      };
    }
  } catch (error) {
    console.warn("[SalesSdk] queryProductDetail before booking edit 失败", error);
  }
  return merged.id != null ? merged : null;
}
function patchCacheItemDisplayMeta(cacheItem, cartItem, sourceProduct) {
  var _a;
  const cartView = cartItem;
  const displayTitle = (sourceProduct == null ? void 0 : sourceProduct.title) ?? cartView.title ?? ((_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.product_name) ?? (cacheItem == null ? void 0 : cacheItem.title) ?? "";
  if (!displayTitle) {
    return cacheItem;
  }
  return {
    ...cacheItem,
    title: displayTitle,
    _extend: {
      ...cacheItem._extend || {},
      product_name: displayTitle
    }
  };
}
function patchMergedBookingQuantity(cacheItem, sources) {
  var _a;
  if (sources.length <= 1) {
    return cacheItem;
  }
  const quantity = (0, import_syncBookingLineQuantityByRows.resolveBookingLineQuantity)(sources);
  const holderIds = sources.flatMap((source) => {
    var _a2, _b, _c;
    const holderId = ((_b = (_a2 = source.booking) == null ? void 0 : _a2.metadata) == null ? void 0 : _b.holder_id) ?? ((_c = source.booking) == null ? void 0 : _c.holder_id);
    if (Array.isArray(holderId)) {
      return holderId.filter((id) => id !== void 0 && id !== null && id !== "");
    }
    return holderId !== void 0 && holderId !== null && holderId !== "" ? [holderId] : [];
  });
  return {
    ...cacheItem,
    _extend: {
      ...cacheItem._extend || {},
      quantity,
      ...holderIds.length ? { holder_id: holderIds } : {},
      other: {
        ...((_a = cacheItem._extend) == null ? void 0 : _a.other) || {},
        quantity
      }
    }
  };
}
function normalizeBookingRowProductPatch(productPatch) {
  return {
    ...productPatch,
    num: 1,
    metadata: {
      ...productPatch.metadata || {}
    }
  };
}
function resolveEditedBookingQuantity(edited, fallbackQuantity) {
  var _a, _b, _c;
  const raw = ((_b = (_a = edited == null ? void 0 : edited._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.quantity) ?? ((_c = edited == null ? void 0 : edited._extend) == null ? void 0 : _c.quantity) ?? fallbackQuantity;
  const quantity = Math.floor(Number(raw));
  return Number.isFinite(quantity) && quantity > 0 ? quantity : fallbackQuantity;
}
function buildEditedAppendSource(source, productPatch, bookingPatch) {
  return {
    ...source,
    product: {
      ...source.product,
      ...productPatch,
      metadata: {
        ...source.product.metadata || {},
        ...productPatch.metadata || {}
      }
    },
    booking: {
      ...source.booking,
      ...bookingPatch || {},
      metadata: {
        ...source.booking.metadata || {},
        ...(bookingPatch == null ? void 0 : bookingPatch.metadata) || {}
      }
    }
  };
}
function omitSplitHolderRemainder(cacheItem) {
  const next = { ...cacheItem };
  delete next._splitHolderRemainder;
  delete next._holderOptionsSnapshot;
  return next;
}
function rebuildSplitHolderForTarget(baseHolder, holderIds, holderOptions) {
  if (!baseHolder) return void 0;
  const holder = {
    ...baseHolder,
    form_record: holderIds
  };
  const names = holderIds.map((id) => {
    var _a;
    return (_a = holderOptions.find((option) => String(option.id) === String(id))) == null ? void 0 : _a.label;
  }).filter((label) => Boolean(label));
  if (names.length) {
    holder.name = names.join(",");
  } else {
    delete holder.name;
  }
  return holder;
}
function buildTargetEditedCacheItem(edited, targetIndex) {
  var _a, _b;
  const base = omitSplitHolderRemainder(edited);
  const remainder = Array.isArray(edited == null ? void 0 : edited._splitHolderRemainder) ? edited._splitHolderRemainder : [];
  const part = targetIndex === 0 ? null : remainder[targetIndex - 1];
  if (!part) {
    return base;
  }
  const holderIds = Array.isArray(part.holder_id) ? part.holder_id : [part.holder_id].filter((id) => id !== void 0 && id !== null && id !== "");
  const quantity = part.quantity ?? 1;
  const holderOptions = Array.isArray(edited == null ? void 0 : edited._holderOptionsSnapshot) ? edited._holderOptionsSnapshot : [];
  const holder = rebuildSplitHolderForTarget((_a = base._extend) == null ? void 0 : _a.holder, holderIds, holderOptions);
  return {
    ...base,
    _id: part._id ?? base._id,
    _extend: {
      ...base._extend || {},
      holder_id: holderIds,
      ...holder ? { holder } : {},
      quantity,
      other: {
        ...((_b = base._extend) == null ? void 0 : _b.other) || {},
        quantity
      }
    }
  };
}
async function ensureBookingContextBeforeEdit(bookingTicket, tempOrder, booking, bookingConfigParams) {
  var _a, _b;
  if (typeof bookingTicket.initBookingContext !== "function") return;
  const bookingIds = (0, import_buildDefaultLoadProductsParams.collectBookingIdsFromTempOrder)(tempOrder);
  const initParams = (0, import_buildDefaultLoadProductsParams.buildInitBookingContextParams)(bookingConfigParams, {
    date: booking.start_date ? (0, import_dayjs.default)(String(booking.start_date)) : (0, import_dayjs.default)(),
    bookingIds: bookingIds.length ? bookingIds : void 0,
    loadResources: true
  });
  const resourcesOrigin = ((_a = bookingTicket.getResourcesOrigin) == null ? void 0 : _a.call(bookingTicket)) ?? [];
  const contextReady = ((_b = bookingTicket.isBookingContextReady) == null ? void 0 : _b.call(bookingTicket, initParams)) ?? false;
  if (contextReady && resourcesOrigin.length > 0) {
    return;
  }
  await bookingTicket.initBookingContext({
    ...initParams,
    forceRefresh: contextReady && resourcesOrigin.length === 0
  });
}
async function editCartLineBooking(input) {
  var _a, _b, _c, _d, _e, _f;
  const { item, bookingTicket, uiHosts, updateItem } = input;
  const tempOrder = ((_a = bookingTicket.getTempOrder) == null ? void 0 : _a.call(bookingTicket)) ?? input.tempOrder ?? null;
  const mergedSources = (0, import_mergeBookingsForDisplay.getMergedBookingSources)(item);
  const editSources = mergedSources.length > 1 ? mergedSources : [];
  const primaryItem = ((_b = editSources[0]) == null ? void 0 : _b.product) ?? item;
  const booking = ((_c = editSources[0]) == null ? void 0 : _c.booking) ?? findBookingForLine(primaryItem, tempOrder);
  if (!booking) {
    throw new Error("[SalesSdk] 该行无关联 booking，无法编辑资源");
  }
  const orderLine = ((_d = editSources[0]) == null ? void 0 : _d.product) ?? findOrderLine(primaryItem, tempOrder);
  if (!orderLine) {
    throw new Error("[SalesSdk] 未在 tempOrder.products 找到对应商品行");
  }
  if (typeof bookingTicket.buildCacheItemFromOrderLine !== "function") {
    throw new Error("[SalesSdk] bookingTicket.buildCacheItemFromOrderLine 不可用，请升级 pisellos");
  }
  const catalog = input.productsCatalog ?? ((_f = (_e = bookingTicket.getProductCatalog) == null ? void 0 : _e.call(bookingTicket)) == null ? void 0 : _f.products) ?? [];
  const sourceProduct = await resolveSourceProductForBookingEdit({
    bookingTicket,
    orderLine,
    catalog,
    cartItem: primaryItem,
    booking
  });
  let cacheItem = bookingTicket.buildCacheItemFromOrderLine({
    product: orderLine,
    booking,
    sourceProduct: sourceProduct ?? null
  });
  cacheItem = (0, import_mergeCatalogDurationIntoCacheItem.mergeCatalogDurationIntoCacheItem)(
    cacheItem,
    sourceProduct ?? null,
    booking
  );
  cacheItem = patchCacheItemDisplayMeta(cacheItem, primaryItem, sourceProduct);
  cacheItem = patchMergedBookingQuantity(cacheItem, editSources);
  await ensureBookingContextBeforeEdit(
    bookingTicket,
    tempOrder,
    booking,
    input.bookingConfigParams
  );
  const openEdit = uiHosts == null ? void 0 : uiHosts.openBookingEdit;
  if (!openEdit) {
    throw new Error("[SalesSdk] uiHosts.openBookingEdit 未配置");
  }
  const date = booking.start_date != null ? String(booking.start_date) : null;
  const edited = await openEdit({
    cacheItem,
    date,
    forceOpen: true,
    deferMultiDayExpand: true,
    sourceProduct: sourceProduct ?? null,
    customerId: (tempOrder == null ? void 0 : tempOrder.customer_id) ?? void 0
  });
  if (!edited) {
    return { status: "cancelled" };
  }
  if (typeof bookingTicket.transformDetailToProductAndBooking !== "function") {
    throw new Error("[SalesSdk] bookingTicket.transformDetailToProductAndBooking 不可用");
  }
  const catalogItem = sourceProduct ?? { id: orderLine.product_id };
  const firstTargetEdited = buildTargetEditedCacheItem(edited, 0);
  const { product: productPatch, booking: bookingPatch } = bookingTicket.transformDetailToProductAndBooking({
    item: catalogItem,
    cacheItem: firstTargetEdited
  });
  const rowProductPatch = normalizeBookingRowProductPatch(productPatch);
  const targets = editSources.length > 1 ? editSources : [
    {
      booking,
      product: primaryItem,
      identity: (0, import_identity.pickIdentity)(primaryItem)
    }
  ];
  const targetQuantity = resolveEditedBookingQuantity(edited, targets.length || 1);
  const appendSource = buildEditedAppendSource(
    targets[0],
    rowProductPatch,
    bookingPatch
  );
  let products = [];
  for (const [targetIndex, target] of targets.entries()) {
    const targetEdited = targetIndex === 0 ? firstTargetEdited : buildTargetEditedCacheItem(edited, targetIndex);
    const targetTransformed = targetIndex === 0 ? { product: productPatch, booking: bookingPatch } : bookingTicket.transformDetailToProductAndBooking({
      item: catalogItem,
      cacheItem: targetEdited
    });
    const targetProductPatch = normalizeBookingRowProductPatch(targetTransformed.product);
    const targetBookingPatch = targetTransformed.booking;
    const updates = (0, import_buildProductLineUpdates.buildProductLineUpdates)(target.product, targetProductPatch);
    const allowBookingReprice = shouldAllowBookingReprice({
      orderLine: target.product,
      updates,
      bookingPatch: targetBookingPatch
    });
    products = await updateItem({
      ...target.identity,
      updates,
      booking: targetBookingPatch,
      ...allowBookingReprice ? { allow_booking_reprice: true } : {}
    });
  }
  products = input.syncQuantityByRows ? await input.syncQuantityByRows({
    sources: targets,
    targetQuantity,
    appendSource
  }) : await (0, import_syncBookingLineQuantityByRows.syncBookingLineQuantityByRows)({
    bookingTicket,
    sources: targets,
    targetQuantity,
    appendSource
  });
  return { status: "updated", products };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  editCartLineBooking
});
