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 _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 dayjs from 'dayjs';
import { resolveManualDiscountMessage } from "../../Order/utils/manualProductDiscount";
function safeFormat(value, fmt) {
  if (value === undefined || value === null) return undefined;
  var d = dayjs(value);
  if (!d.isValid()) return undefined;
  return d.format(fmt);
}
function normalizeTimeString(value) {
  if (value === undefined || value === null) return undefined;
  if (typeof value === 'string') {
    var t = value.trim();
    var hhmmFromHhmmss = t.match(/^(\d{1,2}:\d{2}):\d{2}$/);
    if (hhmmFromHhmmss) return hhmmFromHhmmss[1];
    if (/^\d{1,2}:\d{2}$/.test(t)) return t;
  }
  var d = dayjs(value);
  if (d.isValid()) return d.format('HH:mm');
  return undefined;
}

/**
 * bookings[].resources[] → cacheItem._extend.resource（与 cacheItemToBookingInput.flattenResources 互逆）。
 */
function unflattenResourceMap(resources) {
  var map = {};
  if (!Array.isArray(resources)) return map;
  resources.forEach(function (r) {
    var formId = r === null || r === void 0 ? void 0 : r.form_id;
    if (formId === undefined || formId === null) return;
    var key = String(formId);
    if (!map[key]) map[key] = [];
    map[key].push({
      form_id: formId,
      relation_id: r.relation_id,
      relation_type: r.relation_type || 'form',
      like_status: r.like_status || 'common',
      metadata: r.metadata ? _objectSpread({}, r.metadata) : undefined,
      children: r.children
    });
  });
  return map;
}

/**
 * 从 booking.metadata.capacity 还原 `_extend.capacity`（与 info2 ticketBooking getCapacity 对齐）。
 * 勿用 resources[].relation_id 反推人数维度 id。
 */
function resolveCapacityFromBooking(booking) {
  var _booking$metadata;
  var metaCap = (_booking$metadata = booking.metadata) === null || _booking$metadata === void 0 ? void 0 : _booking$metadata.capacity;
  if (Array.isArray(metaCap) && metaCap.length > 0) {
    return metaCap.map(function (item) {
      var _item$value;
      if (!item || _typeof(item) !== 'object') return null;
      if (item.id === undefined || item.id === null) return null;
      var row = {
        id: item.id,
        value: Number((_item$value = item.value) !== null && _item$value !== void 0 ? _item$value : 0)
      };
      if (item.name !== undefined) row.name = item.name;
      return row;
    }).filter(function (item) {
      return item != null;
    });
  }
  if (typeof metaCap === 'number' && Number.isFinite(metaCap)) {
    return [{
      id: 0,
      value: metaCap,
      name: ''
    }];
  }
  return [];
}
function resolveDurationForExtend(booking) {
  var duration = booking.duration;
  if (booking.sub_type === 'days' || booking.is_all === 1) {
    return duration;
  }
  if (typeof duration === 'number' && Number.isFinite(duration)) {
    return duration;
  }
  return duration;
}

/**
 * 从已加车的 order line + booking 反查 editService 所需的 cacheItem。
 *
 * 与 `buildCacheItemFromCartDetail` / `buildCacheItemFromDetail` 正向拼装互逆（在 getProductExtend 之前调用）。
 * 调用方须传入与该行关联的 booking（通常 bookings[].product_uid === product.metadata.unique_identification_number）。
 */
export function buildCacheItemFromOrderLine(input) {
  var _product$product_id, _product$selling_pric, _product$original_pri, _booking$metadata$hol, _booking$metadata2, _product$product_vari, _product$num, _ref, _ref2, _title, _booking$product, _booking$detail, _ref3, _product$note, _booking$detail2, _product$metadata, _product$metadata2, _ref4, _extension_type, _booking$product2, _title2, _booking$product3, _price, _product$order_detail, _ref5, _booking$id;
  var product = input.product,
    booking = input.booking,
    sourceProduct = input.sourceProduct;
  var resolvedId = (_product$product_id = product.product_id) !== null && _product$product_id !== void 0 ? _product$product_id : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.id;
  var selling = Number((_product$selling_pric = product.selling_price) !== null && _product$selling_pric !== void 0 ? _product$selling_pric : 0);
  var original = Number((_product$original_pri = product.original_price) !== null && _product$original_pri !== void 0 ? _product$original_pri : selling);
  var startDate = safeFormat(booking.start_date, 'YYYY-MM-DD');
  var endDate = safeFormat(booking.end_date, 'YYYY-MM-DD');
  var startTime = normalizeTimeString(booking.start_time);
  var endTime = normalizeTimeString(booking.end_time);
  var resource = unflattenResourceMap(booking.resources);
  var capacity = resolveCapacityFromBooking(booking);
  var holderId = (_booking$metadata$hol = (_booking$metadata2 = booking.metadata) === null || _booking$metadata2 === void 0 ? void 0 : _booking$metadata2.holder_id) !== null && _booking$metadata$hol !== void 0 ? _booking$metadata$hol : booking.holder_id;
  var other = {
    product_variant_id: (_product$product_vari = product.product_variant_id) !== null && _product$product_vari !== void 0 ? _product$product_vari : 0,
    option: Array.isArray(product.product_option_item) ? _toConsumableArray(product.product_option_item) : [],
    bundle: Array.isArray(product.product_bundle) ? _toConsumableArray(product.product_bundle) : []
  };
  var extend = {
    start_date: startDate ? dayjs(startDate) : undefined,
    end_date: endDate ? dayjs(endDate) : undefined,
    startDate: startDate ? dayjs(startDate) : undefined,
    endDate: endDate ? dayjs(endDate) : undefined,
    start_time: startTime,
    end_time: endTime,
    duration: resolveDurationForExtend(booking),
    sub_type: booking.sub_type,
    quantity: (_product$num = product.num) !== null && _product$num !== void 0 ? _product$num : 1,
    product_name: (_ref = (_ref2 = (_title = sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.title) !== null && _title !== void 0 ? _title : booking === null || booking === void 0 || (_booking$product = booking.product) === null || _booking$product === void 0 ? void 0 : _booking$product.title) !== null && _ref2 !== void 0 ? _ref2 : booking === null || booking === void 0 || (_booking$detail = booking.detail) === null || _booking$detail === void 0 ? void 0 : _booking$detail.product_title) !== null && _ref !== void 0 ? _ref : '',
    note: (_ref3 = (_product$note = product.note) !== null && _product$note !== void 0 ? _product$note : booking === null || booking === void 0 || (_booking$detail2 = booking.detail) === null || _booking$detail2 === void 0 ? void 0 : _booking$detail2.note) !== null && _ref3 !== void 0 ? _ref3 : '',
    price: selling,
    total: selling,
    origin_total: original,
    resource: resource,
    capacity: capacity,
    holder_id: holderId,
    other: other,
    like_status: booking.like_status || 'common',
    discount_reason: resolveManualDiscountMessage(product.discount_list, (_product$metadata = product.metadata) === null || _product$metadata === void 0 ? void 0 : _product$metadata.product_discount_reason) || undefined
  };
  var manualDiscount = (product.discount_list || []).find(function (d) {
    return (d === null || d === void 0 ? void 0 : d.type) === 'product';
  });
  if (manualDiscount && extend.origin_total === selling) {
    var _manualDiscount$amoun;
    var manualAmount = Number((_manualDiscount$amoun = manualDiscount.amount) !== null && _manualDiscount$amoun !== void 0 ? _manualDiscount$amoun : 0);
    if (Number.isFinite(manualAmount) && manualAmount > 0) {
      extend.origin_total = selling + manualAmount;
    }
  }
  if (((_product$metadata2 = product.metadata) === null || _product$metadata2 === void 0 ? void 0 : _product$metadata2.price_override) != null || manualDiscount) {
    extend.priceOverride = selling;
  }
  if (booking.holder !== undefined) {
    extend.holder = booking.holder;
  }
  if (Array.isArray(booking.relation_forms)) {
    extend.relation_forms = booking.relation_forms;
  }
  var base = _objectSpread(_objectSpread({}, sourceProduct || {}), {}, {
    id: resolvedId,
    product_id: resolvedId,
    extension_type: (_ref4 = (_extension_type = sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.extension_type) !== null && _extension_type !== void 0 ? _extension_type : booking === null || booking === void 0 || (_booking$product2 = booking.product) === null || _booking$product2 === void 0 ? void 0 : _booking$product2.extension_type) !== null && _ref4 !== void 0 ? _ref4 : sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.extension_type,
    title: (_title2 = sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.title) !== null && _title2 !== void 0 ? _title2 : booking === null || booking === void 0 || (_booking$product3 = booking.product) === null || _booking$product3 === void 0 ? void 0 : _booking$product3.title,
    price: (_price = sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.price) !== null && _price !== void 0 ? _price : selling,
    selling_price: product.selling_price,
    original_price: product.original_price,
    _extend: extend,
    new: 0,
    autoClose: false,
    order_detail_id: (_product$order_detail = product.order_detail_id) !== null && _product$order_detail !== void 0 ? _product$order_detail : null,
    booking_id: (_ref5 = (_booking$id = booking.id) !== null && _booking$id !== void 0 ? _booking$id : booking.booking_id) !== null && _ref5 !== void 0 ? _ref5 : 0
  });
  if ((sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.capacity) !== undefined) {
    base.capacity = sourceProduct.capacity;
  }
  if ((sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.duration) !== undefined) {
    base.duration = sourceProduct.duration;
  }
  if ((sourceProduct === null || sourceProduct === void 0 ? void 0 : sourceProduct.product_resource) !== undefined) {
    base.product_resource = sourceProduct.product_resource;
  }
  if (booking.schedule_event_id !== undefined) {
    base.schedule_event_id = booking.schedule_event_id;
  }
  return base;
}