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 _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 _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 _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 _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 _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); }
import React, { useState, useEffect } from 'react';
import { PisellSingleLineText } from "../../pisellSingleLineText";
import { PisellLongText } from "../../pisellLongText";
import { PisellEmail } from "../../pisellEmail";
import { PisellPhone } from "../../pisellPhone";
import { PisellUrl } from "../../pisellUrl";
import { PisellNumber } from "../../pisellNumber";
import { PisellCurrency } from "../../pisellCurrency";
import { PisellPercent } from "../../pisellPercent";
import { PisellRating } from "../../pisellRating";
import { PisellSingleSelect } from "../../pisellSingleSelect";
import { PisellMultipleSelect } from "../../pisellMultipleSelect";
import { PisellDateTimeDisplay } from "../../pisellDateTimeDisplay";
import { getText } from "../../../locales";
var FIELD_TYPE_TO_READ_COMPONENT = {
  singleLineText: PisellSingleLineText,
  longText: PisellLongText,
  email: PisellEmail,
  phone: PisellPhone,
  url: PisellUrl,
  number: PisellNumber,
  currency: PisellCurrency,
  percent: PisellPercent,
  rating: PisellRating,
  singleSelect: PisellSingleSelect,
  multipleSelect: PisellMultipleSelect,
  dateTime: PisellDateTimeDisplay
};

/** 列 type 对应排序类型默认值（组件未导出 SortOptions 时使用） */
var FIELD_TYPE_TO_SORT_OPTIONS_DEFAULT = {
  singleLineText: {
    type: 'string'
  },
  longText: {
    type: 'string'
  },
  email: {
    type: 'string'
  },
  phone: {
    type: 'string'
  },
  url: {
    type: 'string'
  },
  number: {
    type: 'number'
  },
  currency: {
    type: 'number'
  },
  percent: {
    type: 'number'
  },
  rating: {
    type: 'number'
  },
  singleSelect: {
    type: 'option'
  },
  multipleSelect: {
    type: 'option'
  },
  dateTime: {
    type: 'date'
  }
};

/** 从组件或默认值取排序配置；组件可挂载 SortOptions.getSortItems（内置完整排序项）或 SortOptions.type */
function getSortOptionForFieldType(fieldType) {
  var Com = FIELD_TYPE_TO_READ_COMPONENT[fieldType];
  var fromComponent = Com && Com.SortOptions;
  var fallback = FIELD_TYPE_TO_SORT_OPTIONS_DEFAULT[fieldType];
  var opts = fromComponent !== null && fromComponent !== void 0 ? fromComponent : fallback;
  return opts ? _objectSpread(_objectSpread({}, fallback), opts) : null;
}

/** 列 type 对应到 FilterItem 的 type（用于不传 type 时的手动 filter 或派生筛选项的兼容形态）。dateTime 默认用 rangePickerNew（antd）避免使用自研/MUI 的 rangePicker。 */
var FIELD_TYPE_TO_FILTER_TYPE = {
  singleLineText: 'input',
  longText: 'input',
  email: 'input',
  phone: 'input',
  url: 'input',
  number: 'input',
  currency: 'input',
  percent: 'input',
  rating: 'single',
  singleSelect: 'single',
  multipleSelect: 'single',
  dateTime: 'rangePickerNew'
};
function getColumnKey(column) {
  var _column$key;
  var key = (_column$key = column.key) !== null && _column$key !== void 0 ? _column$key : Array.isArray(column.dataIndex) ? column.dataIndex.join('.') : column.dataIndex;
  return typeof key === 'string' ? key : '';
}

/** 获取列唯一 key，供列显示隐藏等使用 */
export function getRecordBoardColumnKey(column) {
  return getColumnKey(column);
}
function getColumnLabel(column) {
  var title = column.title;
  if (typeof title === 'string') return title;
  return getColumnKey(column) || '';
}

/** 从 record 按 dataIndex（支持 string | string[]）取值 */
function getRecordValue(record, dataIndex) {
  if (record == null || dataIndex == null) return undefined;
  var path = Array.isArray(dataIndex) ? dataIndex : [dataIndex];
  return path.reduce(function (r, k) {
    return r != null && _typeof(r) === 'object' ? r[k] : undefined;
  }, record);
}

/** 是否视为空值（用于「全空」判断） */
function isEmptyValue(v) {
  return v == null || v === '';
}

/** 是否可直接用 === 比较（string / number） */
function isComparablePrimitive(v) {
  return typeof v === 'string' || typeof v === 'number';
}
/**
 * 根据当前页 data 计算：哪些列「全列同值」或「全空」应隐藏，以及总结区展示项。
 * 仅当 grid.collapseUniformColumns 为 true 时使用。
 */
export function computeUniformColumnSummary(data, columns) {
  var uniformHiddenColumnKeys = [];
  var summaryItems = [];
  if (!Array.isArray(data) || data.length === 0) return {
    uniformHiddenColumnKeys: uniformHiddenColumnKeys,
    summaryItems: summaryItems
  };
  var _iterator = _createForOfIteratorHelper(columns),
    _step;
  try {
    var _loop = function _loop() {
        var column = _step.value;
        var collapseWhenUniform = column.collapseWhenUniform !== false;
        if (!collapseWhenUniform) return 0; // continue
        var columnKey = getColumnKey(column);
        if (!columnKey) return 0; // continue
        var dataIndex = column.dataIndex;
        var getVal = typeof column.uniformCompare === 'function' ? function (record) {
          return column.uniformCompare(getRecordValue(record, Array.isArray(dataIndex) ? dataIndex : dataIndex), record);
        } : function (record) {
          return getRecordValue(record, Array.isArray(dataIndex) ? dataIndex : dataIndex);
        };
        var values = data.map(getVal);
        var first = values[0];

        // 仅当 dataIndex 取值为 number 或 string 时才参与合并；undefined/null 的列不参与
        if (first === undefined || first === null) return 0; // continue
        var cellValue = getRecordValue(data[0], Array.isArray(dataIndex) ? dataIndex : dataIndex);
        if (values.every(function (v) {
          return isEmptyValue(v);
        })) {
          uniformHiddenColumnKeys.push(columnKey);
          summaryItems.push({
            columnKey: columnKey,
            title: getColumnLabel(column),
            type: 'empty',
            value: undefined,
            cellValue: cellValue,
            record: data[0]
          });
          return 0; // continue
        }
        var comparable = isComparablePrimitive(first);
        if (!comparable) return 0; // continue
        var allSame = values.every(function (v) {
          return isEmptyValue(v) && isEmptyValue(first) || v === first;
        });
        if (!allSame) return 0; // continue
        uniformHiddenColumnKeys.push(columnKey);
        summaryItems.push({
          columnKey: columnKey,
          title: getColumnLabel(column),
          type: 'uniform',
          displayValue: first != null && first !== '' ? String(first) : undefined,
          value: first,
          cellValue: cellValue,
          record: data[0]
        });
      },
      _ret;
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      _ret = _loop();
      if (_ret === 0) continue;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return {
    uniformHiddenColumnKeys: uniformHiddenColumnKeys,
    summaryItems: summaryItems
  };
}
function normalizeOptions(list) {
  if (!Array.isArray(list)) return [];
  return list.map(function (item) {
    return item && _typeof(item) === 'object' && 'label' in item && 'value' in item ? {
      label: String(item.label),
      value: item.value
    } : {
      label: String(item),
      value: item
    };
  });
}

/**
 * 只读单元格：当列使用 getOptions（异步）时，先解析选项再渲染 Pisell 只读组件。
 */
function AsyncOptionsReadCell(_ref) {
  var getOptions = _ref.getOptions,
    value = _ref.value,
    fieldType = _ref.fieldType,
    fieldProps = _ref.fieldProps;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    options = _useState2[0],
    setOptions = _useState2[1];
  var Com = FIELD_TYPE_TO_READ_COMPONENT[fieldType];
  useEffect(function () {
    var result = getOptions();
    var resolved = Promise.resolve(result);
    resolved.then(function (list) {
      return setOptions(normalizeOptions(list));
    });
  }, [getOptions]);
  if (Com == null) return value;
  var common = _objectSpread(_objectSpread({
    value: value
  }, fieldProps), {}, {
    options: options
  });
  if (fieldType === 'singleSelect' || fieldType === 'multipleSelect') {
    return /*#__PURE__*/React.createElement(Com, _extends({}, common, {
      readOnly: true
    }));
  }
  return /*#__PURE__*/React.createElement(Com, _extends({}, common, {
    mode: "read"
  }));
}

/** 为带 type 的列生成只读态渲染函数（Pisell 组件） */
function createReadRender(column, fieldType) {
  var _column$fieldProps;
  var Com = FIELD_TYPE_TO_READ_COMPONENT[fieldType];
  var fieldProps = (_column$fieldProps = column.fieldProps) !== null && _column$fieldProps !== void 0 ? _column$fieldProps : {};
  var getOptions = fieldProps.getOptions;
  var useAsyncOptions = (fieldType === 'singleSelect' || fieldType === 'multipleSelect') && typeof getOptions === 'function';
  return function (value) {
    if (Com == null) return value;
    if (useAsyncOptions) {
      return /*#__PURE__*/React.createElement(AsyncOptionsReadCell, {
        getOptions: getOptions,
        value: value,
        fieldType: fieldType,
        fieldProps: fieldProps
      });
    }
    var common = _objectSpread({
      value: value
    }, fieldProps);
    if (fieldType === 'singleSelect' || fieldType === 'multipleSelect') {
      return /*#__PURE__*/React.createElement(Com, _extends({}, common, {
        readOnly: true
      }));
    }
    if (fieldType === 'dateTime') {
      return /*#__PURE__*/React.createElement(Com, common);
    }
    return /*#__PURE__*/React.createElement(Com, _extends({}, common, {
      mode: "read"
    }));
  };
}

/**
 * 处理列配置：对带 type 的列注入基于 Pisell 组件的 render，其余列保持不变。
 * 有 type 时若列上传入了 render 则优先使用（覆盖自动派生）。
 */
export function processColumnsForGrid(columns) {
  if (!Array.isArray(columns) || columns.length === 0) return columns !== null && columns !== void 0 ? columns : [];
  return columns.map(function (col) {
    var fieldType = col.type;
    if (!fieldType || !FIELD_TYPE_TO_READ_COMPONENT[fieldType]) {
      return col;
    }
    var existingRender = col.render;
    var readRender = createReadRender(col, fieldType);
    return _objectSpread(_objectSpread({}, col), {}, {
      render: existingRender !== null && existingRender !== void 0 ? existingRender : function (value, record, index) {
        return readRender(value, record, index);
      }
    });
  });
}

/** 从列配置生成筛选项（FilterItemProps）；有 type 时可由 filter 覆盖，无 type 时需传 filter */
function columnToFilterItem(column) {
  var _f$label2, _f$props2, _f$options;
  var key = getColumnKey(column);
  var label = getColumnLabel(column);
  if (!key) return null;
  if (column.filterable === false) return null;
  var hasExplicitFilter = column.filter && (column.filter.type != null || column.filter.component);
  if (column.type && !hasExplicitFilter) {
    var _column$fieldProps2, _fieldProps$options, _fieldProps$placehold, _getText;
    var fieldType = column.type;
    var _filterType = FIELD_TYPE_TO_FILTER_TYPE[fieldType];
    var fieldProps = (_column$fieldProps2 = column.fieldProps) !== null && _column$fieldProps2 !== void 0 ? _column$fieldProps2 : {};
    var _hasGetOptions = typeof fieldProps.getOptions === 'function';
    var options = fieldType === 'singleSelect' || fieldType === 'multipleSelect' || fieldType === 'rating' ? (_fieldProps$options = fieldProps.options) !== null && _fieldProps$options !== void 0 ? _fieldProps$options : fieldType === 'rating' ? [1, 2, 3, 4, 5].map(function (v) {
      return {
        label: String(v),
        value: v
      };
    }) : _hasGetOptions ? undefined : [] : undefined;
    return {
      type: _filterType,
      key: key,
      name: key,
      label: label,
      props: _filterType === 'single' ? _objectSpread({
        options: options !== null && options !== void 0 ? options : [],
        getOptions: fieldProps.getOptions
      }, fieldProps) : _objectSpread({
        placeholder: (_fieldProps$placehold = fieldProps.placeholder) !== null && _fieldProps$placehold !== void 0 ? _fieldProps$placehold : String((_getText = getText('pisell2.recordBoard.filter.placeholderEnter')) !== null && _getText !== void 0 ? _getText : '').replace(/\{label\}/g, label)
      }, fieldProps),
      other: _objectSpread({
        fieldType: fieldType,
        getOptions: fieldProps.getOptions
      }, fieldProps)
    };
  }
  if (!column.filter) return null;
  var f = column.filter;
  if (f.component) {
    var _f$label, _f$props;
    return {
      type: 'custom',
      key: key,
      name: key,
      label: (_f$label = f.label) !== null && _f$label !== void 0 ? _f$label : label,
      props: (_f$props = f.props) !== null && _f$props !== void 0 ? _f$props : {},
      other: _objectSpread({
        component: f.component
      }, f.props || {})
    };
  }
  var filterType = f.type;
  if (!filterType) return null;
  var hasGetOptions = typeof f.getOptions === 'function';
  return {
    type: filterType,
    key: key,
    name: key,
    label: (_f$label2 = f.label) !== null && _f$label2 !== void 0 ? _f$label2 : label,
    props: (_f$props2 = f.props) !== null && _f$props2 !== void 0 ? _f$props2 : filterType === 'single' ? {
      options: (_f$options = f.options) !== null && _f$options !== void 0 ? _f$options : [],
      getOptions: f.getOptions
    } : {},
    other: filterType === 'single' && hasGetOptions ? {
      getOptions: f.getOptions
    } : {}
  };
}

/** 从列配置生成排序项（SortItemProps）；有 type 时可由 sort 覆盖，无 type 时需传 sortable + sort */
function columnToSortItem(column) {
  var _s$label;
  var key = getColumnKey(column);
  var label = getColumnLabel(column);
  if (!key) return null;
  if (column.sortable === false) return null;
  var hasExplicitSort = column.sort && (column.sort.type != null || typeof column.sort.getSortItems === 'function');
  if (column.type && !hasExplicitSort) {
    var _opts$label;
    var fieldType = column.type;
    if (!FIELD_TYPE_TO_READ_COMPONENT[fieldType]) return null;
    var opts = getSortOptionForFieldType(fieldType);
    if (!opts) return null;
    var _hasGetSortItems = 'getSortItems' in opts && typeof opts.getSortItems === 'function';
    return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, _hasGetSortItems ? {} : {
      type: 'type' in opts ? opts.type : undefined
    }), _hasGetSortItems && 'getSortItems' in opts ? {
      getSortItems: opts.getSortItems
    } : {}), {}, {
      name: key,
      label: 'label' in opts ? (_opts$label = opts.label) !== null && _opts$label !== void 0 ? _opts$label : label : label,
      isCustom: false
    }, 'localFilter' in opts && opts.localFilter !== undefined && {
      localFilter: opts.localFilter
    }), 'isHidden' in opts && opts.isHidden !== undefined && {
      isHidden: opts.isHidden
    });
  }
  if (!column.type && column.sortable !== true) return null;
  if (!column.sort) return null;
  var s = column.sort;
  var hasGetSortItems = typeof s.getSortItems === 'function';
  var sortItem = _objectSpread({
    name: key,
    label: (_s$label = s.label) !== null && _s$label !== void 0 ? _s$label : label,
    isCustom: false
  }, s.isHidden !== undefined && {
    isHidden: s.isHidden
  });
  if (hasGetSortItems && s.getSortItems) {
    sortItem.getSortItems = s.getSortItems;
  } else if (s.type != null) {
    sortItem.type = s.type;
  }
  return sortItem;
}

/**
 * 从 columns 派生排序列表（SortItemProps[]）。
 * 有 type 的列：根据组件 SortOptions（或默认）生成；无 type 的列：根据 sortable + sort 生成。
 */
export function deriveSortFromColumns(columns) {
  if (!Array.isArray(columns) || columns.length === 0) return [];
  var list = [];
  var _iterator2 = _createForOfIteratorHelper(columns),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var col = _step2.value;
      var hasType = Boolean(col.type && FIELD_TYPE_TO_READ_COMPONENT[col.type]);
      if (hasType && col.sortable === false) continue;
      var item = columnToSortItem(col);
      if (item) list.push(item);
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return list;
}

/**
 * 从 columns 派生 filter 列表（quickFilter + otherFilter）。
 * 有 type 的列：根据 type + fieldProps 生成筛选项；无 type 的列：根据 filterable + filter 生成。
 */
export function deriveFilterFromColumns(columns) {
  var quickFilter = [];
  var otherFilter = [];
  if (!Array.isArray(columns) || columns.length === 0) {
    return {
      quickFilter: quickFilter,
      otherFilter: otherFilter
    };
  }
  var _iterator3 = _createForOfIteratorHelper(columns),
    _step3;
  try {
    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      var _col$filter, _col$filter2;
      var col = _step3.value;
      var key = getColumnKey(col);
      if (!key) continue;
      var hasType = Boolean(col.type && FIELD_TYPE_TO_READ_COMPONENT[col.type]);
      if (hasType && col.filterable === false) continue;
      // 仅显式配置 quickFilter: true 的列放入快筛（左侧 QuickFilter），其余放入普通筛选（右侧高级筛选）
      var useQuick = hasType ? ((_col$filter = col.filter) === null || _col$filter === void 0 ? void 0 : _col$filter.quickFilter) === true : Boolean(col.filterable && ((_col$filter2 = col.filter) === null || _col$filter2 === void 0 ? void 0 : _col$filter2.quickFilter));
      var item = columnToFilterItem(col);
      if (!item) continue;
      if (useQuick) {
        quickFilter.push(item);
      } else {
        otherFilter.push(item);
      }
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }
  return {
    quickFilter: quickFilter,
    otherFilter: otherFilter
  };
}