function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { composeLinePrice, getBundleSellingMagnitude, normalizeProductSkuOptions, sumOptionUnitPrice } from "../../../modules/Order/utils";
import { buildManualProductDiscountItem, mergeManualProductDiscountIntoList, resolveManualDiscountOriginTotal, resolveManualDiscountReasonFromSources, shouldBuildManualProductDiscount } from "../../../modules/Order/utils/manualProductDiscount";
function toNumber(value) {
  var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var parsedValue = Number(value);
  if (!Number.isFinite(parsedValue)) return fallback;
  return parsedValue;
}
function toProductId(value) {
  if (value === null || value === undefined || value === '') return null;
  var parsedValue = Number(value);
  if (!Number.isFinite(parsedValue)) return null;
  return parsedValue;
}
function toSafePositiveInt(value) {
  var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var parsedValue = Math.floor(Number(value));
  if (!Number.isFinite(parsedValue) || parsedValue < 1) return fallback;
  return parsedValue;
}
function toPriceString(value) {
  var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '0.00';
  var parsedValue = Number(value);
  if (!Number.isFinite(parsedValue)) return fallback;
  return parsedValue.toFixed(2);
}
function normalizeOptionItems(optionItems) {
  if (!Array.isArray(optionItems)) return [];
  return optionItems.map(function (optionItem) {
    var _optionItem$option_gr, _ref, _optionItem$price, _optionItem$num;
    var optionGroupItemId = toNumber((_optionItem$option_gr = optionItem === null || optionItem === void 0 ? void 0 : optionItem.option_group_item_id) !== null && _optionItem$option_gr !== void 0 ? _optionItem$option_gr : optionItem === null || optionItem === void 0 ? void 0 : optionItem.id);
    var price = (_ref = (_optionItem$price = optionItem === null || optionItem === void 0 ? void 0 : optionItem.price) !== null && _optionItem$price !== void 0 ? _optionItem$price : optionItem === null || optionItem === void 0 ? void 0 : optionItem.add_price) !== null && _ref !== void 0 ? _ref : 0;
    return _objectSpread(_objectSpread({}, optionItem), {}, {
      option_group_item_id: optionGroupItemId,
      option_group_id: toNumber(optionItem === null || optionItem === void 0 ? void 0 : optionItem.option_group_id),
      num: toSafePositiveInt((_optionItem$num = optionItem === null || optionItem === void 0 ? void 0 : optionItem.num) !== null && _optionItem$num !== void 0 ? _optionItem$num : optionItem === null || optionItem === void 0 ? void 0 : optionItem.quantity, 1),
      add_price: toNumber(price, 0),
      price: undefined
    });
  });
}
function normalizeBundleItems(bundleItems) {
  var preferPriceField = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  if (!Array.isArray(bundleItems)) return [];
  return bundleItems.map(function (bundleItem) {
    var _ref2, _ref3, _ref4, _bundleItem$price, _ref5, _ref6, _ref7, _bundleItem$bundle_se, _bundleItem$num, _bundleItem$price2, _bundleItem$quantity, _bundleItem$price3, _ref8, _ref9, _bundleItem$original_, _normalizedItem$price;
    var unitSelling = preferPriceField ? (_ref2 = (_ref3 = (_ref4 = (_bundleItem$price = bundleItem.price) !== null && _bundleItem$price !== void 0 ? _bundleItem$price : bundleItem.bundle_selling_price) !== null && _ref4 !== void 0 ? _ref4 : bundleItem.custom_price) !== null && _ref3 !== void 0 ? _ref3 : bundleItem.product_price) !== null && _ref2 !== void 0 ? _ref2 : '0' : (_ref5 = (_ref6 = (_ref7 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref7 !== void 0 ? _ref7 : bundleItem.custom_price) !== null && _ref6 !== void 0 ? _ref6 : bundleItem.product_price) !== null && _ref5 !== void 0 ? _ref5 : '0';
    var unitStr = toPriceString(unitSelling, '0.00');
    var num = toSafePositiveInt((_bundleItem$num = bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.num) !== null && _bundleItem$num !== void 0 ? _bundleItem$num : bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.quantity, 1);
    var magnitudeSource = _objectSpread(_objectSpread({}, bundleItem), {}, {
      option: normalizeOptionItems(bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.option),
      bundle_selling_price: unitStr,
      // 计算 markdown 净额时，只传真实毛价；仅有 bundle_selling_price 时按历史净额兜底。
      price: (_bundleItem$price2 = bundleItem.price) !== null && _bundleItem$price2 !== void 0 ? _bundleItem$price2 : bundleItem.custom_price
    });
    var normalizedItem = _objectSpread(_objectSpread({}, bundleItem), {}, {
      num: num,
      quantity: (_bundleItem$quantity = bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.quantity) !== null && _bundleItem$quantity !== void 0 ? _bundleItem$quantity : num,
      // price 保留毛价（markdown 仍为正），由 price_type 决定符号。
      price: (_bundleItem$price3 = bundleItem.price) !== null && _bundleItem$price3 !== void 0 ? _bundleItem$price3 : unitStr,
      bundle_selling_price: unitStr,
      original_price: (_ref8 = (_ref9 = (_bundleItem$original_ = bundleItem.original_price) !== null && _bundleItem$original_ !== void 0 ? _bundleItem$original_ : bundleItem.product_price) !== null && _ref9 !== void 0 ? _ref9 : bundleItem.price) !== null && _ref8 !== void 0 ? _ref8 : unitStr,
      option: normalizeOptionItems(bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.option)
    });
    // bundle_selling_price 落「正净额」：markdown = |price| − Σoptions；markup/原价维持原值。
    normalizedItem.bundle_selling_price = getBundleSellingMagnitude(magnitudeSource).toFixed(2);
    if (((_normalizedItem$price = normalizedItem.price_type) !== null && _normalizedItem$price !== void 0 ? _normalizedItem$price : normalizedItem.custom_price_type) === 'markdown' && (normalizedItem.price_type_ext === '' || normalizedItem.price_type_ext === undefined || normalizedItem.price_type_ext === null)) {
      var _normalizedItem$custo;
      normalizedItem.custom_price = (_normalizedItem$custo = normalizedItem.custom_price) !== null && _normalizedItem$custo !== void 0 ? _normalizedItem$custo : normalizedItem.price;
      normalizedItem.price = normalizedItem.bundle_selling_price;
    }
    return normalizedItem;
  });
}
function findVariantById(origin, variantId) {
  if (!origin || !variantId || variantId <= 0) return null;
  var variants = Array.isArray(origin === null || origin === void 0 ? void 0 : origin.variant) ? origin.variant : [];
  return variants.find(function (variant) {
    return Number(variant === null || variant === void 0 ? void 0 : variant.id) === variantId;
  }) || null;
}

/**
 * 将商品列表原始数据 + 商品详情选择回调转换成 OrderModule.addProductToOrder 入参。
 *
 * 注意：这里不生成 identity，缺省时由 OrderModule 自动补齐。
 */
export function transformBaseProductToOrderProduct(params) {
  var _ref10, _ref11, _ref12, _payload$product_id, _ref13, _ref14, _payload$product_vari, _payload$_origin, _payload$_origin2, _ref15, _findVariantById, _ref16, _ref17, _ref18, _ref19, _ref20, _ref21, _ref22, _payload$price, _ref23, _payload$line_total, _payload$_extend, _ref24, _ref25, _payload$product_sku$, _payload$product_sku, _payload$bundle, _payload$quantity, _payload$_extend2, _extend, _extend2, _ref26, _ref27, _origin$base_price, _ref28, _ref29, _payload$line_total2, _payload$_extend3, _payload$_extend4, _extend3, _payload$_extend5, _payload$_extend6, _ref30, _ref31, _payload$tax_fee, _ref32, _ref33, _payload$is_charge_ta;
  var payload = params.payload,
    _params$fallbackProdu = params.fallbackProductId,
    fallbackProductId = _params$fallbackProdu === void 0 ? null : _params$fallbackProdu;
  if (!payload || _typeof(payload) !== 'object') return null;
  var sourceProduct = params.sourceProduct || params.sourceItem || {};
  var productId = toProductId((_ref10 = (_ref11 = (_ref12 = (_payload$product_id = payload.product_id) !== null && _payload$product_id !== void 0 ? _payload$product_id : payload.id) !== null && _ref12 !== void 0 ? _ref12 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.product_id) !== null && _ref11 !== void 0 ? _ref11 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.id) !== null && _ref10 !== void 0 ? _ref10 : fallbackProductId);
  if (productId === null) return null;
  var productVariantId = toNumber((_ref13 = (_ref14 = (_payload$product_vari = payload.product_variant_id) !== null && _payload$product_vari !== void 0 ? _payload$product_vari : payload.variant_id) !== null && _ref14 !== void 0 ? _ref14 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.product_variant_id) !== null && _ref13 !== void 0 ? _ref13 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.variant_id, 0);
  var callbackOrigin = payload.origin || ((_payload$_origin = payload._origin) === null || _payload$_origin === void 0 ? void 0 : _payload$_origin.sourceProduct) || ((_payload$_origin2 = payload._origin) === null || _payload$_origin2 === void 0 ? void 0 : _payload$_origin2.sourceItem) || payload._origin || {};
  var origin = _objectSpread(_objectSpread({}, sourceProduct || {}), callbackOrigin || {});
  var matchedVariant = (_ref15 = (_findVariantById = findVariantById(callbackOrigin, productVariantId)) !== null && _findVariantById !== void 0 ? _findVariantById : findVariantById(sourceProduct, productVariantId)) !== null && _ref15 !== void 0 ? _ref15 : findVariantById(origin, productVariantId);
  var sourceProductPrice = toPriceString((_ref16 = (_ref17 = (_ref18 = (_ref19 = (_ref20 = (_ref21 = (_ref22 = (_payload$price = payload.price) !== null && _payload$price !== void 0 ? _payload$price : payload.selling_price) !== null && _ref22 !== void 0 ? _ref22 : matchedVariant === null || matchedVariant === void 0 ? void 0 : matchedVariant.price) !== null && _ref21 !== void 0 ? _ref21 : matchedVariant === null || matchedVariant === void 0 ? void 0 : matchedVariant.base_price) !== null && _ref20 !== void 0 ? _ref20 : origin === null || origin === void 0 ? void 0 : origin.price) !== null && _ref19 !== void 0 ? _ref19 : origin === null || origin === void 0 ? void 0 : origin.base_price) !== null && _ref18 !== void 0 ? _ref18 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.price) !== null && _ref17 !== void 0 ? _ref17 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.selling_price) !== null && _ref16 !== void 0 ? _ref16 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.base_price, '0.00');
  var lineCompositeTotal = toPriceString((_ref23 = (_payload$line_total = payload.line_total) !== null && _payload$line_total !== void 0 ? _payload$line_total : payload.total) !== null && _ref23 !== void 0 ? _ref23 : (_payload$_extend = payload._extend) === null || _payload$_extend === void 0 ? void 0 : _payload$_extend.total, sourceProductPrice);
  var hasPriceOverride = payload.price_override !== undefined && payload.price_override !== null && payload.price_override !== '';
  var productOptionItem = normalizeProductSkuOptions(normalizeOptionItems((_ref24 = (_ref25 = (_payload$product_sku$ = (_payload$product_sku = payload.product_sku) === null || _payload$product_sku === void 0 ? void 0 : _payload$product_sku.option) !== null && _payload$product_sku$ !== void 0 ? _payload$product_sku$ : payload.option) !== null && _ref25 !== void 0 ? _ref25 : payload.options) !== null && _ref24 !== void 0 ? _ref24 : payload.product_option_item));
  var productBundle = normalizeBundleItems((_payload$bundle = payload.bundle) !== null && _payload$bundle !== void 0 ? _payload$bundle : payload.product_bundle, hasPriceOverride);
  // `payload.unique` 是业务侧商品/票务标识，可能在连续加同一商品时重复；
  // 行级唯一值只接受显式协议字段，缺省交给 OrderModule 生成。
  var uniqueIdentificationNumber = payload.unique_identification_number;
  var resolvedQuantity = toSafePositiveInt((_payload$quantity = payload.quantity) !== null && _payload$quantity !== void 0 ? _payload$quantity : payload.num, 1);
  var originTotal = resolveManualDiscountOriginTotal({
    originTotal: payload.origin_total,
    extendOriginTotal: (_payload$_extend2 = payload._extend) === null || _payload$_extend2 === void 0 ? void 0 : _payload$_extend2.origin_total,
    originExtendOriginTotal: origin === null || origin === void 0 || (_extend = origin._extend) === null || _extend === void 0 ? void 0 : _extend.origin_total,
    sourceExtendOriginTotal: sourceProduct === null || sourceProduct === void 0 || (_extend2 = sourceProduct._extend) === null || _extend2 === void 0 ? void 0 : _extend2.origin_total,
    catalogUnitPrice: (_ref26 = (_ref27 = (_origin$base_price = origin === null || origin === void 0 ? void 0 : origin.base_price) !== null && _origin$base_price !== void 0 ? _origin$base_price : origin === null || origin === void 0 ? void 0 : origin.price) !== null && _ref27 !== void 0 ? _ref27 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.base_price) !== null && _ref26 !== void 0 ? _ref26 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.price,
    quantity: resolvedQuantity
  });
  var sellingTotal = Number((_ref28 = (_ref29 = (_payload$line_total2 = payload.line_total) !== null && _payload$line_total2 !== void 0 ? _payload$line_total2 : payload.total) !== null && _ref29 !== void 0 ? _ref29 : (_payload$_extend3 = payload._extend) === null || _payload$_extend3 === void 0 ? void 0 : _payload$_extend3.total) !== null && _ref28 !== void 0 ? _ref28 : lineCompositeTotal);
  var discountReason = resolveManualDiscountReasonFromSources({
    discountReason: payload.discount_reason,
    extendDiscountReason: (_payload$_extend4 = payload._extend) === null || _payload$_extend4 === void 0 ? void 0 : _payload$_extend4.discount_reason,
    originExtendDiscountReason: origin === null || origin === void 0 || (_extend3 = origin._extend) === null || _extend3 === void 0 ? void 0 : _extend3.discount_reason
  });
  var lineOriginalPrice = hasPriceOverride && Number.isFinite(originTotal) ? toPriceString(originTotal) : lineCompositeTotal;
  var manualDiscountList = shouldBuildManualProductDiscount({
    hasPriceOverride: hasPriceOverride,
    originTotal: originTotal,
    sellingTotal: sellingTotal
  }) ? mergeManualProductDiscountIntoList(payload.discount_list, buildManualProductDiscountItem({
    originTotal: Number.isFinite(originTotal) ? originTotal : Number(lineOriginalPrice),
    sellingTotal: Number.isFinite(sellingTotal) ? sellingTotal : Number(lineCompositeTotal),
    quantity: resolvedQuantity,
    message: discountReason,
    discountway: (_payload$_extend5 = payload._extend) === null || _payload$_extend5 === void 0 ? void 0 : _payload$_extend5.discountway,
    discount_per: (_payload$_extend6 = payload._extend) === null || _payload$_extend6 === void 0 ? void 0 : _payload$_extend6.discount_per
  })) : payload.discount_list || [];

  // v2：source 不含 option；main_product_* 含 option（与 normalizeOrderProduct 一致）
  var optionSum = sumOptionUnitPrice(productOptionItem).toNumber();
  var mainProductOriginalPrice = toPriceString(Number(sourceProductPrice) + optionSum);
  var bundleOnlyComposite = composeLinePrice({
    mainPrice: 0,
    bundle: productBundle
  });
  var derivedMainSelling = Number(lineCompositeTotal) - Number(bundleOnlyComposite);
  var mainProductSellingPrice = toPriceString(Number.isFinite(derivedMainSelling) && derivedMainSelling >= 0 ? derivedMainSelling : Number(mainProductOriginalPrice));
  var metadata = _objectSpread(_objectSpread({
    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,
    source_product_price: sourceProductPrice,
    main_product_selling_price: mainProductSellingPrice,
    main_product_original_price: mainProductOriginalPrice,
    price_schema_version: 2
  }, hasPriceOverride ? {
    price_override: String(payload.price_override),
    is_manual_discount: 1
  } : {}), payload.bundle_edit !== undefined ? {
    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) : undefined,
    num: resolvedQuantity,
    product_sku: _objectSpread(_objectSpread({}, payload.product_sku && _typeof(payload.product_sku) === 'object' ? payload.product_sku : {}), {}, {
      option: productOptionItem
    }),
    product_bundle: productBundle,
    discount_list: manualDiscountList,
    // 折后行价由 normalizeOrderProduct 按 main + bundle 合成；手动改价时 bundle 已为分摊后单价
    selling_price: lineCompositeTotal,
    original_price: lineOriginalPrice,
    tax_fee: toPriceString((_ref30 = (_ref31 = (_payload$tax_fee = payload.tax_fee) !== null && _payload$tax_fee !== void 0 ? _payload$tax_fee : matchedVariant === null || matchedVariant === void 0 ? void 0 : matchedVariant.tax_fee) !== null && _ref31 !== void 0 ? _ref31 : origin === null || origin === void 0 ? void 0 : origin.tax_fee) !== null && _ref30 !== void 0 ? _ref30 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.tax_fee, '0.00'),
    is_charge_tax: toNumber((_ref32 = (_ref33 = (_payload$is_charge_ta = payload.is_charge_tax) !== null && _payload$is_charge_ta !== void 0 ? _payload$is_charge_ta : matchedVariant === null || matchedVariant === void 0 ? void 0 : matchedVariant.is_charge_tax) !== null && _ref33 !== void 0 ? _ref33 : origin === null || origin === void 0 ? void 0 : origin.is_charge_tax) !== null && _ref32 !== void 0 ? _ref32 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.is_charge_tax, 0),
    metadata: metadata,
    note: payload.note != null ? String(payload.note) : '',
    _origin: _objectSpread(_objectSpread({}, sourceProduct || {}), {}, {
      callbackData: payload
    })
  };
}