function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
import Decimal from 'decimal.js';
import dayjs from 'dayjs';
import { createUuidV4 } from "../../../modules/Order/utils";
export function buildVenueIdentityKey(resourceId, groupIndex) {
  return "venue:".concat(resourceId, ":").concat(groupIndex, ":").concat(createUuidV4());
}
export function mergeConsecutiveSlots(slots) {
  if (!slots.length) return [];
  var sorted = _toConsumableArray(slots).sort(function (a, b) {
    return a.startTime.localeCompare(b.startTime);
  });
  var groups = [];
  var currentSlots = [sorted[0]];
  var currentStart = sorted[0].startTime;
  var currentEnd = sorted[0].endTime;
  var totalPrice = new Decimal(sorted[0].price || '0');
  for (var i = 1; i < sorted.length; i++) {
    var slot = sorted[i];
    if (slot.startTime === currentEnd) {
      currentEnd = slot.endTime;
      totalPrice = totalPrice.add(new Decimal(slot.price || '0'));
      currentSlots.push(slot);
    } else {
      groups.push({
        startTime: currentStart,
        endTime: currentEnd,
        totalPrice: totalPrice.toFixed(2),
        slotCount: currentSlots.length,
        slots: currentSlots
      });
      currentSlots = [slot];
      currentStart = slot.startTime;
      currentEnd = slot.endTime;
      totalPrice = new Decimal(slot.price || '0');
    }
  }
  groups.push({
    startTime: currentStart,
    endTime: currentEnd,
    totalPrice: totalPrice.toFixed(2),
    slotCount: currentSlots.length,
    slots: currentSlots
  });
  return groups;
}
export function buildPriceBreakdown(params) {
  var group = params.group,
    productId = params.productId,
    quotation = params.quotation;
  if (!group.slots.length) return [];
  var entries = [];
  var _iterator = _createForOfIteratorHelper(group.slots),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var slot = _step.value;
      var unitPrice = Number(slot.price || '0');
      var shelfId = quotation ? quotation.getQuotationShelfId({
        productId: productId,
        datetime: slot.startTime
      }) : 0;
      var startHm = dayjs(slot.startTime, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm');
      var endHm = dayjs(slot.endTime, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm');
      var last = entries[entries.length - 1];
      if (last && last.unit_price === unitPrice && last.quotation_shelf_id === shelfId && last.end_time === startHm) {
        last.end_time = endHm;
        last.quantity += 1;
      } else {
        entries.push({
          start_time: startHm,
          end_time: endHm,
          unit_price: unitPrice,
          quotation_shelf_id: shelfId,
          quantity: 1
        });
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return entries;
}
export function buildVenueResourceMetadata(params) {
  var _rawResource$form_nam, _ref, _rawResource$main_fie, _rawResource$combined;
  var mapping = params.mapping,
    rawResource = params.rawResource;
  return {
    form_name: (_rawResource$form_nam = rawResource === null || rawResource === void 0 ? void 0 : rawResource.form_name) !== null && _rawResource$form_nam !== void 0 ? _rawResource$form_nam : '',
    resource_name: (_ref = (_rawResource$main_fie = rawResource === null || rawResource === void 0 ? void 0 : rawResource.main_field) !== null && _rawResource$main_fie !== void 0 ? _rawResource$main_fie : mapping.resourceName) !== null && _ref !== void 0 ? _ref : '',
    combined_resource: (_rawResource$combined = rawResource === null || rawResource === void 0 ? void 0 : rawResource.combined_resource) !== null && _rawResource$combined !== void 0 ? _rawResource$combined : null
  };
}
export function buildVenueBookingEntry(params) {
  var _rawResource$form_id;
  var group = params.group,
    resourceId = params.resourceId,
    mapping = params.mapping,
    rawResource = params.rawResource,
    bookingUuid = params.bookingUuid,
    productUid = params.productUid,
    childResources = params.childResources;
  var startMoment = dayjs(group.startTime, 'YYYY-MM-DD HH:mm');
  var endMoment = dayjs(group.endTime, 'YYYY-MM-DD HH:mm');
  var duration = endMoment.diff(startMoment, 'minute');
  var resourceEntry = {
    relation_type: 'form',
    like_status: 'common',
    id: resourceId,
    main_field: mapping.resourceName,
    form_id: (_rawResource$form_id = rawResource === null || rawResource === void 0 ? void 0 : rawResource.form_id) !== null && _rawResource$form_id !== void 0 ? _rawResource$form_id : mapping.formId,
    relation_id: resourceId,
    capacity: 1,
    metadata: {}
  };
  if (childResources && childResources.length) {
    resourceEntry.children = childResources.map(function (child) {
      var _child$form_id, _child$capacity;
      return {
        relation_type: 'form',
        like_status: 'common',
        id: child.resourceId,
        main_field: child.main_field || '',
        form_id: (_child$form_id = child.form_id) !== null && _child$form_id !== void 0 ? _child$form_id : child.formId,
        relation_id: child.resourceId,
        capacity: (_child$capacity = child.capacity) !== null && _child$capacity !== void 0 ? _child$capacity : 1,
        metadata: {}
      };
    });
  }
  return {
    schedule_event_id: null,
    appointment_status: 'new',
    start_date: startMoment.format('YYYY-MM-DD'),
    start_time: startMoment.format('HH:mm'),
    end_date: endMoment.format('YYYY-MM-DD'),
    end_time: endMoment.format('HH:mm'),
    select_date: startMoment.format('YYYY-MM-DD'),
    duration: duration,
    sub_type: 'minutes',
    like_status: 'common',
    number: 1,
    is_all: false,
    schedule_id: 0,
    product_uid: productUid,
    resources: [resourceEntry],
    relation_products: [],
    relation_forms: [],
    holder: null,
    metadata: {
      unique_identification_number: bookingUuid,
      venue_booking: true,
      resource_id: resourceId,
      product_id: mapping.productId
    }
  };
}

/**
 * 从一条已合并的订单商品还原出独立的时段列表。
 * 优先使用 metadata.price_breakdown 还原每个时段的精确价格，
 * 回退到按 selling_price / slot_count 均分。
 */
export function expandMergedSlotToIndividual(product, slotDurationMinutes) {
  var meta = product.metadata || {};
  var resourceId = meta.resource_id;
  if (resourceId == null) return [];
  var startTime = meta.start_time;
  var endTime = meta.end_time;
  if (!startTime || !endTime) return [];
  var productId = Number(product.product_id);
  var breakdown = meta.price_breakdown;
  var result = [];
  var cursor = dayjs(startTime, 'YYYY-MM-DD HH:mm');
  var end = dayjs(endTime, 'YYYY-MM-DD HH:mm');
  if (breakdown !== null && breakdown !== void 0 && breakdown.length) {
    var priceMap = new Map();
    var _iterator2 = _createForOfIteratorHelper(breakdown),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var entry = _step2.value;
        var entryCursor = dayjs(entry.start_time, 'YYYY-MM-DD HH:mm');
        var entryEnd = dayjs(entry.end_time, 'YYYY-MM-DD HH:mm');
        while (entryCursor.isBefore(entryEnd)) {
          priceMap.set(entryCursor.format('HH:mm'), entry.unit_price);
          entryCursor = entryCursor.add(slotDurationMinutes, 'minute');
        }
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
    while (cursor.isBefore(end)) {
      var _priceMap$get;
      var slotEnd = cursor.add(slotDurationMinutes, 'minute');
      var hm = cursor.format('HH:mm');
      var price = (_priceMap$get = priceMap.get(hm)) !== null && _priceMap$get !== void 0 ? _priceMap$get : 0;
      result.push({
        resourceId: resourceId,
        productId: productId,
        startTime: cursor.format('YYYY-MM-DD HH:mm'),
        endTime: slotEnd.format('YYYY-MM-DD HH:mm'),
        price: new Decimal(price).toFixed(2)
      });
      cursor = slotEnd;
    }
  } else {
    var slotCount = meta.slot_count || 1;
    var totalPrice = new Decimal(product.selling_price || '0');
    var perSlotPrice = slotCount > 0 ? totalPrice.div(slotCount).toFixed(2) : totalPrice.toFixed(2);
    while (cursor.isBefore(end)) {
      var _slotEnd = cursor.add(slotDurationMinutes, 'minute');
      result.push({
        resourceId: resourceId,
        productId: productId,
        startTime: cursor.format('YYYY-MM-DD HH:mm'),
        endTime: _slotEnd.format('YYYY-MM-DD HH:mm'),
        price: perSlotPrice
      });
      cursor = _slotEnd;
    }
  }
  return result;
}