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); }
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); }
/**
 * 预约页与 RecordBoard 共用的纯函数：内置列表判定、筛参合并、按营业日改 booking 窗口、持久化 bodyView 读取。
 */
import dayjs from 'dayjs';
import { PISELL_RESERVATION_BODY_VIEW_STORAGE_KEY, PISELL_RESERVATION_FLOOR_MAP_APPEARANCE_STORAGE_PREFIX } from "../reservationConstants";
import { RESERVATION_TIMELINE_BUSINESS_RANGE } from "../reservationConstants";
import { bookingTimeWindowForReservationView, bookingTimeWindowForCalendarRange } from "../hooks/usePisellReservationBookingData";

/**
 * 比较两个 `booking_time_start_between` 窗口的**值**是否一致；
 * 支持 Dayjs / Date / string / number 混合（统一经 `dayjs()` 归一再取 `valueOf()`）。
 * 任一端不是长度为 2 的数组或某项不可解析时，保守返回 false（视为"有变化"，对应原行为）。
 */
function isSameBookingTimeWindow(a, b) {
  if (!Array.isArray(a) || !Array.isArray(b)) return false;
  if (a.length !== 2 || b.length !== 2) return false;
  try {
    for (var i = 0; i < 2; i++) {
      var av = dayjs(a[i]).valueOf();
      var bv = dayjs(b[i]).valueOf();
      if (!Number.isFinite(av) || !Number.isFinite(bv)) return false;
      if (av !== bv) return false;
    }
    return true;
  } catch (_unused) {
    return false;
  }
}

/**
 * 是否使用内置预约/资源请求：
 * - 未传 `data` / `null`；
 * - 或低代码只绑了空数组作占位，且未同时受控 total / onPageChange。
 *   （仅有 pagination 占位而无 onPageChange 时仍走内置，否则会永不请求列表。）
 */
export function shouldUseBuiltinReservationList(dataProp, totalProp, paginationProp, onPageChangeProp) {
  if (dataProp == null) return true;
  return Array.isArray(dataProp) && dataProp.length === 0 && totalProp === undefined && onPageChangeProp === undefined;
}

/**
 * 表格筛选若未带支付态默认值，接口可能返回空；与 QuickFilter/高级筛选项合并时保留 monitor 默认。
 */
export function mergeGridBookingSearchParams(params) {
  var p = params && _typeof(params) === 'object' ? _objectSpread({}, params) : {};
  var filterRaw = p.filter;
  var filter = _typeof(filterRaw) === 'object' && filterRaw !== null && !Array.isArray(filterRaw) ? _objectSpread({}, filterRaw) : {};
  var valuesRaw = filter.values;
  var values = _typeof(valuesRaw) === 'object' && valuesRaw !== null && !Array.isArray(valuesRaw) ? _objectSpread({}, valuesRaw) : {};
  if (!Array.isArray(values.order_payment_status) || values.order_payment_status.length === 0) {
    values.order_payment_status = undefined;
  }
  return _objectSpread(_objectSpread({}, p), {}, {
    filter: _objectSpread(_objectSpread({}, filter), {}, {
      values: values
    })
  });
}

/** 列表请求：平面图 / 资源墙 / 非日历视图下，按顶栏日程与时间轴营业窗更新 booking_time_start_between */
export function mergeSearchParamsBookingWindow(prev, anchorDay, operatingDayBoundary) {
  var timelineRange = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : RESERVATION_TIMELINE_BUSINESS_RANGE;
  var wallClock = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : dayjs();
  var prevFilter = _typeof(prev.filter) === 'object' && prev.filter ? prev.filter : {};
  var prevValues = _typeof(prevFilter.values) === 'object' && prevFilter.values ? prevFilter.values : {};
  var nextWindow = bookingTimeWindowForReservationView(anchorDay, operatingDayBoundary, timelineRange, wallClock);
  /**
   * 引用稳定化：若新旧 `booking_time_start_between` 值完全一致，返回原 `prev`，
   * 避免 `patchSearchParams` 误判为"参数变化"后触发不必要的 SSE 重连 / 列表重拉
   * （常见于 calendar day 视图切回 floorMap / resourceWall 时——值未变但每次都产生新对象引用）。
   */
  if (isSameBookingTimeWindow(prevValues.booking_time_start_between, nextWindow)) {
    return prev;
  }
  return _objectSpread(_objectSpread({}, prev), {}, {
    filter: _objectSpread(_objectSpread({}, prevFilter), {}, {
      values: _objectSpread(_objectSpread({}, prevValues), {}, {
        booking_time_start_between: nextWindow
      })
    })
  });
}

/**
 * 清理仅在日历周/月视图下设置的请求 flag：
 * - `compact_fields`：为 true 时，osServer 远端 SSE 走精简 with，不返回 booking.resources；
 * - `enable_remote_memory_cache`：开启后 osServer 会写入 `bookingRemoteCache`，Ably 推送时按 compact with 同步。
 *
 * 切回平面图 / 资源墙 / 表格时必须先清掉，否则非今日锚定下平面图会拿到无 resources 的 booking，
 * 导致按桌合并全部落空、画布空白。
 */
export function stripCalendarOnlyFlags(prev) {
  var prevFilter = _typeof(prev.filter) === 'object' && prev.filter ? prev.filter : {};
  var prevValuesRaw = _typeof(prevFilter.values) === 'object' && prevFilter.values ? prevFilter.values : {};
  if (!('compact_fields' in prevValuesRaw) && !('enable_remote_memory_cache' in prevValuesRaw)) {
    return prev;
  }
  var nextValues = _objectSpread({}, prevValuesRaw);
  delete nextValues.compact_fields;
  delete nextValues.enable_remote_memory_cache;
  return _objectSpread(_objectSpread({}, prev), {}, {
    filter: _objectSpread(_objectSpread({}, prevFilter), {}, {
      values: nextValues
    })
  });
}

/** 日历导航：按视口自然日范围扩展 `booking_time_start_between` */
export function mergeSearchParamsBookingRange(prev, rangeStart, rangeEnd, operatingDayBoundary) {
  var prevFilter = _typeof(prev.filter) === 'object' && prev.filter ? prev.filter : {};
  var prevValues = _typeof(prevFilter.values) === 'object' && prevFilter.values ? prevFilter.values : {};
  return _objectSpread(_objectSpread({}, prev), {}, {
    filter: _objectSpread(_objectSpread({}, prevFilter), {}, {
      values: _objectSpread(_objectSpread({}, prevValues), {}, {
        booking_time_start_between: bookingTimeWindowForCalendarRange(rangeStart, rangeEnd, operatingDayBoundary)
      })
    })
  });
}

/**
 * 按任意 key 读取表格/平面图偏好（与 PisellRecordBoard 内 read 规则一致）。
 */
export function readBodyViewFromStorageKey(key) {
  if (typeof window === 'undefined' || !key) return 'floorMap';
  try {
    var raw = localStorage.getItem(key);
    if (raw === 'grid' || raw === 'floorMap' || raw === 'calendar' || raw === 'resourceWall') return raw;
  } catch (_unused2) {
    /* quota / private mode */
  }
  return 'floorMap';
}

/**
 * 预约页默认持久化 key：有合法 localStorage 则用，否则平面图。
 */
export function readPersistedReservationBodyView() {
  return readBodyViewFromStorageKey(PISELL_RESERVATION_BODY_VIEW_STORAGE_KEY);
}
function getFloorMapAppearanceStorageKey(floorPlanCode) {
  return "".concat(PISELL_RESERVATION_FLOOR_MAP_APPEARANCE_STORAGE_PREFIX, ":").concat(floorPlanCode || 'default');
}

/**
 * 读取平面图操作栏「暗色背景」偏好，按门店/平面图 code 隔离；无缓存默认 `light`。
 */
export function readReservationFloorMapAppearanceMode(floorPlanCode) {
  if (typeof window === 'undefined') return 'light';
  try {
    var raw = localStorage.getItem(getFloorMapAppearanceStorageKey(floorPlanCode));
    if (raw === 'dark' || raw === 'light') return raw;
  } catch (_unused3) {
    /* quota / private mode */
  }
  return 'light';
}

/**
 * 写入平面图操作栏「暗色背景」偏好，按门店/平面图 code 隔离。
 */
export function writeReservationFloorMapAppearanceMode(floorPlanCode, mode) {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(getFloorMapAppearanceStorageKey(floorPlanCode), mode);
  } catch (_unused4) {
    /* quota / private mode */
  }
}