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 _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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import dayjs from 'dayjs';
import { getHorizontalAxisSlotCount } from '@pisell/materials';
import { RESERVATION_TIMELINE_BUSINESS_RANGE } from "../reservationConstants";
import { bookingTimeWindowForReservationView } from "../hooks/usePisellReservationBookingData";
var TIMELINE_RANGE_FORMAT = 'YYYY-MM-DD HH:mm';

/**
 * 与顶栏 PisellTimeNavigator / 平面图列表请求共用 {@link bookingTimeWindowForReservationView}。
 * 用于 `getTimelineHighlights(列表, startStr, endStr)` 与宿主对齐。
 */
export function reservationTimelineRangeStrings(scheduleDate) {
  var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : RESERVATION_TIMELINE_BUSINESS_RANGE;
  var operatingDayBoundary = arguments.length > 2 ? arguments[2] : undefined;
  var wallClock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : dayjs();
  var _bookingTimeWindowFor = bookingTimeWindowForReservationView(scheduleDate, operatingDayBoundary, range, wallClock),
    _bookingTimeWindowFor2 = _slicedToArray(_bookingTimeWindowFor, 2),
    rangeStart = _bookingTimeWindowFor2[0],
    rangeEnd = _bookingTimeWindowFor2[1];
  return {
    startStr: rangeStart.format(TIMELINE_RANGE_FORMAT),
    endStr: rangeEnd.format(TIMELINE_RANGE_FORMAT)
  };
}

/**
 * 解析宿主 `sales.getTimelineHighlights` 返回值：数字序列（如 [0,0,1,1,2,…]），用于时间轴折线。
 * 支持数组、类数组（含 TypedArray）、可迭代对象。
 */
export function normalizeSalesTimelineHighlightsRaw(raw) {
  var values;
  if (Array.isArray(raw)) {
    values = raw;
  } else if (raw != null && _typeof(raw) === 'object') {
    if (Symbol.iterator in raw) {
      try {
        values = Array.from(raw);
      } catch (_unused) {
        return null;
      }
    } else {
      var keys = Object.keys(raw).filter(function (k) {
        return /^\d+$/.test(k);
      }).sort(function (a, b) {
        return Number(a) - Number(b);
      });
      if (keys.length === 0) return null;
      values = keys.map(function (k) {
        return raw[k];
      });
    }
  } else {
    return null;
  }
  var out = values.map(function (v) {
    var n = typeof v === 'number' ? v : Number(v);
    return Number.isFinite(n) ? Math.max(0, Math.round(n)) : 0;
  });
  return out.length > 0 ? out : null;
}

/**
 * 将宿主返回的密度序列裁剪/补零到与当前时间轴格数一致（与 PisellTimeNavigator 内 `axis.ticks` 长度对齐）。
 */
export function fitTimelineHighlightsToSlotCount(series, slotCount) {
  var n = Math.max(1, slotCount);
  if (series.length === n) return _toConsumableArray(series);
  if (series.length > n) return series.slice(0, n);
  return [].concat(_toConsumableArray(series), _toConsumableArray(new Array(n - series.length).fill(0)));
}

/** 预约页时间轴在指定锚定日、步长下的横向格数（与 TimeNavigator + 营业 range 一致） */
export function reservationTimelineAxisSlotCount(referenceDate, stepMinutes) {
  var range = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : RESERVATION_TIMELINE_BUSINESS_RANGE;
  return getHorizontalAxisSlotCount(range, referenceDate.startOf('day'), stepMinutes);
}

/**
 * 时间轴密度层：按 referenceDate 所在自然日统计预约开始时刻落入的槽位。
 */
export function computeReservationDensityBuckets(densityRows, referenceDate, stepMinutes) {
  var day = referenceDate.startOf('day');
  var slotCount = Math.max(1, Math.round(24 * 60 / Math.max(1, stepMinutes)));
  var buckets = new Array(slotCount).fill(0);
  var _iterator = _createForOfIteratorHelper(densityRows),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _ref, _ref2;
      var row = _step.value;
      var raw = (_ref = (_ref2 = row.bookingTimeStart) !== null && _ref2 !== void 0 ? _ref2 : row.start_at) !== null && _ref !== void 0 ? _ref : row.start_date && row.start_time ? "".concat(row.start_date, " ").concat(row.start_time) : undefined;
      if (!raw || typeof raw !== 'string') continue;
      var t = dayjs(raw);
      if (!t.isValid() || !t.isSame(day, 'day')) continue;
      var idx = Math.min(slotCount - 1, Math.floor((t.hour() * 60 + t.minute()) / stepMinutes));
      buckets[idx] += 1;
    }
    /** 无当天数据时给一条可视 mock 折线，便于验证密度层布局 */
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  if (!buckets.some(function (v) {
    return v > 0;
  })) {
    return buckets.map(function (_, i) {
      var waveA = Math.sin(i / Math.max(1, slotCount - 1) * Math.PI * 2);
      var waveB = Math.sin(i / Math.max(1, slotCount - 1) * Math.PI * 6);
      return Math.max(0, Math.round(2 + waveA * 2 + waveB));
    });
  }
  return buckets;
}