var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/solution/BaseSales/utils/transformBaseProductToOrderProduct.ts
var transformBaseProductToOrderProduct_exports = {};
__export(transformBaseProductToOrderProduct_exports, {
  transformBaseProductToOrderProduct: () => transformBaseProductToOrderProduct
});
module.exports = __toCommonJS(transformBaseProductToOrderProduct_exports);
var import_manualProductDiscount = require("../../../modules/Order/utils/manualProductDiscount");
function toNumber(value, fallback = 0) {
  const parsedValue = Number(value);
  if (!Number.isFinite(parsedValue))
    return fallback;
  return parsedValue;
}
function toProductId(value) {
  if (value === null || value === void 0 || value === "")
    return null;
  const parsedValue = Number(value);
  if (!Number.isFinite(parsedValue))
    return null;
  return parsedValue;
}
function toSafePositiveInt(value, fallback = 1) {
  const parsedValue = Math.floor(Number(value));
  if (!Number.isFinite(parsedValue) || parsedValue < 1)
    return fallback;
  return parsedValue;
}
function toPriceString(value, fallback = "0.00") {
  const parsedValue = Number(value);
  if (!Number.isFinite(parsedValue))
    return fallback;
  return parsedValue.toFixed(2);
}
function normalizeOptionItems(optionItems) {
  if (!Array.isArray(optionItems))
    return [];
  return optionItems.map((optionItem) => {
    const optionGroupItemId = toNumber(optionItem == null ? void 0 : optionItem.option_group_item_id);
    const price = (optionItem == null ? void 0 : optionItem.price) ?? (optionItem == null ? void 0 : optionItem.add_price) ?? 0;
    return {
      option_group_item_id: optionGroupItemId,
      option_group_id: toNumber(optionItem == null ? void 0 : optionItem.option_group_id),
      num: toSafePositiveInt((optionItem == null ? void 0 : optionItem.num) ?? (optionItem == null ? void 0 : optionItem.quantity), 1),
      price: toNumber(price, 0)
    };
  });
}
function normalizeBundleItems(bundleItems, preferPriceField = false) {
  if (!Array.isArray(bundleItems))
    return [];
  return bundleItems.map((bundleItem) => {
    const unitSelling = preferPriceField ? bundleItem.price ?? bundleItem.bundle_selling_price ?? bundleItem.custom_price ?? bundleItem.product_price ?? "0" : bundleItem.bundle_selling_price ?? bundleItem.price ?? bundleItem.custom_price ?? bundleItem.product_price ?? "0";
    const unitStr = toPriceString(unitSelling, "0.00");
    const num = toSafePositiveInt((bundleItem == null ? void 0 : bundleItem.num) ?? (bundleItem == null ? void 0 : bundleItem.quantity), 1);
    return {
      ...bundleItem,
      num,
      quantity: (bundleItem == null ? void 0 : bundleItem.quantity) ?? num,
      price: bundleItem.price ?? unitStr,
      bundle_selling_price: unitStr,
      original_price: bundleItem.original_price ?? bundleItem.product_price ?? bundleItem.price ?? unitStr,
      option: normalizeOptionItems(bundleItem == null ? void 0 : bundleItem.option)
    };
  });
}
function findVariantById(origin, variantId) {
  if (!origin || !variantId || variantId <= 0)
    return null;
  const variants = Array.isArray(origin == null ? void 0 : origin.variant) ? origin.variant : [];
  return variants.find((variant) => Number(variant == null ? void 0 : variant.id) === variantId) || null;
}
function transformBaseProductToOrderProduct(params) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const { payload, fallbackProductId = null } = params;
  if (!payload || typeof payload !== "object")
    return null;
  const sourceProduct = params.sourceProduct || params.sourceItem || {};
  const productId = toProductId(
    payload.product_id ?? payload.id ?? (sourceProduct == null ? void 0 : sourceProduct.product_id) ?? (sourceProduct == null ? void 0 : sourceProduct.id) ?? fallbackProductId
  );
  if (productId === null)
    return null;
  const productVariantId = toNumber(
    payload.product_variant_id ?? payload.variant_id ?? (sourceProduct == null ? void 0 : sourceProduct.product_variant_id) ?? (sourceProduct == null ? void 0 : sourceProduct.variant_id),
    0
  );
  const callbackOrigin = payload.origin || ((_a = payload._origin) == null ? void 0 : _a.sourceProduct) || ((_b = payload._origin) == null ? void 0 : _b.sourceItem) || payload._origin || {};
  const origin = {
    ...sourceProduct || {},
    ...callbackOrigin || {}
  };
  const matchedVariant = findVariantById(callbackOrigin, productVariantId) ?? findVariantById(sourceProduct, productVariantId) ?? findVariantById(origin, productVariantId);
  const sourceProductPrice = toPriceString(
    payload.price ?? payload.selling_price ?? (matchedVariant == null ? void 0 : matchedVariant.price) ?? (matchedVariant == null ? void 0 : matchedVariant.base_price) ?? (origin == null ? void 0 : origin.price) ?? (origin == null ? void 0 : origin.base_price) ?? (sourceProduct == null ? void 0 : sourceProduct.price) ?? (sourceProduct == null ? void 0 : sourceProduct.selling_price) ?? (sourceProduct == null ? void 0 : sourceProduct.base_price),
    "0.00"
  );
  const lineCompositeTotal = toPriceString(
    payload.line_total ?? payload.total ?? ((_c = payload._extend) == null ? void 0 : _c.total),
    sourceProductPrice
  );
  const hasPriceOverride = payload.price_override !== void 0 && payload.price_override !== null && payload.price_override !== "";
  const productOptionItem = normalizeOptionItems(
    payload.option ?? payload.options ?? payload.product_option_item
  );
  const productBundle = normalizeBundleItems(
    payload.bundle ?? payload.product_bundle,
    hasPriceOverride
  );
  const uniqueIdentificationNumber = payload.unique_identification_number ?? payload.unique;
  const resolvedQuantity = toSafePositiveInt(payload.quantity ?? payload.num, 1);
  const originTotal = (0, import_manualProductDiscount.resolveManualDiscountOriginTotal)({
    originTotal: payload.origin_total,
    extendOriginTotal: (_d = payload._extend) == null ? void 0 : _d.origin_total,
    originExtendOriginTotal: (_e = origin == null ? void 0 : origin._extend) == null ? void 0 : _e.origin_total,
    sourceExtendOriginTotal: (_f = sourceProduct == null ? void 0 : sourceProduct._extend) == null ? void 0 : _f.origin_total,
    catalogUnitPrice: (origin == null ? void 0 : origin.base_price) ?? (origin == null ? void 0 : origin.price) ?? (sourceProduct == null ? void 0 : sourceProduct.base_price) ?? (sourceProduct == null ? void 0 : sourceProduct.price),
    quantity: resolvedQuantity
  });
  const sellingTotal = Number(
    payload.line_total ?? payload.total ?? ((_g = payload._extend) == null ? void 0 : _g.total) ?? lineCompositeTotal
  );
  const discountReason = (0, import_manualProductDiscount.resolveManualDiscountReasonFromSources)({
    discountReason: payload.discount_reason,
    extendDiscountReason: (_h = payload._extend) == null ? void 0 : _h.discount_reason,
    originExtendDiscountReason: (_i = origin == null ? void 0 : origin._extend) == null ? void 0 : _i.discount_reason
  });
  const lineOriginalPrice = hasPriceOverride && Number.isFinite(originTotal) ? toPriceString(originTotal) : lineCompositeTotal;
  const manualDiscountList = (0, import_manualProductDiscount.shouldBuildManualProductDiscount)({
    hasPriceOverride,
    originTotal,
    sellingTotal
  }) ? (0, import_manualProductDiscount.mergeManualProductDiscountIntoList)(
    payload.discount_list,
    (0, import_manualProductDiscount.buildManualProductDiscountItem)({
      originTotal: Number.isFinite(originTotal) ? originTotal : Number(lineOriginalPrice),
      sellingTotal: Number.isFinite(sellingTotal) ? sellingTotal : Number(lineCompositeTotal),
      quantity: resolvedQuantity,
      message: discountReason,
      discountway: (_j = payload._extend) == null ? void 0 : _j.discountway,
      discount_per: (_k = payload._extend) == null ? void 0 : _k.discount_per
    })
  ) : payload.discount_list || [];
  const metadata = {
    unique: payload.unique,
    session: payload.session,
    form: payload.form,
    service_times: payload.service_times,
    machine_code: payload.machine_code,
    schedule_id: payload.schedule_id,
    duration: payload.duration,
    policy_id: payload.policy_id,
    source_shop_id: payload.source_shop_id,
    origin,
    source_product_price: sourceProductPrice,
    main_product_selling_price: sourceProductPrice,
    main_product_original_price: sourceProductPrice,
    ...hasPriceOverride ? {
      price_override: String(payload.price_override),
      is_manual_discount: 1
    } : {},
    ...payload.bundle_edit !== void 0 ? { bundle_edit: payload.bundle_edit } : {}
  };
  if (uniqueIdentificationNumber) {
    metadata.unique_identification_number = String(uniqueIdentificationNumber);
  }
  return {
    product_id: productId,
    product_variant_id: productVariantId,
    unique_identification_number: uniqueIdentificationNumber ? String(uniqueIdentificationNumber) : void 0,
    num: resolvedQuantity,
    product_option_item: productOptionItem,
    product_bundle: productBundle,
    discount_list: manualDiscountList,
    // 折后行价由 normalizeOrderProduct 按 main + bundle 合成；手动改价时 bundle 已为分摊后单价
    selling_price: lineCompositeTotal,
    original_price: lineOriginalPrice,
    tax_fee: toPriceString(
      payload.tax_fee ?? (matchedVariant == null ? void 0 : matchedVariant.tax_fee) ?? (origin == null ? void 0 : origin.tax_fee) ?? (sourceProduct == null ? void 0 : sourceProduct.tax_fee),
      "0.00"
    ),
    is_charge_tax: toNumber(
      payload.is_charge_tax ?? (matchedVariant == null ? void 0 : matchedVariant.is_charge_tax) ?? (origin == null ? void 0 : origin.is_charge_tax) ?? (sourceProduct == null ? void 0 : sourceProduct.is_charge_tax),
      0
    ),
    metadata,
    note: payload.note != null ? String(payload.note) : "",
    _origin: {
      ...sourceProduct || {},
      callbackData: payload
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  transformBaseProductToOrderProduct
});
