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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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 { getUniqueId } from '@pisell/utils';
import Decimal from 'decimal.js';
import { genHolderKey, genServiceKey } from "../../../components/ticketBooking/utils";
import { getServiceTimes } from "../../../components/booking/utils";
import { setProductPrice } from "../../../components/booking/info2/service/editService/utils";
import { mergeFormIntoExtend } from "./mergeFormIntoExtend";
import { resolveCacheItemForResourceCheck } from "./resolveCacheItemForResourceCheck";
import { applyHolderToCacheItem, normalizeSelectedHolderIds } from "../utils/applyHolderToCacheItem";
/** 手动改价时剔除旧 type=product 项；新项由 OS transform 根据 origin/total/reason 合成 */
function stripManualProductDiscountFromList(discountList) {
  return (discountList || []).filter(function (item) {
    return (item === null || item === void 0 ? void 0 : item.type) !== 'product';
  });
}

/**
 * 将编辑抽屉表单值合并为可交给 `cart.confirmBookingEdit` 的 cacheItem。
 * 对齐 Info2 editService `onFinish` 的核心合并逻辑，不写 miniRedux / 不拆 service 列表。
 */
export function buildEditedCacheItem(options) {
  var _item$_extend2, _item$_extend3;
  var values = options.values,
    sourceItem = options.cacheItem,
    isEditGroup = options.isEditGroup,
    isChangeTotal = options.isChangeTotal,
    isPriceIncludeTax = options.isPriceIncludeTax,
    bookingConfig = options.bookingConfig,
    customerId = options.customerId,
    isFranchisee = options.isFranchisee,
    holderOptions = options.holderOptions;
  var item = _objectSpread(_objectSpread({
    is_price_include_tax: isPriceIncludeTax
  }, sourceItem), {}, {
    autoClose: false
  });
  var extend = mergeFormIntoExtend(item._extend, values);
  if (values.quantity !== undefined) {
    extend.other = _objectSpread(_objectSpread({}, extend.other || {}), {}, {
      quantity: values.quantity
    });
  }
  if (isEditGroup) {
    extend.quantity = 1;
    extend.startDate = extend === null || extend === void 0 ? void 0 : extend.start_date;
    extend.endDate = extend === null || extend === void 0 ? void 0 : extend.end_date;
  } else {
    var _getServiceTimes = getServiceTimes({
        _extend: extend
      }),
      startDate = _getServiceTimes.startDate,
      endDate = _getServiceTimes.endDate;
    extend.startDate = startDate;
    extend.endDate = endDate;
  }
  if (isChangeTotal) {
    var _ref, _extend$origin_total, _item$_extend;
    var originTotal = (_ref = (_extend$origin_total = extend.origin_total) !== null && _extend$origin_total !== void 0 ? _extend$origin_total : (_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.origin_total) !== null && _ref !== void 0 ? _ref : values.origin_total;
    applyManualDiscountToExtend(extend, values.total, originTotal);
    // OS transform 依赖 priceOverride 识别手动改价，并配合 origin_total 恢复划线原价
    extend.priceOverride = values.total;
    if (extend.origin_total == null || extend.origin_total === '') {
      extend.origin_total = originTotal;
    }
  }
  if (extend.bundle_edit !== undefined) {
    extend.bundle_edit = 1;
  }
  item._extend = extend;
  item._time = new Date().getTime();
  item._serviceKey = genServiceKey(item);
  item._holderKey = genHolderKey(item);
  item = applyHolderSplit(item);
  if (((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.holder_id) !== undefined) {
    item = applyHolderToCacheItem(item, normalizeSelectedHolderIds(item._extend.holder_id), {
      bookingConfig: bookingConfig,
      customerId: customerId,
      isFranchisee: isFranchisee,
      holderOptions: holderOptions
    });
  }
  item = setProductPrice(item, {
    newTotal: values.total,
    origin_total: (_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.origin_total
  });
  if (isChangeTotal) {
    // 保留券/GoodPass 等非 product 折扣；手动 product 项由 PisellOS transform 写入 discount_list
    item.discount_list = stripManualProductDiscountFromList(item.discount_list);
  }
  return resolveCacheItemForResourceCheck(_objectSpread(_objectSpread({}, item), {}, {
    new: 0
  }));
}
function applyManualDiscountToExtend(extend, total, originTotal) {
  var _extend$other, _extend$other2;
  var discountRatio = new Decimal(total).div(originTotal);
  var bundles = (extend === null || extend === void 0 || (_extend$other = extend.other) === null || _extend$other === void 0 ? void 0 : _extend$other.bundle) || [];
  var childProductsTotal = new Decimal(0);
  if (bundles.length > 0) {
    bundles.forEach(function (bundle) {
      var discountedPrice = new Decimal(bundle.original_price).mul(discountRatio).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
      bundle.bundle_selling_price = discountedPrice.toNumber();
      childProductsTotal = childProductsTotal.add(discountedPrice.mul(bundle.quantity));
    });
  }
  var mainProductTotal = new Decimal(total).sub(childProductsTotal);
  var mainProductQuantity = ((_extend$other2 = extend.other) === null || _extend$other2 === void 0 ? void 0 : _extend$other2.quantity) || extend.quantity || 1;
  extend.main_product_selling_price = mainProductTotal.div(mainProductQuantity).toNumber();
}

/** 多持有人拆行：SalesSdk 加车仍回传主行 cacheItem（与 Info2 列表拆行区分）。 */
function applyHolderSplit(item) {
  var _item$_extend4, _item$_extend5;
  var holderIds = (_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.holder_id;
  if ((holderIds === null || holderIds === void 0 ? void 0 : holderIds.length) > 1 || ((_item$_extend5 = item._extend) === null || _item$_extend5 === void 0 ? void 0 : _item$_extend5.quantity) > 1 && (holderIds === null || holderIds === void 0 ? void 0 : holderIds.length) >= 1) {
    var ids = _toConsumableArray(holderIds);
    item._extend.holder_id = ids[0];
    if (item._extend.quantity > 1) {
      item._extend.quantity = 1;
    }
    item._holderKey = genHolderKey(item);
    item._splitHolderRemainder = ids.slice(1).map(function (holder_id) {
      return {
        _id: getUniqueId(),
        holder_id: [holder_id],
        quantity: 1
      };
    });
  }
  return item;
}