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/table/Table/utils.ts
var utils_exports = {};
__export(utils_exports, {
  calcFilterSort: () => calcFilterSort,
  clearTableSettingToLocalStorage: () => clearTableSettingToLocalStorage,
  filterDataSource: () => filterDataSource,
  getCurrentViewModeFromLocalStorage: () => getCurrentViewModeFromLocalStorage,
  getHash: () => getHash,
  getIdByRowKey: () => getIdByRowKey,
  getSettingKeyArrByMode: () => getSettingKeyArrByMode,
  getTableSettingByCurrentViewMode: () => getTableSettingByCurrentViewMode,
  getTableSettingFromLocalStorage: () => getTableSettingFromLocalStorage,
  groupDataSource: () => groupDataSource,
  mergeColumnSetting: () => mergeColumnSetting,
  mergeFilterSetting: () => mergeFilterSetting,
  omit: () => omit,
  setFormValuesToLocalStorage: () => setFormValuesToLocalStorage,
  setTableSettingToLocalStorage: () => setTableSettingToLocalStorage,
  sortDataSource: () => sortDataSource,
  stringify: () => stringify
});
module.exports = __toCommonJS(utils_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_md5 = __toESM(require("crypto-js/md5"));
var import_enc_hex = __toESM(require("crypto-js/enc-hex"));
var import_fields = require("./fields");
var import_utils2 = require("./fields/utils");
var tableKeyPrefix = "table-setting";
var getHash = (obj) => {
  const jsonString = JSON.stringify(obj);
  const hash = (0, import_md5.default)(jsonString);
  return hash.toString(import_enc_hex.default.Hex);
};
var transColumnsMap = (columns) => {
  return columns.reduce((p, c) => {
    return {
      ...p,
      [c.dataIndex]: c
    };
  }, {});
};
var filterFnMap = {
  text: (value, record, dataIndex) => {
    var _a;
    return (_a = record[dataIndex]) == null ? void 0 : _a.toString().toLowerCase().includes(value.toLowerCase());
  },
  number: (value, record, dataIndex) => record[dataIndex] >= value.min && record[dataIndex] <= value.max,
  filters: (value, record, dataIndex) => {
    var _a;
    return value.map((item) => item.toLowerCase()).includes((_a = record[dataIndex]) == null ? void 0 : _a.toString().toLowerCase());
  }
};
var sorter = (item) => (a, b) => {
  if (item.field_type === "date") {
    return (0, import_dayjs.default)(a[item.dataIndex]).valueOf() - (0, import_dayjs.default)(b[item.dataIndex]).valueOf();
  }
  return a[item.dataIndex] - b[item.dataIndex];
};
var calcFilterSort = ({ dataSource, filter, sort, columns }) => {
  const columnMap = transColumnsMap(columns);
  const newDataSource = dataSource.filter((item) => {
    return Object.keys(filter || {}).every((f) => {
      var _a, _b;
      if (!((_a = filter[f]) == null ? void 0 : _a.length))
        return true;
      const columnDetail = columnMap[f];
      if (((_b = columnDetail.filters) == null ? void 0 : _b.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 ? void 0 : sort.order) {
    newDataSource.sort((a, b) => {
      const { order } = sort;
      if (order === "descend") {
        return sorter(sort.column)(b, a);
      }
      if (order === "ascend") {
        return sorter(sort.column)(a, b);
      }
    });
  }
  return newDataSource;
};
var getColumnsFromLocalStorage = (tableId, currentViewMode) => {
  if (!tableId)
    return {};
  const { column_setting } = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {};
  const col = column_setting;
  if (col) {
    const colKeyMap = col.reduce(
      (p, c) => {
        p[c.key] = c;
        return p;
      },
      {}
    );
    return colKeyMap;
  }
  return {};
};
var mergeColumnSetting = ({
  columns,
  tableId,
  currentViewMode
}) => {
  if (!tableId)
    return columns.map((item) => ({
      ...item,
      isShow: true
    }));
  const colKeyMap = getColumnsFromLocalStorage(tableId, currentViewMode);
  const newColumns = columns.map((item, index) => {
    const col = colKeyMap[item.key];
    let sortIndex = index;
    if ((0, import_utils.isBoolean)(item.fixed) && item.fixed || item.fixed === "left") {
      sortIndex = -99;
    } else if (item.fixed === "right") {
      sortIndex = 9999;
    }
    if (col) {
      sortIndex = [true, false, "left", "right"].includes(item.fixed) ? sortIndex : col.sortIndex;
      return {
        ...item,
        width: col.width ?? item.width,
        isShow: col.isShow ?? true,
        sortIndex
      };
    }
    return { ...item, isShow: true, sortIndex };
  });
  newColumns.sort((a, b) => a.sortIndex - b.sortIndex);
  return newColumns;
};
var sortDataSource = (dataSource, sortObj) => {
  const { sortKey, sortValue, sortType } = sortObj;
  const newDataSource = [...dataSource];
  const sorter2 = (sortKey2, sortType2) => {
    return (a, b) => {
      const aValue = (0, import_utils2.getValueByKeys)(a, sortKey2.split(","));
      const bValue = (0, import_utils2.getValueByKeys)(b, sortKey2.split(","));
      if (sortType2 === "string") {
        if (sortValue === "asc") {
          return aValue == null ? void 0 : aValue.localeCompare(bValue);
        }
        return bValue == null ? void 0 : bValue.localeCompare(aValue);
      }
      if (sortType2 === "date") {
        if (sortValue !== "asc") {
          return new Date(bValue).getTime() - new Date(aValue).getTime();
        }
        return new Date(aValue).getTime() - new Date(bValue).getTime();
      }
      if (sortType2 === "number") {
        if (sortValue === "asc") {
          return (Number(aValue) || 0) - (Number(bValue) || 0);
        }
        return (Number(bValue) || 0) - (Number(aValue) || 0);
      }
    };
  };
  newDataSource.sort(sorter2(sortKey, sortType));
  return newDataSource;
};
var getIdByRowKey = (item, rowKey) => {
  if ((0, import_utils.isString)(rowKey)) {
    return item[rowKey];
  } else if ((0, import_utils.isFunction)(rowKey)) {
    return item[rowKey(item)];
  }
  return item[rowKey || "id"];
};
var groupDataSource = (dataSource, group, rowKey) => {
  const groupField = group[0].field;
  if (!groupField) {
    return dataSource;
  }
  const dataIndex = groupField.split(",");
  let newDataSource = [...dataSource];
  newDataSource = Object.values(
    newDataSource.reduce((pre, cur, index) => {
      const groupValue = (0, import_utils2.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-${pre[groupValue].children.map((item) => getIdByRowKey(item, rowKey)).join("-")}`;
      pre[groupValue].id = pre[groupValue].__rowKey;
      return { ...pre };
    }, {})
  );
  return newDataSource;
};
var setTableSettingToLocalStorage = ({
  tableId,
  tableSettingObj,
  currentViewMode,
  currentSettingHash
}) => {
  if (!tableId)
    return;
  const originData = localStorage.getItem(getTableKey(tableId));
  let newData = {};
  if (originData && (0, import_utils.isJson)(originData)) {
    const data = JSON.parse(originData) || {};
    newData = {
      ...data
    };
  }
  const { view_mode, ...itemSetting } = tableSettingObj;
  newData = {
    ...newData,
    view_mode: view_mode || newData.view_mode,
    currentSettingHash,
    [currentViewMode]: {
      ...newData[currentViewMode] || {},
      ...itemSetting
    }
  };
  localStorage.setItem(getTableKey(tableId), JSON.stringify(newData));
};
var clearTableSettingToLocalStorage = (tableId) => {
  if (!tableId)
    return;
  localStorage.removeItem(getTableKey(tableId));
};
var getTableSettingFromLocalStorage = (tableId) => {
  if (!tableId)
    return {};
  const originData = localStorage.getItem(getTableKey(tableId));
  if (originData && (0, import_utils.isJson)(originData)) {
    return JSON.parse(originData);
  }
  return {};
};
var getCurrentViewModeFromLocalStorage = (tableId) => {
  const allSetting = getTableSettingFromLocalStorage(tableId);
  return allSetting["view_mode"];
};
var getTableSettingByCurrentViewMode = (tableId, currentViewMode) => {
  const allSetting = getTableSettingFromLocalStorage(tableId);
  return allSetting[currentViewMode];
};
var setFormValuesToLocalStorage = ({
  tableId,
  allValues,
  keys,
  currentViewMode,
  currentSettingHash
}) => {
  if (!tableId)
    return;
  let obj = {};
  keys == null ? void 0 : keys.forEach((key) => {
    obj[key] = allValues == null ? void 0 : allValues[key];
  });
  setTableSettingToLocalStorage({
    tableId,
    tableSettingObj: obj,
    currentViewMode,
    currentSettingHash
  });
};
var getTableKey = (tableId) => `${tableKeyPrefix}-${tableId}`;
var mergeFilterSetting = ({
  list,
  quickFilterMaxLength,
  tableId,
  sortButtonShow,
  currentViewMode
}) => {
  var _a, _b;
  if (!sortButtonShow) {
    return {
      quickFilter: [],
      otherFilter: [],
      notSortFilter: list
    };
  }
  const { filter_setting } = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {};
  const { quickFilter, otherFilter } = filter_setting || {};
  const notSortList = [];
  const sortList = [];
  list.forEach((item) => {
    if (item.sort) {
      sortList.push(item);
    } else {
      notSortList.push(item);
    }
  });
  if (!tableId || !quickFilter || !otherFilter) {
    return {
      quickFilter: ((_a = sortList == null ? void 0 : sortList.slice) == null ? void 0 : _a.call(sortList, 0, quickFilterMaxLength)) || [],
      otherFilter: ((_b = sortList == null ? void 0 : sortList.slice) == null ? void 0 : _b.call(sortList, quickFilterMaxLength)) || [],
      notSortFilter: notSortList
    };
  }
  const quickFilterMap = new Map(
    quickFilter.map((item, index) => [item.key, { ...item, sortIndex: index }])
  );
  const otherFilterMap = new Map(
    otherFilter.map((item, index) => [item.key, { ...item, sortIndex: index }])
  );
  let newQuickFilter = Array.from({ length: 200 });
  let newOtherFilter = Array.from({ length: 200 });
  let notSortFilter = [];
  list.forEach((item) => {
    if (!item.sort) {
      notSortFilter.push(item);
    } else if (quickFilterMap.has(item.key)) {
      if ((0, import_utils.isNumber)(quickFilterMap.get(item.key).sortIndex)) {
        newQuickFilter[quickFilterMap.get(item.key).sortIndex] = item;
      } else {
        newQuickFilter.push(item);
      }
    } else if (otherFilterMap.has(item.key)) {
      if ((0, import_utils.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
  };
};
var filterDataSource = (dataSource, filters, filterLocalArr) => {
  const fnArr = filterLocalArr.map((filterItem) => {
    if (!filters[filterItem.name]) {
      return null;
    }
    const { filterFn } = import_fields.fieldMaps[filterItem.type];
    if (!(0, import_utils.isFunction)(filterFn)) {
      return null;
    }
    return (item) => {
      try {
        return filterFn({
          value: filters[filterItem.name],
          item,
          key: filterItem.name
        });
      } catch (error) {
        return false;
      }
    };
  }).filter(Boolean);
  return dataSource.filter((item) => {
    return !fnArr.some((fn) => {
      return !(fn == null ? void 0 : fn(item));
    });
  });
};
var getSettingKeyArrByMode = ({
  filter,
  columnSetting,
  dataSourceGroup,
  sort,
  mode,
  currentViewMode
}) => {
  const keyArr = [];
  if ((filter == null ? void 0 : filter.show) && ((filter == null ? void 0 : filter.storageMode) || "") == mode) {
    keyArr.push("filter_setting");
  }
  if (((columnSetting == null ? void 0 : columnSetting.storageMode) || "") == mode && currentViewMode === "gallery") {
    keyArr.push("gallery_setting", "column_setting");
  }
  if (((columnSetting == null ? void 0 : columnSetting.storageMode) || "") == mode && currentViewMode === "grid") {
    keyArr.push("column_setting");
  }
  if ((dataSourceGroup == null ? void 0 : dataSourceGroup.show) && ((dataSourceGroup == null ? void 0 : dataSourceGroup.storageMode) || "") == mode) {
    keyArr.push("group_by");
  }
  if ((sort == null ? void 0 : sort.show) && sort.storageMode == mode) {
    keyArr.push("order_by");
  }
  keyArr.push("view_mode");
  return keyArr;
};
var omit = (obj, keys) => {
  const shallowCopy = Object.assign({}, obj);
  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    delete shallowCopy[key];
  }
  return shallowCopy;
};
var stringify = (obj) => {
  return JSON.stringify(obj, (key, value) => {
    if ((0, import_utils.isFunction)(value)) {
      return value.toString();
    }
    if (import_react.default.isValidElement(value)) {
      return value.toString();
    }
    return value;
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  calcFilterSort,
  clearTableSettingToLocalStorage,
  filterDataSource,
  getCurrentViewModeFromLocalStorage,
  getHash,
  getIdByRowKey,
  getSettingKeyArrByMode,
  getTableSettingByCurrentViewMode,
  getTableSettingFromLocalStorage,
  groupDataSource,
  mergeColumnSetting,
  mergeFilterSetting,
  omit,
  setFormValuesToLocalStorage,
  setTableSettingToLocalStorage,
  sortDataSource,
  stringify
});
