var _excluded = ["view_mode"];
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 _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; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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 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 from "react";
import dayjs from "dayjs";
import { isBoolean, isFunction, isJson, isNumber, isString } from "@pisell/utils";
// @ts-ignore
import md5 from "crypto-js/md5";
// @ts-ignore
import enc from "crypto-js/enc-hex";
import { fieldMaps } from "./fields";
import { getValueByKeys } from "./fields/utils";
var tableKeyPrefix = "table-setting";
export var getHash = function getHash(obj) {
  var jsonString = JSON.stringify(obj);
  var hash = md5(jsonString);
  return hash.toString(enc.Hex);
};
var transColumnsMap = function transColumnsMap(columns) {
  return columns.reduce(function (p, c) {
    return _objectSpread(_objectSpread({}, p), {}, _defineProperty({}, c.dataIndex, c));
  }, {});
};
var filterFnMap = {
  text: function text(value, record, dataIndex) {
    var _record$dataIndex;
    return (_record$dataIndex = record[dataIndex]) === null || _record$dataIndex === void 0 ? void 0 : _record$dataIndex.toString().toLowerCase().includes(value.toLowerCase());
  },
  number: function number(value, record, dataIndex) {
    return record[dataIndex] >= value.min && record[dataIndex] <= value.max;
  },
  filters: function filters(value, record, dataIndex) {
    var _record$dataIndex2;
    return value.map(function (item) {
      return item.toLowerCase();
    }).includes((_record$dataIndex2 = record[dataIndex]) === null || _record$dataIndex2 === void 0 ? void 0 : _record$dataIndex2.toString().toLowerCase());
  }
};
var sorter = function sorter(item) {
  return function (a, b) {
    if (item.field_type === "date") {
      return dayjs(a[item.dataIndex]).valueOf() - dayjs(b[item.dataIndex]).valueOf();
    }
    return a[item.dataIndex] - b[item.dataIndex];
  };
};
export var calcFilterSort = function calcFilterSort(_ref) {
  var dataSource = _ref.dataSource,
    filter = _ref.filter,
    sort = _ref.sort,
    columns = _ref.columns;
  var columnMap = transColumnsMap(columns);
  var newDataSource = dataSource.filter(function (item) {
    return Object.keys(filter || {}).every(function (f) {
      var _filter$f, _columnDetail$filters;
      if (!((_filter$f = filter[f]) !== null && _filter$f !== void 0 && _filter$f.length)) return true;
      var columnDetail = columnMap[f];
      if (((_columnDetail$filters = columnDetail.filters) === null || _columnDetail$filters === void 0 ? void 0 : _columnDetail$filters.length) > 0) {
        return filterFnMap["filters"](filter[f][0], item, columnDetail.dataIndex);
      }
      if (columnDetail.field_type === "text") {
        return filterFnMap[columnDetail.field_type](filter[f][0], item, columnDetail.dataIndex);
      } else if (columnDetail.field_type === "number") {
        return filterFnMap[columnDetail.field_type](filter[f][0], item, columnDetail.dataIndex);
      }
      return true;
    });
  });
  if (sort !== null && sort !== void 0 && sort.order) {
    newDataSource.sort(function (a, b) {
      var order = sort.order;
      if (order === "descend") {
        return sorter(sort.column)(b, a);
      }
      if (order === "ascend") {
        return sorter(sort.column)(a, b);
      }
    });
  }
  return newDataSource;
};

/**
 * 从本地存储获取指定表的列信息
 * @param tableId 表的标识符
 * @returns 返回包含列信息的对象，若未找到则返回空对象
 */
var getColumnsFromLocalStorage = function getColumnsFromLocalStorage(tableId, currentViewMode) {
  if (!tableId) return {};
  var _ref2 = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {},
    column_setting = _ref2.column_setting;
  var col = column_setting;
  if (col) {
    var colKeyMap = col.reduce(function (p, c) {
      p[c.key] = c;
      return p;
    }, {});
    return colKeyMap;
  }
  return {};
};

/**
 * 合并列设置
 * @param defaultColumns 默认列设置
 * @param tableId 表ID
 * @returns 合并后的列设置
 */
export var mergeColumnSetting = function mergeColumnSetting(_ref3) {
  var columns = _ref3.columns,
    tableId = _ref3.tableId,
    currentViewMode = _ref3.currentViewMode;
  if (!tableId) return columns.map(function (item) {
    return _objectSpread(_objectSpread({}, item), {}, {
      isShow: true
    });
  });
  var colKeyMap = getColumnsFromLocalStorage(tableId, currentViewMode);
  var newColumns = columns.map(function (item, index) {
    var col = colKeyMap[item.key];
    var sortIndex = index;
    if (isBoolean(item.fixed) && item.fixed || item.fixed === "left") {
      sortIndex = -99;
    } else if (item.fixed === "right") {
      sortIndex = 9999;
    }
    // 如果本地已经存在columns配置
    if (col) {
      var _col$width, _col$isShow;
      sortIndex = [true, false, "left", "right"].includes(item.fixed) ? sortIndex : col.sortIndex;
      return _objectSpread(_objectSpread({}, item), {}, {
        width: (_col$width = col.width) !== null && _col$width !== void 0 ? _col$width : item.width,
        isShow: (_col$isShow = col.isShow) !== null && _col$isShow !== void 0 ? _col$isShow : true,
        sortIndex: sortIndex
      });
    }
    return _objectSpread(_objectSpread({}, item), {}, {
      isShow: true,
      sortIndex: sortIndex
    });
  });
  // 排序
  newColumns.sort(function (a, b) {
    return a.sortIndex - b.sortIndex;
  });
  return newColumns;
};

/**
 * 对数据源进行排序
 * @param dataSource 数据源数组
 * @param sortObj 排序对象，包含排序的键、值和类型
 * @returns 排序后的数据源数组
 */
export var sortDataSource = function sortDataSource(dataSource, sortObj) {
  var sortKey = sortObj.sortKey,
    sortValue = sortObj.sortValue,
    sortType = sortObj.sortType;
  var newDataSource = _toConsumableArray(dataSource);
  var sorter = function sorter(sortKey, sortType) {
    return function (a, b) {
      var aValue = getValueByKeys(a, sortKey.split(","));
      var bValue = getValueByKeys(b, sortKey.split(","));
      // 对比字符串排序
      if (sortType === "string") {
        if (sortValue === "asc") {
          return aValue === null || aValue === void 0 ? void 0 : aValue.localeCompare(bValue);
        }
        return bValue === null || bValue === void 0 ? void 0 : bValue.localeCompare(aValue);
      }
      // 对比日期排序
      if (sortType === "date") {
        if (sortValue !== "asc") {
          return new Date(bValue).getTime() - new Date(aValue).getTime();
        }
        return new Date(aValue).getTime() - new Date(bValue).getTime();
      }
      // 对比数字排序
      if (sortType === "number") {
        if (sortValue === "asc") {
          return (Number(aValue) || 0) - (Number(bValue) || 0);
        }
        return (Number(bValue) || 0) - (Number(aValue) || 0);
      }
    };
  };
  newDataSource.sort(sorter(sortKey, sortType));
  return newDataSource;
};

/**
 * 根据行键获取 ID
 * @param item 记录对象
 * @param rowKey 行键，可以是字符串或函数
 * @returns 返回 ID
 */
export var getIdByRowKey = function getIdByRowKey(item, rowKey) {
  if (isString(rowKey)) {
    return item[rowKey];
  } else if (isFunction(rowKey)) {
    return item[rowKey(item)];
  }
  return item[rowKey || "id"];
};

/**
 * 根据分组条件对数据源进行分组
 * @param dataSource 数据源
 * @param group 分组条件
 * @param rowKey 行键生成函数或字符串
 * @returns 返回分组后的数据源
 */
export var groupDataSource = function groupDataSource(dataSource, group, rowKey) {
  var groupField = group[0].field;
  if (!groupField) {
    return dataSource;
  }
  var dataIndex = groupField.split(",");
  var newDataSource = _toConsumableArray(dataSource);
  newDataSource = Object.values(newDataSource.reduce(function (pre, cur, index) {
    var groupValue = getValueByKeys(cur, dataIndex);
    if (!pre[groupValue]) {
      pre[groupValue] = {
        __table_group_field: groupField,
        __is_group: true,
        children: [cur]
      };
    } else {
      pre[groupValue].children.push(cur);
    }
    pre[groupValue].__rowKey = "group-".concat(pre[groupValue].children.map(function (item) {
      return getIdByRowKey(item, rowKey);
    }).join("-"));
    pre[groupValue].id = pre[groupValue].__rowKey;
    return _objectSpread({}, pre);
  }, {}));
  return newDataSource;
};

/**
 * 本地存储的表格设置对象
 */

/**
 * 将表格设置保存到本地存储
 * @param tableId 表格id
 * @param tableSettingObj 表格设置对象
 */
export var setTableSettingToLocalStorage = function setTableSettingToLocalStorage(_ref4) {
  var tableId = _ref4.tableId,
    tableSettingObj = _ref4.tableSettingObj,
    currentViewMode = _ref4.currentViewMode,
    currentSettingHash = _ref4.currentSettingHash;
  if (!tableId) return;
  var originData = localStorage.getItem(getTableKey(tableId));
  var newData = {};
  if (originData && isJson(originData)) {
    var data = JSON.parse(originData) || {};
    newData = _objectSpread({}, data);
  }
  var view_mode = tableSettingObj.view_mode,
    itemSetting = _objectWithoutProperties(tableSettingObj, _excluded);
  newData = _objectSpread(_objectSpread({}, newData), {}, _defineProperty({
    view_mode: view_mode || newData.view_mode,
    currentSettingHash: currentSettingHash
  }, currentViewMode, _objectSpread(_objectSpread({}, newData[currentViewMode] || {}), itemSetting)));
  localStorage.setItem(getTableKey(tableId), JSON.stringify(newData));
};
export var clearTableSettingToLocalStorage = function clearTableSettingToLocalStorage(tableId) {
  if (!tableId) return;
  localStorage.removeItem(getTableKey(tableId));
};

/**
 * 从本地存储中获取表格设置, 全部配置
 * @param tableId 表格ID
 * @returns 表格设置对象
 */
export var getTableSettingFromLocalStorage = function getTableSettingFromLocalStorage(tableId) {
  if (!tableId) return {};
  var originData = localStorage.getItem(getTableKey(tableId));
  if (originData && isJson(originData)) {
    return JSON.parse(originData);
  }
  return {};
};

/**
 * 从LocalStorage读取表当前视图模式
 * @param tableId
 */
export var getCurrentViewModeFromLocalStorage = function getCurrentViewModeFromLocalStorage(tableId) {
  var allSetting = getTableSettingFromLocalStorage(tableId);
  return allSetting["view_mode"];
};

/**
 * 根据视图模式获取配置
 * @param tableId
 * @param currentViewMode
 */
export var getTableSettingByCurrentViewMode = function getTableSettingByCurrentViewMode(tableId, currentViewMode) {
  var allSetting = getTableSettingFromLocalStorage(tableId);
  return allSetting[currentViewMode];
};

/**
 * 将表单值保存到本地存储中
 * @param tableId 表单ID
 * @param allValues 表单所有值
 * @param keys 存储的键名
 */
export var setFormValuesToLocalStorage = function setFormValuesToLocalStorage(_ref5) {
  var tableId = _ref5.tableId,
    allValues = _ref5.allValues,
    keys = _ref5.keys,
    currentViewMode = _ref5.currentViewMode,
    currentSettingHash = _ref5.currentSettingHash;
  if (!tableId) return;
  var obj = {};
  keys === null || keys === void 0 || keys.forEach(function (key) {
    obj[key] = allValues === null || allValues === void 0 ? void 0 : allValues[key];
  });
  setTableSettingToLocalStorage({
    tableId: tableId,
    tableSettingObj: obj,
    currentViewMode: currentViewMode,
    currentSettingHash: currentSettingHash
  });
};

/**
 * 获取表格键值
 * @param tableId 表格ID
 * @returns 返回格式化后的表格键值
 */
var getTableKey = function getTableKey(tableId) {
  // 兼容非浏览器环境（如SSR/测试）
  if (typeof window === "undefined" || typeof window.location === "undefined") {
    return "".concat(tableKeyPrefix, "-").concat(tableId);
  }
  var _window$location = window.location,
    pathname = _window$location.pathname,
    search = _window$location.search;
  var appendPath = pathname || "/";

  // 仅用于读取 memory_key，其余查询参数忽略
  var memoryKey = "";
  try {
    var _params = new URLSearchParams(search || "");
    var mk = _params.get("memory_key");
    if (mk && mk.trim() !== "") {
      memoryKey = mk.trim();
    }
  } catch (e) {
    // 忽略解析异常，降级为仅使用 pathname
  }
  var urlPart = memoryKey ? "".concat(appendPath, "#").concat(memoryKey) : appendPath;
  return "".concat(tableKeyPrefix, "-").concat(tableId, "-").concat(urlPart);
};

/**
 * 合并筛选设置
 * @param list 列表数据
 * @param quickFilterMaxLength 快速筛选最大长度
 * @param tableId 表ID
 * @returns 返回合并后的筛选设置
 */
export var mergeFilterSetting = function mergeFilterSetting(_ref6) {
  var list = _ref6.list,
    quickFilterMaxLength = _ref6.quickFilterMaxLength,
    tableId = _ref6.tableId,
    sortButtonShow = _ref6.sortButtonShow,
    currentViewMode = _ref6.currentViewMode;
  if (!sortButtonShow) {
    return {
      quickFilter: [],
      otherFilter: [],
      notSortFilter: list
    };
  }
  var _ref7 = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {},
    filter_setting = _ref7.filter_setting;
  var _ref8 = filter_setting || {},
    quickFilter = _ref8.quickFilter,
    otherFilter = _ref8.otherFilter;
  // 如果没有本地配置，使用quickFilterMaxLength切割数组
  var notSortList = [];
  var sortList = [];
  list.forEach(function (item) {
    if (item.sort) {
      sortList.push(item);
    } else {
      notSortList.push(item);
    }
  });
  if (!tableId || !quickFilter || !otherFilter) {
    var _sortList$slice, _sortList$slice2;
    return {
      quickFilter: (sortList === null || sortList === void 0 || (_sortList$slice = sortList.slice) === null || _sortList$slice === void 0 ? void 0 : _sortList$slice.call(sortList, 0, quickFilterMaxLength)) || [],
      otherFilter: (sortList === null || sortList === void 0 || (_sortList$slice2 = sortList.slice) === null || _sortList$slice2 === void 0 ? void 0 : _sortList$slice2.call(sortList, quickFilterMaxLength)) || [],
      notSortFilter: notSortList
    };
  }
  var quickFilterMap = new Map(quickFilter.map(function (item, index) {
    return [item.key, _objectSpread(_objectSpread({}, item), {}, {
      sortIndex: index
    })];
  }));
  var otherFilterMap = new Map(otherFilter.map(function (item, index) {
    return [item.key, _objectSpread(_objectSpread({}, item), {}, {
      sortIndex: index
    })];
  }));
  var newQuickFilter = Array.from({
    length: 200
  });
  var newOtherFilter = Array.from({
    length: 200
  });
  var notSortFilter = [];
  list.forEach(function (item) {
    if (!item.sort) {
      notSortFilter.push(item);
    } else if (quickFilterMap.has(item.key)) {
      if (isNumber(quickFilterMap.get(item.key).sortIndex)) {
        newQuickFilter[quickFilterMap.get(item.key).sortIndex] = item;
      } else {
        newQuickFilter.push(item);
      }
    } else if (otherFilterMap.has(item.key)) {
      if (isNumber(otherFilterMap.get(item.key).sortIndex)) {
        newOtherFilter[otherFilterMap.get(item.key).sortIndex] = item;
      } else {
        newOtherFilter.push(item);
      }
    } else {
      newOtherFilter.push(item);
    }
  });
  return {
    quickFilter: newQuickFilter.filter(Boolean),
    otherFilter: newOtherFilter.filter(Boolean),
    notSortFilter: notSortFilter
  };
};

/**
 * 过滤数据源
 * @param dataSource 数据源
 * @param filters 过滤条件
 * @param filterLocalArr 本地过滤项
 * @returns 过滤后的数据源
 */
export var filterDataSource = function filterDataSource(dataSource, filters, filterLocalArr) {
  var fnArr = filterLocalArr.map(function (filterItem) {
    if (!filters[filterItem.name]) {
      return null;
    }
    var filterFn = fieldMaps[filterItem.type].filterFn;
    if (!isFunction(filterFn)) {
      return null;
    }
    return function (item) {
      try {
        return filterFn({
          value: filters[filterItem.name],
          item: item,
          key: filterItem.name
        });
      } catch (error) {
        return false;
      }
    };
  }).filter(Boolean);
  return dataSource.filter(function (item) {
    return !fnArr.some(function (fn) {
      return !(fn !== null && fn !== void 0 && fn(item));
    });
  });
};

/**
 * 根据模式获取设置键数组
 * @param filter 筛选器
 * @param columnSetting 列设置
 * @param dataSourceGroup 数据源分组
 * @param sort 排序
 * @param mode 模式，可选值为 "localStorage" 或 "remote"
 * @returns 返回设置键数组
 */
export var getSettingKeyArrByMode = function getSettingKeyArrByMode(_ref9) {
  var filter = _ref9.filter,
    columnSetting = _ref9.columnSetting,
    dataSourceGroup = _ref9.dataSourceGroup,
    sort = _ref9.sort,
    mode = _ref9.mode,
    currentViewMode = _ref9.currentViewMode;
  var keyArr = [];
  if (filter !== null && filter !== void 0 && filter.show && ((filter === null || filter === void 0 ? void 0 : filter.storageMode) || "") == mode) {
    keyArr.push("filter_setting");
  }
  if (((columnSetting === null || columnSetting === void 0 ? void 0 : columnSetting.storageMode) || "") == mode && currentViewMode === "gallery") {
    keyArr.push("gallery_setting", "column_setting");
  }
  if (((columnSetting === null || columnSetting === void 0 ? void 0 : columnSetting.storageMode) || "") == mode && currentViewMode === "grid") {
    keyArr.push("column_setting");
  }
  if (dataSourceGroup !== null && dataSourceGroup !== void 0 && dataSourceGroup.show && ((dataSourceGroup === null || dataSourceGroup === void 0 ? void 0 : dataSourceGroup.storageMode) || "") == mode) {
    keyArr.push("group_by");
  }
  if (sort !== null && sort !== void 0 && sort.show && sort.storageMode == mode) {
    keyArr.push("order_by");
  }
  keyArr.push("view_mode");
  return keyArr;
};
export var omit = function omit(obj, keys) {
  var shallowCopy = Object.assign({}, obj);
  for (var i = 0; i < keys.length; i += 1) {
    var key = keys[i];
    delete shallowCopy[key];
  }
  return shallowCopy;
};
export var stringify = function stringify(obj) {
  return JSON.stringify(obj, function (key, value) {
    if (isFunction(value)) {
      return value.toString();
    }
    if ( /*#__PURE__*/React.isValidElement(value)) {
      return value.toString();
    }
    return value;
  });
};