var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/pisellRecordBoard/PisellRecordBoard.tsx
var PisellRecordBoard_exports = {};
__export(PisellRecordBoard_exports, {
  default: () => PisellRecordBoard_default
});
module.exports = __toCommonJS(PisellRecordBoard_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_RecordBoardProvider = require("./context/RecordBoardProvider");
var import_recordBoardColumns = require("./utils/recordBoardColumns");
var defaultPagination = { pageNumber: 1, pageSize: 50 };
function readBodyViewFromStorage(key, fallback) {
  if (typeof window === "undefined" || !key) return fallback;
  try {
    const raw = localStorage.getItem(key);
    if (raw === "grid" || raw === "floorMap" || raw === "calendar" || raw === "resourceWall")
      return raw;
  } catch {
  }
  return fallback;
}
function mergeChildComponentProps(props) {
  const hasAny = props.grid != null || props.toolBar != null || props.search != null || props.paginationConfig != null || props.batchActionBar != null || props.cardList != null;
  if (!hasAny) return void 0;
  return {
    ...props.grid != null && { grid: props.grid },
    ...props.toolBar != null && { toolBar: props.toolBar },
    ...props.search != null && { search: props.search },
    ...props.paginationConfig != null && {
      pagination: props.paginationConfig
    },
    ...props.batchActionBar != null && {
      batchActionBar: props.batchActionBar
    },
    ...props.cardList != null && { cardList: props.cardList }
  };
}
function getDefaultRecordBoardContext(layoutType, selection, rowKey) {
  return {
    data: [],
    loading: false,
    total: 0,
    pagination: defaultPagination,
    onPageChange: () => {
    },
    searchParams: {},
    onSearch: () => {
    },
    onReset: () => {
    },
    layoutType,
    selectedKeys: selection.selectedKeys,
    selectedRows: selection.selectedRows,
    onSelectionChange: selection.onSelectionChange,
    rowKey,
    childComponentProps: void 0,
    scrollAreaHeight: null,
    setScrollAreaHeight: void 0,
    filterResetKey: void 0,
    setFilterResetKey: void 0,
    bodyView: "grid",
    setBodyView: () => {
    },
    floorMapProps: void 0,
    floorMapLayoutContext: void 0,
    defaultBodyView: void 0,
    bodyViewSwitchable: true,
    floorMapLayoutRef: void 0,
    floorMapFooter: void 0,
    calendarProps: void 0,
    resourceWallProps: void 0,
    dataSources: void 0,
    gridDataSourceKey: void 0,
    paginationRender: void 0
  };
}
var PisellRecordBoard = (props) => {
  var _a;
  const {
    children,
    layoutType = "grid",
    rowKey: rowKeyProp,
    data: dataProp,
    dataSources: dataSourcesProp,
    gridDataSourceKey: gridDataSourceKeyProp,
    loading: loadingProp,
    total: totalProp,
    pagination: paginationProp,
    onPageChange: onPageChangeProp,
    searchParams: searchParamsProp,
    onSearch: onSearchProp,
    onReset: onResetProp,
    floorMap: floorMapProp,
    calendar: calendarProp,
    resourceWall: resourceWallProp,
    floorMapLayoutContext: floorMapLayoutContextProp,
    defaultBodyView,
    bodyViewStorageKey,
    bodyViewSwitchable = true,
    lockedBodyView: lockedBodyViewProp,
    floorMapLayoutRef,
    floorMapFooter,
    layoutVariant = "default",
    className: classNameProp,
    style: styleProp,
    ...rest
  } = props;
  const effectiveLockedBodyView = bodyViewSwitchable === false ? lockedBodyViewProp ?? "floorMap" : void 0;
  const fillHeight = true;
  const columnVisibilityStorageKey = props.columnVisibilityStorageKey ?? props.__id;
  const mergedChildComponentProps = (0, import_react.useMemo)(
    () => mergeChildComponentProps(props),
    [
      props.grid,
      props.toolBar,
      props.search,
      props.paginationConfig,
      props.batchActionBar,
      props.cardList
    ]
  );
  const [internalSelectedKeys, setInternalSelectedKeys] = (0, import_react.useState)(
    []
  );
  const [internalSelectedRows, setInternalSelectedRows] = (0, import_react.useState)([]);
  const [scrollAreaHeight, setScrollAreaHeight] = (0, import_react.useState)(null);
  const [filterResetKey, setFilterResetKey] = (0, import_react.useState)(0);
  const [bodyView, setBodyViewState] = (0, import_react.useState)(() => {
    if (effectiveLockedBodyView != null) {
      return effectiveLockedBodyView;
    }
    const fallback = defaultBodyView === "floorMap" ? "floorMap" : defaultBodyView === "calendar" ? "calendar" : defaultBodyView === "resourceWall" ? "resourceWall" : "grid";
    return readBodyViewFromStorage(bodyViewStorageKey, fallback);
  });
  const setBodyView = (0, import_react.useCallback)(
    (v) => {
      if (bodyViewSwitchable === false && effectiveLockedBodyView != null && v !== effectiveLockedBodyView) {
        return;
      }
      setBodyViewState(v);
      if (typeof window !== "undefined" && bodyViewStorageKey) {
        try {
          localStorage.setItem(bodyViewStorageKey, v);
        } catch {
        }
      }
    },
    [
      bodyViewStorageKey,
      bodyViewSwitchable,
      effectiveLockedBodyView
    ]
  );
  (0, import_react.useEffect)(() => {
    if (bodyViewSwitchable === false && effectiveLockedBodyView != null && bodyView !== effectiveLockedBodyView) {
      setBodyViewState(effectiveLockedBodyView);
    }
  }, [
    bodyViewSwitchable,
    effectiveLockedBodyView,
    bodyView
  ]);
  const [internalColumnVisibility, setInternalColumnVisibility] = (0, import_react.useState)(() => {
    var _a2, _b;
    const fromConfig = ((_a2 = props.grid) == null ? void 0 : _a2.defaultHiddenColumnKeys) ?? [];
    const fromColumns = (((_b = props.grid) == null ? void 0 : _b.columns) ?? []).filter(
      (col) => col.hidden === true
    ).map((col) => (0, import_recordBoardColumns.getRecordBoardColumnKey)(col)).filter(Boolean);
    const allHiddenKeys = Array.from(/* @__PURE__ */ new Set([...fromConfig, ...fromColumns]));
    const defaultVis = {};
    allHiddenKeys.forEach((k) => {
      defaultVis[k] = false;
    });
    if (typeof columnVisibilityStorageKey === "string" && columnVisibilityStorageKey) {
      if (typeof import_utils.getRecordBoardColumnSettingFromLocal === "function") {
        const saved = (0, import_utils.getRecordBoardColumnSettingFromLocal)(columnVisibilityStorageKey);
        if ((saved == null ? void 0 : saved.columnVisibility) && Object.keys(saved.columnVisibility).length > 0) {
          return { ...defaultVis, ...saved.columnVisibility };
        }
      } else if (typeof import_utils.getColumnVisibilityFromLocal === "function") {
        const savedVis = (0, import_utils.getColumnVisibilityFromLocal)(columnVisibilityStorageKey);
        if (savedVis && Object.keys(savedVis).length > 0) {
          return { ...defaultVis, ...savedVis };
        }
      }
    }
    return defaultVis;
  });
  const [internalColumnOrder, setInternalColumnOrder] = (0, import_react.useState)(
    () => {
      if (typeof columnVisibilityStorageKey === "string" && columnVisibilityStorageKey && typeof import_utils.getRecordBoardColumnSettingFromLocal === "function") {
        const saved = (0, import_utils.getRecordBoardColumnSettingFromLocal)(columnVisibilityStorageKey);
        return (saved == null ? void 0 : saved.columnOrder) ?? null;
      }
      return null;
    }
  );
  (0, import_react.useEffect)(() => {
    if (typeof columnVisibilityStorageKey !== "string" || !columnVisibilityStorageKey)
      return;
    (0, import_utils.saveColumnVisibilityToLocal)({
      componentId: columnVisibilityStorageKey,
      columnVisibility: internalColumnVisibility,
      columnOrder: internalColumnOrder ?? void 0
    });
  }, [columnVisibilityStorageKey, internalColumnVisibility, internalColumnOrder]);
  const onSelectionChangeInternal = (0, import_react.useCallback)(
    (keys, rows) => {
      setInternalSelectedKeys(keys);
      setInternalSelectedRows(rows);
    },
    []
  );
  const onColumnVisibilityChangeInternal = (0, import_react.useCallback)(
    (visibility) => {
      setInternalColumnVisibility((prev) => ({ ...prev, ...visibility }));
    },
    []
  );
  const onColumnOrderChangeInternal = (0, import_react.useCallback)((columnKeys) => {
    setInternalColumnOrder(columnKeys);
  }, []);
  const contextValue = (0, import_react.useMemo)(() => {
    var _a2;
    const defaultCtx = getDefaultRecordBoardContext(
      layoutType,
      {
        selectedKeys: internalSelectedKeys,
        selectedRows: internalSelectedRows,
        onSelectionChange: onSelectionChangeInternal
      },
      rowKeyProp
    );
    const pagination = paginationProp !== void 0 ? paginationProp : defaultCtx.pagination;
    const gridInfiniteScroll = ((_a2 = props.grid) == null ? void 0 : _a2.infiniteScroll) === true;
    let data;
    let total;
    if (dataProp !== void 0) {
      data = dataProp;
      total = totalProp !== void 0 ? totalProp : defaultCtx.total;
    } else if (dataSourcesProp != null && gridDataSourceKeyProp != null && gridDataSourceKeyProp !== "") {
      const raw = dataSourcesProp[gridDataSourceKeyProp] ?? [];
      total = totalProp !== void 0 ? totalProp : raw.length;
      const { pageNumber, pageSize } = pagination;
      const safeSize = Math.max(1, pageSize);
      if (gridInfiniteScroll) {
        const end = Math.min(raw.length, pageNumber * safeSize);
        data = raw.slice(0, end);
      } else {
        const start = Math.max(0, (pageNumber - 1) * safeSize);
        data = raw.slice(start, start + safeSize);
      }
    } else {
      data = defaultCtx.data;
      total = totalProp !== void 0 ? totalProp : defaultCtx.total;
    }
    const loading = loadingProp !== void 0 ? loadingProp : defaultCtx.loading;
    const onPageChange = onPageChangeProp ?? defaultCtx.onPageChange;
    const searchParams = searchParamsProp !== void 0 ? searchParamsProp : defaultCtx.searchParams;
    const onSearch = onSearchProp ?? defaultCtx.onSearch;
    const onReset = onResetProp ?? defaultCtx.onReset;
    const rowKey = rowKeyProp ?? defaultCtx.rowKey;
    const gridSelection = props.grid;
    const hasControlledSelection = (gridSelection == null ? void 0 : gridSelection.selectedKeys) != null && Array.isArray(gridSelection.selectedKeys) && typeof gridSelection.onSelectionChange === "function";
    const selectedKeys = hasControlledSelection ? gridSelection.selectedKeys : internalSelectedKeys;
    const selectedRows = hasControlledSelection ? gridSelection.selectedRows ?? [] : internalSelectedRows;
    const onSelectionChange = hasControlledSelection ? gridSelection.onSelectionChange : onSelectionChangeInternal;
    return {
      ...defaultCtx,
      layoutType,
      layoutVariant,
      rowKey,
      dataSources: dataSourcesProp,
      gridDataSourceKey: gridDataSourceKeyProp,
      data,
      loading,
      total,
      pagination,
      onPageChange,
      searchParams,
      onSearch,
      onReset,
      selectedKeys,
      selectedRows,
      onSelectionChange,
      columnVisibility: internalColumnVisibility,
      onColumnVisibilityChange: onColumnVisibilityChangeInternal,
      columnOrder: internalColumnOrder,
      onColumnOrderChange: onColumnOrderChangeInternal,
      childComponentProps: mergedChildComponentProps ?? defaultCtx.childComponentProps,
      fillHeight,
      scrollAreaHeight,
      setScrollAreaHeight,
      filterResetKey,
      setFilterResetKey,
      bodyView,
      setBodyView,
      floorMapProps: floorMapProp,
      floorMapLayoutContext: floorMapLayoutContextProp,
      defaultBodyView,
      bodyViewSwitchable,
      floorMapLayoutRef,
      floorMapFooter,
      calendarProps: calendarProp,
      resourceWallProps: resourceWallProp,
      /**
       * 业务方传入的自定义分页渲染：注入 ctx 后，shellFrame 内置的
       * `<RecordBoardPagination />` 会优先使用它（详见 RecordBoardPagination 实现）。
       */
      paginationRender: props.paginationRender,
      gridInfiniteScroll
    };
  }, [
    layoutType,
    layoutVariant,
    rowKeyProp,
    dataProp,
    dataSourcesProp,
    gridDataSourceKeyProp,
    loadingProp,
    totalProp,
    paginationProp,
    onPageChangeProp,
    searchParamsProp,
    onSearchProp,
    onResetProp,
    mergedChildComponentProps,
    internalSelectedKeys,
    internalSelectedRows,
    onSelectionChangeInternal,
    internalColumnVisibility,
    onColumnVisibilityChangeInternal,
    internalColumnOrder,
    onColumnOrderChangeInternal,
    fillHeight,
    scrollAreaHeight,
    filterResetKey,
    floorMapProp,
    floorMapLayoutContextProp,
    defaultBodyView,
    bodyViewSwitchable,
    floorMapLayoutRef,
    floorMapFooter,
    calendarProp,
    resourceWallProp,
    bodyView,
    setBodyView,
    props.paginationRender,
    (_a = props.grid) == null ? void 0 : _a.infiniteScroll
  ]);
  const content = /* @__PURE__ */ import_react.default.createElement(import_RecordBoardProvider.RecordBoardProvider, { value: contextValue }, children);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: classNameProp ? `pisell-record-board-root ${classNameProp}` : "pisell-record-board-root",
      style: {
        height: "100%",
        display: "flex",
        flexDirection: "column",
        minHeight: 0,
        ...styleProp
      }
    },
    content
  );
};
var PisellRecordBoard_default = PisellRecordBoard;
