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";
import { RESERVATION_TIMELINE_BUSINESS_RANGE } from "../reservationConstants";
/**
 * 内置列表且资源台 + floorDayBooking 均就绪后，向宿主 sales 拉两套数据：
 * - `getResourceBookingList`：游标时刻下的预约子集，参与合并进平面图 dataSources；
 * - `getTimelineHighlights`：时间轴密度折线（无则退回 PisellReservation 内本地计算）。
 */
export function useReservationSalesHostData(options) {
  var _timeNavigatorPropsPr2, _timeNavigatorPropsPr3;
  var isInternalListData = options.isInternalListData,
    pisellosRef = options.pisellosRef,
    hasPisellosGetModule = options.hasPisellosGetModule,
    debouncedSchedule = options.debouncedSchedule,
    resourceBoardLoading = options.resourceBoardLoading,
    floorDayBookingLoading = options.floorDayBookingLoading,
    floorDayBookingData = options.floorDayBookingData,
    scheduleDate = options.scheduleDate,
    timeNavigatorPropsProp = options.timeNavigatorPropsProp;
  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 常给新的 `[]`，会触发死循环。
   */
  var floorDayBookingDepKey = useMemo(function () {
    var d = floorDayBookingData;
    if (!Array.isArray(d) || d.length === 0) {
      return '__empty__';
    }
    var head = d.slice(0, 24);
    var parts = head.map(function (row) {
      var _ref, _ref2, _r$booking_id;
      var r = row;
      return String((_ref = (_ref2 = (_r$booking_id = r === null || r === void 0 ? void 0 : r.booking_id) !== null && _r$booking_id !== void 0 ? _r$booking_id : r === null || r === void 0 ? void 0 : r.id) !== null && _ref2 !== void 0 ? _ref2 : r === null || r === void 0 ? void 0 : r.bookingId) !== null && _ref !== void 0 ? _ref : '');
    });
    return "".concat(d.length, ":").concat(parts.join('|'));
  }, [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, "|").concat(hasPisellosGetModule ? 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);
    var resourceBookingListTimeFormat = 'YYYY-MM-DD HH:mm';
    var timeStr = dayjs(debouncedSchedule.at).format(resourceBookingListTimeFormat);
    var currentTimeStr = 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(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, debouncedAtMs, 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, _timeNavigatorPropsPr;
    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 timelineRange = (_timeNavigatorPropsPr = timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 ? void 0 : timeNavigatorPropsProp.range) !== null && _timeNavigatorPropsPr !== void 0 ? _timeNavigatorPropsPr : RESERVATION_TIMELINE_BUSINESS_RANGE;
    var _reservationTimelineR = reservationTimelineRangeStrings(scheduleDate, timelineRange),
      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, timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 || (_timeNavigatorPropsPr2 = timeNavigatorPropsProp.range) === null || _timeNavigatorPropsPr2 === void 0 ? void 0 : _timeNavigatorPropsPr2.start, timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 || (_timeNavigatorPropsPr3 = timeNavigatorPropsProp.range) === null || _timeNavigatorPropsPr3 === void 0 ? void 0 : _timeNavigatorPropsPr3.end, pisellosRef]);
  return {
    salesResourceBookings: salesResourceBookings,
    salesTimelineHighlights: salesTimelineHighlights
  };
}