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 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 _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 React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { filterBookingsByResourceIds } from "../data/bookingToReservationTables";
import { applyHudDrawerLocalListQuery, cloneHudDrawerSearchParams, mergeHudDrawerSearchParams, stripHudDrawerBookingDateQuickFilter, stripHudDrawerBucketFilterDefaults } from "../data/hudDrawerLocalListQuery";
import { ReservationFloorMapHud, reservationFloorMapHudSeatStatsTotal } from "../floorMap/ReservationFloorMapHud";
import { buildReservationHudDrawerToolbarConfig } from "../mobileTable/buildReservationMobileTableConfig";
import { ReservationHudMapItemsSync } from "../floorMap/ReservationHudMapItemsSync";
import { filterReservationRowsBoundOnCanvas } from "../floorMap/reservationHudTableRows";
import { buildResourceRootBuckets } from "../floorMap/reservationHudResourceRootBuckets";
import { ReservationHudDrawerQuickFilters } from "../components/ReservationHudDrawerQuickFilters";
import { PISELL_RESERVATION_HUD_LOCAL_PAGE_SIZE } from "../reservationConstants";
import { getReservationRenderItemByKind } from "../floorMap/reservationCards";

/** floorDayBooking 请求 hook 返回值（仅抽屉打开快照用 searchParams） */

/**
 * 平面图 HUD 抽屉：视口 items 同步、本地列表分页与筛参、展开/收起、ESC、内嵌 RecordBoard toolbar 覆写。
 */
export function useReservationHudDrawer(_ref) {
  var floorMapHudTableDrawer = _ref.floorMapHudTableDrawer,
    dataSources = _ref.dataSources,
    gridDataSourceKey = _ref.gridDataSourceKey,
    isInternalListData = _ref.isInternalListData,
    floorDayBookingData = _ref.floorDayBookingData,
    searchParamsProp = _ref.searchParamsProp,
    dataProp = _ref.dataProp,
    loadingProp = _ref.loadingProp,
    bookingChildProps = _ref.bookingChildProps,
    resourceBoardData = _ref.resourceBoardData,
    phoneLayout = _ref.phoneLayout,
    _ref$hideViewportHudS = _ref.hideViewportHudStats,
    hideViewportHudStats = _ref$hideViewportHudS === void 0 ? false : _ref$hideViewportHudS;
  var hudItemsRef = useRef([]);
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    hudMapItems = _useState2[0],
    setHudMapItems = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    hudDrawerOpen = _useState4[0],
    setHudDrawerOpen = _useState4[1];
  var hudDrawerRef = useRef(null);
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    hudDrawerResourceIds = _useState6[0],
    setHudDrawerResourceIds = _useState6[1];
  var _useState7 = useState({}),
    _useState8 = _slicedToArray(_useState7, 2),
    hudDrawerLocalSearchParams = _useState8[0],
    setHudDrawerLocalSearchParams = _useState8[1];
  var hudDrawerSearchParamsOpenSnapshotRef = useRef({});
  var _useState9 = useState({
      pageNumber: 1,
      pageSize: PISELL_RESERVATION_HUD_LOCAL_PAGE_SIZE
    }),
    _useState10 = _slicedToArray(_useState9, 2),
    hudDrawerListPagination = _useState10[0],
    setHudDrawerListPagination = _useState10[1];
  var showVenueHudDock = useMemo(function () {
    return floorMapHudTableDrawer && (hudDrawerOpen || reservationFloorMapHudSeatStatsTotal(hudMapItems, dataSources) > 0);
  }, [floorMapHudTableDrawer, hudDrawerOpen, hudMapItems, dataSources]);
  var handleOpenHudTableDrawer = useCallback(function () {
    var boundTableRows = filterReservationRowsBoundOnCanvas(hudItemsRef.current, dataSources, gridDataSourceKey);
    var resourceIdSet = new Set(boundTableRows.map(function (r) {
      return String(r.id);
    }).filter(Boolean));
    var parentSnapshot = cloneHudDrawerSearchParams(isInternalListData ? floorDayBookingData.searchParams : searchParamsProp !== null && searchParamsProp !== void 0 ? searchParamsProp : {});
    stripHudDrawerBookingDateQuickFilter(parentSnapshot);
    stripHudDrawerBucketFilterDefaults(parentSnapshot);
    hudDrawerSearchParamsOpenSnapshotRef.current = parentSnapshot;
    setHudDrawerLocalSearchParams(parentSnapshot);
    setHudDrawerResourceIds(resourceIdSet);
    setHudDrawerListPagination({
      pageNumber: 1,
      pageSize: PISELL_RESERVATION_HUD_LOCAL_PAGE_SIZE
    });
    setHudDrawerOpen(true);
  }, [dataSources, gridDataSourceKey, isInternalListData, floorDayBookingData.searchParams, searchParamsProp]);
  var closeHudTableDrawer = useCallback(function () {
    setHudDrawerOpen(false);
    setHudDrawerResourceIds(null);
    setHudDrawerLocalSearchParams({});
    setHudDrawerListPagination({
      pageNumber: 1,
      pageSize: PISELL_RESERVATION_HUD_LOCAL_PAGE_SIZE
    });
  }, []);
  useEffect(function () {
    if (!floorMapHudTableDrawer || !hudDrawerOpen) return;
    var onKeyDown = function onKeyDown(e) {
      if (e.key === 'Escape') closeHudTableDrawer();
    };
    window.addEventListener('keydown', onKeyDown);
    return function () {
      return window.removeEventListener('keydown', onKeyDown);
    };
  }, [floorMapHudTableDrawer, hudDrawerOpen, closeHudTableDrawer]);
  var hudDrawerResourceRootBuckets = useMemo(function () {
    return buildResourceRootBuckets(resourceBoardData.data);
  }, [resourceBoardData.data]);
  var hudDrawerDisplayRows = useMemo(function () {
    if (!floorMapHudTableDrawer || !hudDrawerOpen || !hudDrawerResourceIds || hudDrawerResourceIds.size === 0) {
      return [];
    }
    var source = isInternalListData ? floorDayBookingData.data : dataProp !== null && dataProp !== void 0 ? dataProp : [];
    var baseRows = filterBookingsByResourceIds(source, hudDrawerResourceIds);
    return applyHudDrawerLocalListQuery(baseRows, hudDrawerLocalSearchParams);
  }, [floorMapHudTableDrawer, hudDrawerOpen, hudDrawerResourceIds, isInternalListData, floorDayBookingData.data, dataProp, hudDrawerLocalSearchParams]);
  var hudDrawerFilteredTotal = hudDrawerDisplayRows.length;
  var hudDrawerMaxPage = Math.max(1, Math.ceil(hudDrawerFilteredTotal / hudDrawerListPagination.pageSize) || 1);
  useEffect(function () {
    if (hudDrawerListPagination.pageNumber <= hudDrawerMaxPage) return;
    setHudDrawerListPagination(function (p) {
      return _objectSpread(_objectSpread({}, p), {}, {
        pageNumber: hudDrawerMaxPage
      });
    });
  }, [hudDrawerMaxPage, hudDrawerListPagination.pageNumber]);

  /** 与 RecordBoard `grid.infiniteScroll` 一致：按页数累积展示行（触底增加 pageNumber 后多展一段） */
  var hudDrawerPagedRows = useMemo(function () {
    var pageNumber = hudDrawerListPagination.pageNumber,
      pageSize = hudDrawerListPagination.pageSize;
    var safeSize = Math.max(1, pageSize);
    var end = Math.min(hudDrawerDisplayRows.length, pageNumber * safeSize);
    return hudDrawerDisplayRows.slice(0, end);
  }, [hudDrawerDisplayRows, hudDrawerListPagination]);
  var hudDrawerToolBar = useMemo(function () {
    var raw = bookingChildProps.toolBar;
    var base = raw != null && _typeof(raw) === 'object' && !Array.isArray(raw) ? raw : {};
    return buildReservationHudDrawerToolbarConfig({
      baseToolBar: base,
      searchGetContainer: function searchGetContainer() {
        var _hudDrawerRef$current;
        return (_hudDrawerRef$current = hudDrawerRef.current) !== null && _hudDrawerRef$current !== void 0 ? _hudDrawerRef$current : document.body;
      },
      quickFilterComponent: ReservationHudDrawerQuickFilters
    });
  }, [bookingChildProps.toolBar]);
  var hudDrawerLoading = isInternalListData ? floorDayBookingData.loading : loadingProp !== null && loadingProp !== void 0 ? loadingProp : false;
  var hudDrawerBookingPagination = useMemo(function () {
    return {
      pageNumber: hudDrawerListPagination.pageNumber,
      pageSize: hudDrawerListPagination.pageSize
    };
  }, [hudDrawerListPagination.pageNumber, hudDrawerListPagination.pageSize]);
  var hudDrawerOnSearch = useCallback(function (params) {
    setHudDrawerListPagination(function (p) {
      return _objectSpread(_objectSpread({}, p), {}, {
        pageNumber: 1
      });
    });
    setHudDrawerLocalSearchParams(function (prev) {
      return mergeHudDrawerSearchParams(prev, params);
    });
  }, []);
  var handleHudDrawerFormRecordIdsChange = useCallback(function (formRecordIds) {
    hudDrawerOnSearch({
      filter: {
        values: {
          form_record_ids: formRecordIds
        }
      }
    });
  }, [hudDrawerOnSearch]);
  var hudDrawerOnReset = useCallback(function () {
    setHudDrawerListPagination(function (p) {
      return _objectSpread(_objectSpread({}, p), {}, {
        pageNumber: 1
      });
    });
    setHudDrawerLocalSearchParams(cloneHudDrawerSearchParams(hudDrawerSearchParamsOpenSnapshotRef.current));
  }, []);
  var hudDrawerOnPageChange = useCallback(function (pageNumber, pageSize) {
    setHudDrawerListPagination({
      pageNumber: pageNumber,
      pageSize: pageSize
    });
  }, []);
  var renderItemByKind = useMemo(function () {
    return getReservationRenderItemByKind(dataSources);
  }, [dataSources]);
  var reservationFloorMapViewportOverlay = useCallback(function (args) {
    var items = args.items;
    hudItemsRef.current = items;
    if (floorMapHudTableDrawer) {
      return /*#__PURE__*/React.createElement(ReservationHudMapItemsSync, {
        items: items,
        setItems: setHudMapItems
      });
    }
    if (hideViewportHudStats) {
      return null;
    }
    return /*#__PURE__*/React.createElement(ReservationFloorMapHud, {
      items: items,
      dataSources: args.dataSources,
      interactive: false,
      phoneLayout: phoneLayout
    });
  }, [floorMapHudTableDrawer, phoneLayout, hideViewportHudStats]);
  return {
    hudItemsRef: hudItemsRef,
    hudMapItems: hudMapItems,
    setHudMapItems: setHudMapItems,
    hudDrawerRef: hudDrawerRef,
    hudDrawerOpen: hudDrawerOpen,
    showVenueHudDock: showVenueHudDock,
    handleOpenHudTableDrawer: handleOpenHudTableDrawer,
    closeHudTableDrawer: closeHudTableDrawer,
    hudDrawerResourceRootBuckets: hudDrawerResourceRootBuckets,
    hudDrawerPagedRows: hudDrawerPagedRows,
    hudDrawerFilteredTotal: hudDrawerFilteredTotal,
    hudDrawerLoading: hudDrawerLoading,
    hudDrawerBookingPagination: hudDrawerBookingPagination,
    hudDrawerOnSearch: hudDrawerOnSearch,
    hudDrawerOnReset: hudDrawerOnReset,
    hudDrawerOnPageChange: hudDrawerOnPageChange,
    hudDrawerToolBar: hudDrawerToolBar,
    hudDrawerLocalSearchParams: hudDrawerLocalSearchParams,
    handleHudDrawerFormRecordIdsChange: handleHudDrawerFormRecordIdsChange,
    reservationFloorMapViewportOverlay: reservationFloorMapViewportOverlay,
    renderItemByKind: renderItemByKind
  };
}