var _excluded = ["render", "columns", "rowKey", "rowSelection"],
  _excluded2 = ["autoCalc"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useMemo, useRef, useState, useEffect } from 'react';
import { Table } from 'antd';
import { useRecordBoardContext } from "../../hooks/useRecordBoardContext";
import { processColumnsForGrid, getRecordBoardColumnKey, computeUniformColumnSummary } from "../../utils/recordBoardColumns";
import { getText } from "../../../../locales";
import "./Grid.less";
function getRowKey(record, rowKey) {
  var _ref, _record$id;
  if (typeof rowKey === 'function') {
    return rowKey(record);
  }
  if (typeof rowKey === 'string' && record != null && rowKey in record) {
    return record[rowKey];
  }
  return (_ref = (_record$id = record === null || record === void 0 ? void 0 : record.id) !== null && _record$id !== void 0 ? _record$id : record === null || record === void 0 ? void 0 : record.key) !== null && _ref !== void 0 ? _ref : record;
}

/**
 * Grid 布局下的数据视图：使用 antd Table，从 context 取 data / loading / 多选态。
 */
/** Context 中与 Table 无关的 key，透传 Table 时排除，避免覆盖或无效传递（含 grid 合并进的 columns/scroll 等） */
var CONTEXT_ONLY_KEYS = ['data', 'loading', 'total', 'pagination', 'onPageChange', 'searchParams', 'onSearch', 'onReset', 'layoutType', 'selectedKeys', 'selectedRows', 'onSelectionChange', 'rowKey', 'childComponentProps', 'columnVisibility', 'onColumnVisibilityChange', 'columns', 'scroll', 'size', 'defaultHiddenColumnKeys', 'scrollAreaHeight', 'setScrollAreaHeight', 'collapseUniformColumns', 'columnOrder', 'onColumnOrderChange'];
var RecordBoardGridView = function RecordBoardGridView(props) {
  var _ref2, _ctx$data2, _ctx$data3;
  var ctx = useRecordBoardContext({
    displayName: 'grid'
  });
  var render = props.render,
    columnsProp = props.columns,
    rowKeyProp = props.rowKey,
    rowSelectionProp = props.rowSelection,
    rest = _objectWithoutProperties(props, _excluded);

  // columns 优先用 props，其次用 childComponentProps.grid 合并进 ctx 的 columns
  var rawColumns = (_ref2 = columnsProp !== null && columnsProp !== void 0 ? columnsProp : ctx.columns) !== null && _ref2 !== void 0 ? _ref2 : [];
  var columnVisibility = ctx.columnVisibility;
  var columnOrder = ctx.columnOrder;
  var collapseUniformColumns = ctx.collapseUniformColumns !== false;

  /** 同值列总结区高度，用于 autoCalc 时正确计算 scroll.y */
  var summaryRef = useRef(null);
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    uniformSummaryHeight = _useState2[0],
    setUniformSummaryHeight = _useState2[1];
  var _useMemo = useMemo(function () {
      var _ctx$data;
      var list = rawColumns;
      if (Array.isArray(columnOrder) && columnOrder.length > 0) {
        var keyToCol = new Map(list.map(function (c) {
          return [getRecordBoardColumnKey(c), c];
        }));
        var ordered = [];
        var _iterator = _createForOfIteratorHelper(columnOrder),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var key = _step.value;
            var col = keyToCol.get(key);
            if (col) ordered.push(col);
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        list.forEach(function (col) {
          var key = getRecordBoardColumnKey(col);
          if (!columnOrder.includes(key)) ordered.push(col);
        });
        list = ordered;
      }
      var visibleByUser = columnVisibility == null ? list : list.filter(function (col) {
        return columnVisibility[getRecordBoardColumnKey(col)] !== false;
      });
      var data = (_ctx$data = ctx.data) !== null && _ctx$data !== void 0 ? _ctx$data : [];
      var shouldCollapseUniform = collapseUniformColumns && data.length > 5;
      if (!shouldCollapseUniform) {
        return {
          columns: processColumnsForGrid(visibleByUser),
          uniformSummaryItems: [],
          processedColumnsForSummary: undefined
        };
      }
      var processedAllVisible = processColumnsForGrid(visibleByUser);
      var _computeUniformColumn = computeUniformColumnSummary(data, visibleByUser),
        uniformHiddenColumnKeys = _computeUniformColumn.uniformHiddenColumnKeys,
        items = _computeUniformColumn.summaryItems;
      var columnsForTable = processedAllVisible.filter(function (col) {
        return !uniformHiddenColumnKeys.includes(getRecordBoardColumnKey(col));
      });
      return {
        columns: columnsForTable,
        uniformSummaryItems: items,
        processedColumnsForSummary: items.length > 0 ? processedAllVisible : undefined
      };
    }, [rawColumns, columnVisibility, columnOrder, collapseUniformColumns, ctx.data]),
    columns = _useMemo.columns,
    summaryItems = _useMemo.uniformSummaryItems,
    processedColumnsForSummary = _useMemo.processedColumnsForSummary;
  var tableRowKey = useMemo(function () {
    var _ref3, _ctx$rowKey;
    var key = (_ref3 = (_ctx$rowKey = ctx.rowKey) !== null && _ctx$rowKey !== void 0 ? _ctx$rowKey : rowKeyProp) !== null && _ref3 !== void 0 ? _ref3 : 'id';
    return typeof key === 'function' ? key : function (record) {
      return getRowKey(record, typeof key === 'string' ? key : String(key));
    };
  }, [ctx.rowKey, rowKeyProp]);
  var rowSelectionConfig = rowSelectionProp !== null && rowSelectionProp !== void 0 ? rowSelectionProp : ctx.rowSelection;
  var rowSelection = useMemo(function () {
    if (rowSelectionConfig === false) return undefined;
    var base = _typeof(rowSelectionConfig) === 'object' ? rowSelectionConfig : {};
    return _objectSpread(_objectSpread({}, base), {}, {
      selectedRowKeys: ctx.selectedKeys,
      onChange: function onChange(selectedRowKeys, selectedRows) {
        var _onChange, _ref4;
        ctx.onSelectionChange(selectedRowKeys, selectedRows);
        (_onChange = (_ref4 = base).onChange) === null || _onChange === void 0 || _onChange.call(_ref4, selectedRowKeys, selectedRows);
      }
    });
  }, [ctx.selectedKeys, ctx.onSelectionChange, rowSelectionConfig]);

  /** 测量同值列总结区高度，供 autoCalc 时 scroll.y 减去该高度 */
  useEffect(function () {
    if (summaryItems.length === 0) {
      setUniformSummaryHeight(0);
      return;
    }
    var el = summaryRef.current;
    if (!el) return;
    var ro = new ResizeObserver(function (entries) {
      var entry = entries[0];
      if (entry) setUniformSummaryHeight(entry.contentRect.height);
    });
    ro.observe(el);
    return function () {
      ro.disconnect();
      setUniformSummaryHeight(0);
    };
  }, [summaryItems.length]);

  // grid 透传的 Table props（onRow、onHeaderRow、expandable、rowClassName、summary 等）从 ctx 取出并传给 Table
  var gridTableProps = useMemo(function () {
    var picked = {};
    Object.keys(ctx).forEach(function (k) {
      if (CONTEXT_ONLY_KEYS.includes(k)) return;
      picked[k] = ctx[k];
    });
    return picked;
  }, [ctx]);
  if (typeof render === 'function') {
    return /*#__PURE__*/React.createElement(React.Fragment, null, render(_objectSpread(_objectSpread({}, ctx), rest)));
  }
  var dataSource = (_ctx$data2 = ctx.data) !== null && _ctx$data2 !== void 0 ? _ctx$data2 : [];
  var isEmpty = !Array.isArray(dataSource) || dataSource.length === 0;
  var sumColumnWidths = useMemo(function () {
    return columns.reduce(function (sum, col) {
      var _col$width;
      return sum + ((_col$width = col.width) !== null && _col$width !== void 0 ? _col$width : 250);
    }, 0) || 2000;
  }, [columns]);

  // 与 materials Table useGenScroll 对齐：autoCalc 时根据 scrollAreaHeight 计算 scroll.y；无数据且 scroll.x 非数字时用列宽之和避免表头被压窄换行
  var tableScroll = useMemo(function () {
    var _rest$scroll;
    var scroll = (_rest$scroll = rest.scroll) !== null && _rest$scroll !== void 0 ? _rest$scroll : ctx.scroll;
    var scrollX = isEmpty && scroll && typeof scroll.x !== 'number' ? sumColumnWidths : scroll === null || scroll === void 0 ? void 0 : scroll.x;
    if (scroll !== null && scroll !== void 0 && scroll.autoCalc && typeof ctx.scrollAreaHeight === 'number') {
      var wrapHeight = ctx.scrollAreaHeight;
      // 40：表头等固定占高；uniformSummaryHeight：同值列总结区动态高度，无总结时为 0, 24是 uniformSummary padding
      var reservedHeight = 40 + uniformSummaryHeight + 24;
      return {
        x: scrollX !== null && scrollX !== void 0 ? scrollX : sumColumnWidths,
        y: Math.max(wrapHeight - reservedHeight, 100),
        scrollToFirstRowOnChange: scroll.scrollToFirstRowOnChange
      };
    }
    if (scroll && _typeof(scroll) === 'object') {
      var _ref5 = scroll,
        _a = _ref5.autoCalc,
        restScroll = _objectWithoutProperties(_ref5, _excluded2);
      var resolved = Object.keys(restScroll).length ? restScroll : undefined;
      if (resolved) {
        var _ref6;
        return _objectSpread(_objectSpread({}, resolved), {}, {
          x: (_ref6 = scrollX !== null && scrollX !== void 0 ? scrollX : resolved.x) !== null && _ref6 !== void 0 ? _ref6 : sumColumnWidths
        });
      }
      return resolved;
    }
    return scroll;
  }, [rest.scroll, ctx.scroll, ctx.scrollAreaHeight, ctx.pagination, columns, sumColumnWidths, isEmpty, uniformSummaryHeight]);
  return /*#__PURE__*/React.createElement("div", {
    "data-layout-slot": "grid",
    className: "pisell-lowcode-record-board-grid"
  }, summaryItems.length > 0 && /*#__PURE__*/React.createElement("div", {
    ref: summaryRef,
    className: "pisell-record-board-uniform-summary"
  }, summaryItems.map(function (item) {
    var _item$record, _item$displayValue;
    var processedCol = processedColumnsForSummary === null || processedColumnsForSummary === void 0 ? void 0 : processedColumnsForSummary.find(function (c) {
      return getRecordBoardColumnKey(c) === item.columnKey;
    });
    var useRender = typeof (processedCol === null || processedCol === void 0 ? void 0 : processedCol.render) === 'function';
    // render 只接收表格单元格相同的 (value, record)：value 固定用 cellValue（dataIndex 取值），绝不传 uniformCompare 的返回值
    var content = useRender ? processedCol.render(item.cellValue, (_item$record = item.record) !== null && _item$record !== void 0 ? _item$record : {}, 0) : item.type === 'empty' ? getText('record-board-uniform-summary-empty') : (_item$displayValue = item.displayValue) !== null && _item$displayValue !== void 0 ? _item$displayValue : getText('record-board-uniform-summary-same');
    return /*#__PURE__*/React.createElement("div", {
      key: item.columnKey,
      className: "pisell-record-board-uniform-summary-item"
    }, /*#__PURE__*/React.createElement("span", {
      className: "pisell-record-board-uniform-summary-label"
    }, item.title), /*#__PURE__*/React.createElement("span", {
      className: "pisell-record-board-uniform-summary-value"
    }, content));
  })), /*#__PURE__*/React.createElement(Table, _extends({}, rest, gridTableProps, {
    scroll: tableScroll,
    rowKey: tableRowKey,
    dataSource: (_ctx$data3 = ctx.data) !== null && _ctx$data3 !== void 0 ? _ctx$data3 : [],
    loading: ctx.loading,
    columns: columns,
    rowSelection: rowSelection,
    pagination: false
  })));
};
export default RecordBoardGridView;