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 { useEffect, useMemo, useRef, useState } from 'react';
import dayjs from 'dayjs';
import { normalizeSalesTimelineHighlightsRaw, reservationTimelineRangeStrings } from "../data/reservationDensity";
import { normalizeSalesResourceBookingListResult } from "../data/reservationTablesMerge";
/**
 * 内置列表且资源台 + floorDayBooking 均就绪后，向宿主 sales 拉两套数据：
 * - `getResourceBookingList`：游标时刻下的预约子集，参与合并进平面图 dataSources；
 * - `getTimelineHighlights`：时间轴密度折线（无则退回 PisellReservation 内本地计算）。
 *
 * **跟随当前**：`followWallClock === true` 时第三个参数 `currentTimeStr` 与 `timeStr` 相同（均来自 `debouncedSchedule.at`），
 * 避免与墙钟 `dayjs()` 差一分钟；手动关闭跟随后仍传实时 `dayjs()`，保留「游标 vs 此刻」双通道语义。
 */
export function useReservationSalesHostData(options) {
  var isInternalListData = options.isInternalListData,
    pisellosRef = options.pisellosRef,
    hasPisellosGetModule = options.hasPisellosGetModule,
    debouncedSchedule = options.debouncedSchedule,
    followWallClock = options.followWallClock,
    resourceBoardLoading = options.resourceBoardLoading,
    floorDayBookingLoading = options.floorDayBookingLoading,
    floorDayBookingData = options.floorDayBookingData,
    floorDayBookingDataVersion = options.floorDayBookingDataVersion,
    scheduleDate = options.scheduleDate,
    timeNavigatorPropsProp = options.timeNavigatorPropsProp,
    timelineRange = options.timelineRange,
    operatingDayBoundary = options.operatingDayBoundary;
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    salesResourceBookings = _useState2[0],
    setSalesResourceBookings = _useState2[1];
  var salesBookingRequestRef = useRef(0);
  /** 非宿主 / sales 子模块拒绝时避免同一「日程 + 列表快照」下反复打接口与刷 console */
  var resourceListHostSkipRef = useRef(false);
  var resourceListRetryGateRef = useRef('');
  var debouncedAtMs = (debouncedSchedule === null || debouncedSchedule === void 0 ? void 0 : debouncedSchedule.at) != null && dayjs(debouncedSchedule.at).isValid() ? dayjs(debouncedSchedule.at).valueOf() : null;

  /**
   * 勿把 `floorDayBookingData` 数组引用直接放进 effect：useRequest 常给新的 `[]`，会触发死循环。
   *
   * 旧实现只采样头 24 条 id，导致 WS 推送只更新中后段 / 仅改字段不动顺序时，dep key 不变，
   * effect 不重跑 → `salesResourceBookings` 无法刷新 → 画布看上去"推送丢了 / 不更新"。
   * 这里改成对全量遍历一次，把每条的 booking_id + 关键状态字段拼进一个 cheap 字符串 hash，
   * 比对时只是字符串相等，性能仍是 O(N) 一次纯字符串拼接，万级也只在 ms 级。
   */
  var floorDayBookingDepKey = useMemo(function () {
    var d = floorDayBookingData;
    if (!Array.isArray(d) || d.length === 0) {
      return '__empty__';
    }
    /**
     * 用 djb2 的轻量变种逐字节积分，避免 join 长字符串占内存：
     *   h = ((h << 5) + h) ^ ch
     * 对 booking_id + status + 主要时间 + 支付态做指纹，其余字段视为不影响合并 / 画布。
     */
    var h = 5381;
    var accChar = function accChar(s) {
      for (var i = 0; i < s.length; i++) {
        h = (h << 5) + h ^ s.charCodeAt(i) | 0;
      }
      h = (h << 5) + h + 31 | 0;
    };
    for (var i = 0; i < d.length; i++) {
      var _ref, _ref2, _row$booking_id, _row$status, _ref3, _row$start_time, _ref4, _row$end_time, _ref5, _order$payment_status;
      var row = d[i];
      if (!row) {
        accChar('null');
        continue;
      }
      accChar(String((_ref = (_ref2 = (_row$booking_id = row.booking_id) !== null && _row$booking_id !== void 0 ? _row$booking_id : row.id) !== null && _ref2 !== void 0 ? _ref2 : row.bookingId) !== null && _ref !== void 0 ? _ref : ''));
      accChar(String((_row$status = row.status) !== null && _row$status !== void 0 ? _row$status : ''));
      accChar(String((_ref3 = (_row$start_time = row.start_time) !== null && _row$start_time !== void 0 ? _row$start_time : row.start_date) !== null && _ref3 !== void 0 ? _ref3 : ''));
      accChar(String((_ref4 = (_row$end_time = row.end_time) !== null && _row$end_time !== void 0 ? _row$end_time : row.end_date) !== null && _ref4 !== void 0 ? _ref4 : ''));
      var order = row.order;
      accChar(String((_ref5 = (_order$payment_status = order === null || order === void 0 ? void 0 : order.payment_status) !== null && _order$payment_status !== void 0 ? _order$payment_status : row.order_payment_status) !== null && _ref5 !== void 0 ? _ref5 : ''));
    }
    return "".concat(d.length, ":").concat(h);
  }, [floorDayBookingData]);
  var floorDayBookingDataRef = useRef(floorDayBookingData);
  floorDayBookingDataRef.current = floorDayBookingData;

  // --- 游标时刻预约列表（与 floorDayBooking 列表格式一致，供合并行） ---

  useEffect(function () {
    var _salesModule;
    var pisellosNow = pisellosRef.current;
    if (!isInternalListData) {
      setSalesResourceBookings(function (p) {
        return p == null ? p : null;
      });
      return;
    }
    if (!(pisellosNow !== null && pisellosNow !== void 0 && pisellosNow.getModule)) {
      setSalesResourceBookings(function (p) {
        return p == null ? p : null;
      });
      return;
    }
    if (!(debouncedSchedule !== null && debouncedSchedule !== void 0 && debouncedSchedule.at) || !dayjs(debouncedSchedule.at).isValid()) {
      return;
    }
    if (resourceBoardLoading || floorDayBookingLoading) {
      return;
    }
    var list = floorDayBookingDataRef.current;
    if (!Array.isArray(list)) {
      return;
    }
    var retryGateKey = "".concat(debouncedAtMs !== null && debouncedAtMs !== void 0 ? debouncedAtMs : 'na', "|").concat(floorDayBookingDepKey, "|v").concat(floorDayBookingDataVersion, "|").concat(hasPisellosGetModule ? 1 : 0, "|fw").concat(followWallClock ? 1 : 0);
    if (retryGateKey !== resourceListRetryGateRef.current) {
      resourceListRetryGateRef.current = retryGateKey;
      resourceListHostSkipRef.current = false;
    }
    if (resourceListHostSkipRef.current) {
      return;
    }
    var salesModule;
    try {
      salesModule = pisellosNow.getModule('sales');
    } catch (_unused) {
      setSalesResourceBookings(function (p) {
        return p == null ? p : null;
      });
      return;
    }
    var fn = (_salesModule = salesModule) === null || _salesModule === void 0 ? void 0 : _salesModule.getResourceBookingList;
    if (typeof fn !== 'function') {
      setSalesResourceBookings(function (p) {
        return p == null ? p : null;
      });
      return;
    }
    var reqId = ++salesBookingRequestRef.current;
    /**
     * 不再在请求开始时 `setSalesResourceBookings(null)`，避免「画布闪空 → 等宿主返回 → 再切回」的中间态闪烁。
     * stale-while-revalidate：保留旧值给画布继续渲染，等新值到达后再 swap；
     * 出错时再回退到本地全量过滤（让 buildReservationMergedTableRows 用 floorDayBookingList）。
     */

    var resourceBookingListTimeFormat = 'YYYY-MM-DD HH:mm';
    var timeStr = dayjs(debouncedSchedule.at).format(resourceBookingListTimeFormat);
    var currentTimeStr = followWallClock ? timeStr : dayjs().format(resourceBookingListTimeFormat);
    var applyHostList = function applyHostList(raw) {
      if (salesBookingRequestRef.current !== reqId) return;
      var normalized = normalizeSalesResourceBookingListResult(raw);
      setSalesResourceBookings(normalized);
      resourceListHostSkipRef.current = false;
    };
    var revertToLocalFilter = function revertToLocalFilter() {
      if (salesBookingRequestRef.current !== reqId) return;
      setSalesResourceBookings(function (p) {
        return p == null ? p : null;
      });
    };
    try {
      var result = fn.call(salesModule, timeStr, list, currentTimeStr);
      if (result != null && typeof result.then === 'function') {
        result.then(applyHostList).catch(function (e) {
          resourceListHostSkipRef.current = true;
          if (process.env.NODE_ENV !== 'production') {
            console.warn('[PisellReservation] sales.getResourceBookingList rejected（非宿主或 sales 未就绪时将不再重试，直至日程或列表数据变化）', e);
          }
          revertToLocalFilter();
        });
      } else {
        applyHostList(result);
      }
    } catch (e) {
      resourceListHostSkipRef.current = true;
      if (process.env.NODE_ENV !== 'production') {
        console.warn('[PisellReservation] sales.getResourceBookingList error', e);
      }
      revertToLocalFilter();
    }
  }, [isInternalListData, hasPisellosGetModule, resourceBoardLoading, floorDayBookingLoading, floorDayBookingDepKey,
  /**
   * 兜底信号：哪怕 cheap hash 没变，只要有 WS 推送 mutate 就重跑 host call。
   * 配合 `resourceListRetryGateRef` 保证非宿主场景不会重复打接口。
   */
  floorDayBookingDataVersion, debouncedAtMs, followWallClock, pisellosRef]);
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    salesTimelineHighlights = _useState4[0],
    setSalesTimelineHighlights = _useState4[1];
  var timelineHighlightsReqRef = useRef(0);
  var timelineHighlightsMissingLoggedRef = useRef(false);
  var scheduleDayMs = dayjs(scheduleDate).startOf('day').valueOf();
  useEffect(function () {
    if (!isInternalListData) {
      setSalesTimelineHighlights(null);
    }
  }, [isInternalListData]);

  // --- 时间轴密度：与顶栏 TimeNavigator 营业区间起止字符串一致 ---

  useEffect(function () {
    var _salesModule2;
    if (!isInternalListData) return;
    var pisellosNow = pisellosRef.current;
    if (!(pisellosNow !== null && pisellosNow !== void 0 && pisellosNow.getModule)) return;
    if (resourceBoardLoading || floorDayBookingLoading) return;
    var bookingList = floorDayBookingDataRef.current;
    if (!Array.isArray(bookingList)) return;
    var salesModule;
    try {
      salesModule = pisellosNow.getModule('sales');
    } catch (_unused2) {
      return;
    }
    var highlightsFn = (_salesModule2 = salesModule) === null || _salesModule2 === void 0 ? void 0 : _salesModule2.getTimelineHighlights;
    if (typeof highlightsFn !== 'function') {
      setSalesTimelineHighlights(null);
      if (!timelineHighlightsMissingLoggedRef.current) {
        timelineHighlightsMissingLoggedRef.current = true;
        console.warn('[PisellReservation] sales.getTimelineHighlights 未注册或非函数；时间轴密度退回本地计算');
      }
      return;
    }
    var reqId = ++timelineHighlightsReqRef.current;
    var _reservationTimelineR = reservationTimelineRangeStrings(scheduleDate, timelineRange, operatingDayBoundary, dayjs()),
      startStr = _reservationTimelineR.startStr,
      endStr = _reservationTimelineR.endStr;
    var applyHighlights = function applyHighlights(raw) {
      if (timelineHighlightsReqRef.current !== reqId) return;
      var normalized = normalizeSalesTimelineHighlightsRaw(raw);
      setSalesTimelineHighlights(normalized);
    };
    try {
      var out = highlightsFn.call(salesModule, bookingList, startStr, endStr);
      if (out != null && typeof out.then === 'function') {
        out.then(applyHighlights).catch(function (e) {
          if (process.env.NODE_ENV !== 'production') {
            console.warn('[PisellReservation] sales.getTimelineHighlights Promise 失败', e);
          }
        });
      } else {
        applyHighlights(out);
      }
    } catch (e) {
      if (process.env.NODE_ENV !== 'production') {
        console.warn('[PisellReservation] sales.getTimelineHighlights 同步调用异常', e);
      }
    }
  }, [isInternalListData, hasPisellosGetModule, resourceBoardLoading, floorDayBookingLoading, floorDayBookingDepKey, scheduleDayMs, debouncedAtMs, timelineRange.start, timelineRange.end, pisellosRef, operatingDayBoundary]);
  return {
    salesResourceBookings: salesResourceBookings,
    salesTimelineHighlights: salesTimelineHighlights
  };
}