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 { useMemo } from "react";
import { getSettingKeyArrByMode, getTableSettingByCurrentViewMode, getTableSettingFromLocalStorage, mergeColumnSetting, mergeFilterSetting, setTableSettingToLocalStorage, setFormValuesToLocalStorage } from "../Table/utils";
import { useMemoizedFn } from "ahooks";
import React from "react";
var useTableSetting = function useTableSetting(params) {
  var tableId = params.tableId,
    filter = params.filter,
    columnSetting = params.columnSetting,
    dataSourceGroup = params.dataSourceGroup,
    sort = params.sort,
    view = params.view,
    currentViewMode = params.currentViewMode,
    propsColumns = params.columns,
    gallery = params.gallery,
    currentSettingHash = params.currentSettingHash,
    exportImport = params.exportImport,
    localSettings = params.localSettings;
  var columnsMap = useMemo(function () {
    return new Map(propsColumns.map(function (item) {
      return [item.key, item];
    }));
  }, [propsColumns]);

  // 获取当前视图下的columns配置
  var columns = useMemo(function () {
    if (currentViewMode === "grid") {
      return propsColumns;
    } else if (currentViewMode === "gallery") {
      var _gallery$content;
      return ((gallery === null || gallery === void 0 || (_gallery$content = gallery.content) === null || _gallery$content === void 0 ? void 0 : _gallery$content.fields) || []).filter(function (item) {
        return item.show;
      }).map(function (item) {
        return columnsMap.get(item.columnKey);
      }).filter(Boolean);
    }
    return propsColumns;
  }, [propsColumns, currentViewMode, gallery, columnsMap]);
  var _ref = filter || {},
    list = _ref.list,
    quickFilterMaxLength = _ref.quickFilterMaxLength,
    sortButtonShow = _ref.sortButtonShow;
  var defaultGalleryCoverSetting = useMemo(function () {
    var _gallery$cover, _columns$find;
    return {
      coverObjectFit: gallery === null || gallery === void 0 || (_gallery$cover = gallery.cover) === null || _gallery$cover === void 0 ? void 0 : _gallery$cover.objectFit,
      coverField: (_columns$find = columns.find(function (column) {
        var _gallery$cover2;
        return column.key === (gallery === null || gallery === void 0 || (_gallery$cover2 = gallery.cover) === null || _gallery$cover2 === void 0 || (_gallery$cover2 = _gallery$cover2.fields) === null || _gallery$cover2 === void 0 ? void 0 : _gallery$cover2[0]);
      })) === null || _columns$find === void 0 ? void 0 : _columns$find.dataIndex,
      compactMode: "default",
      isShowLabel: true
    };
  }, [gallery, columns]);

  /**
   * 获取需要本地存储的 keyArr
   */
  var localStorageSettingKeyArr = useMemo(function () {
    var _localSettings$scope;
    var keys = getSettingKeyArrByMode({
      filter: filter,
      columnSetting: columnSetting,
      dataSourceGroup: dataSourceGroup,
      sort: sort,
      mode: "localStorage",
      currentViewMode: currentViewMode
    });
    // 本地记忆：filters 范围 -> 存储到 filter 字段
    if (localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope = localSettings.scope) !== null && _localSettings$scope !== void 0 && _localSettings$scope.includes("filters")) {
      if (!keys.includes("filters")) {
        keys.push("filters");
      }
    }
    return keys;
  }, [tableId, filter, columnSetting, dataSourceGroup, sort, currentViewMode]);
  var defaultKeyArr = useMemo(function () {
    return getSettingKeyArrByMode({
      filter: filter,
      columnSetting: columnSetting,
      dataSourceGroup: dataSourceGroup,
      sort: sort,
      mode: "",
      currentViewMode: currentViewMode
    });
  }, [tableId, filter, columnSetting, dataSourceGroup, sort, view, currentViewMode]);

  /**
   * 获取本地存储的 tableSetting 用于刷新后回显
   */
  var tableLocalSetting = useMemo(function () {
    var setting = {};
    /** 当前组件下的所有配置 */
    var allSetting = getTableSettingFromLocalStorage(tableId);
    /** 当前视图下的配置 */
    var currentViewModeSetting = getTableSettingByCurrentViewMode(tableId, currentViewMode);
    var mergedSetting = _objectSpread(_objectSpread({}, allSetting), currentViewModeSetting);
    localStorageSettingKeyArr.forEach(function (item) {
      if (item === "view_mode") {
        /** 多视图模式当前视图从本地存储取， 单视图模式直接取默认视图 */
        setting[item] = view.multiple ? (mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item]) || view.defaultViewMode : view.defaultViewMode;
      } else if (item === "filter_setting") {
        setting[item] = mergeFilterSetting({
          list: list,
          quickFilterMaxLength: quickFilterMaxLength,
          tableId: tableId,
          sortButtonShow: sortButtonShow,
          currentViewMode: currentViewMode
        });
      } else if (item === "column_setting") {
        setting[item] = mergeColumnSetting({
          columns: columns,
          tableId: tableId,
          currentViewMode: currentViewMode
        });
      } else if (item === "gallery_setting") {
        var _mergedSetting$item, _mergedSetting$item2, _mergedSetting$item3, _mergedSetting$item$i, _mergedSetting$item4;
        setting[item] = _objectSpread(_objectSpread({}, mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item]), {}, {
          // 本地没有默认封面效果时取配置中的
          coverObjectFit: (mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item = mergedSetting[item]) === null || _mergedSetting$item === void 0 ? void 0 : _mergedSetting$item.coverObjectFit) || defaultGalleryCoverSetting.coverObjectFit,
          coverField: (mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item2 = mergedSetting[item]) === null || _mergedSetting$item2 === void 0 ? void 0 : _mergedSetting$item2.coverField) || defaultGalleryCoverSetting.coverField,
          compactMode: (mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item3 = mergedSetting[item]) === null || _mergedSetting$item3 === void 0 ? void 0 : _mergedSetting$item3.compactMode) || defaultGalleryCoverSetting.compactMode,
          isShowLabel: (_mergedSetting$item$i = mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item4 = mergedSetting[item]) === null || _mergedSetting$item4 === void 0 ? void 0 : _mergedSetting$item4.isShowLabel) !== null && _mergedSetting$item$i !== void 0 ? _mergedSetting$item$i : defaultGalleryCoverSetting.isShowLabel
        });
      } else if (item === "filters") {
        setting[item] = (mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item]) || {};
      } else {
        setting[item] = mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item];
      }
    });
    return setting;
  }, [localStorageSettingKeyArr, tableId, view, list, quickFilterMaxLength, tableId, sortButtonShow, columns, currentViewMode, gallery, defaultGalleryCoverSetting]);
  var defaultTableSetting = useMemo(function () {
    var setting = {};
    defaultKeyArr.forEach(function (item) {
      if (item === "column_setting") {
        setting[item] = mergeColumnSetting({
          columns: columns,
          tableId: tableId,
          currentViewMode: currentViewMode
        });
      } else if (item === "filter_setting") {
        setting[item] = mergeFilterSetting({
          list: list,
          quickFilterMaxLength: quickFilterMaxLength,
          tableId: "",
          sortButtonShow: sortButtonShow,
          currentViewMode: currentViewMode
        });
      } else if (item === "gallery_setting") {
        setting[item] = {
          // 取配置中的设置
          coverObjectFit: defaultGalleryCoverSetting.coverObjectFit,
          coverField: defaultGalleryCoverSetting.coverField,
          compactMode: defaultGalleryCoverSetting.compactMode,
          isShowLabel: defaultGalleryCoverSetting.isShowLabel
        };
      }
    });
    return setting;
  }, [defaultKeyArr, columns, defaultGalleryCoverSetting, columns, tableId, currentViewMode, list, quickFilterMaxLength, sortButtonShow]);

  /**
   * 更新 tableSetting
   * @param values
   */
  var setTableSetting = useMemoizedFn(function (values) {
    var _localSettings$scope2;
    // 计算需要存储的 filter 值（仅当开启本地记忆且包含 filters 时）
    var valuesForSave = values;
    if (localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope2 = localSettings.scope) !== null && _localSettings$scope2 !== void 0 && _localSettings$scope2.includes("filters")) {
      var excluded = new Set((localSettings === null || localSettings === void 0 ? void 0 : localSettings.excludedFilterFields) || []);
      var filterValue = {};
      ((filter === null || filter === void 0 ? void 0 : filter.list) || []).forEach(function (item) {
        var rawName = item === null || item === void 0 ? void 0 : item.name;
        if (!rawName) return;
        var key = Array.isArray(rawName) ? rawName.join(",") : String(rawName);
        if (excluded.has(key)) return;
        if (values.hasOwnProperty(key)) {
          filterValue[key] = values[key];
        }
      });
      valuesForSave = _objectSpread(_objectSpread({}, values), {}, {
        filters: filterValue
      });
    }
    setFormValuesToLocalStorage({
      tableId: tableId,
      allValues: valuesForSave,
      keys: localStorageSettingKeyArr,
      currentViewMode: currentViewMode,
      currentSettingHash: currentSettingHash
    });
  });
  var tableSetting = useMemo(function () {
    var _localSettings$scope3;
    var merged = _objectSpread(_objectSpread({}, tableLocalSetting), defaultTableSetting);
    // 将本地记忆的 filter 扁平化注入初始表单值（不改变存储结构）
    if (localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope3 = localSettings.scope) !== null && _localSettings$scope3 !== void 0 && _localSettings$scope3.includes("filters")) {
      var persistedFilter = tableLocalSetting === null || tableLocalSetting === void 0 ? void 0 : tableLocalSetting.filters;
      if (persistedFilter && _typeof(persistedFilter) === "object") {
        return _objectSpread(_objectSpread({}, merged), persistedFilter);
      }
    }
    return merged;
  }, [tableLocalSetting, defaultTableSetting]);

  /**
   * 当刷新后获得新的 localSettings（scope 或 excludedFilterFields 变化）时，
   * 根据最新规则调整已存储的 filters
   */
  // 对本地已存储 filters 做一次对齐（仅在必要时写回）
  useMemo(function () {
    try {
      var _localSettings$scope4;
      if (!tableId) return;
      var current = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {};
      var persistedFilters = (current === null || current === void 0 ? void 0 : current.filters) || {};
      var nextFilters = _objectSpread({}, persistedFilters);
      var shouldUpdate = false;
      var enableFiltersMemory = !!(localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope4 = localSettings.scope) !== null && _localSettings$scope4 !== void 0 && _localSettings$scope4.includes("filters"));
      if (!enableFiltersMemory) {
        if (Object.keys(persistedFilters || {}).length > 0) {
          nextFilters = {};
          shouldUpdate = true;
        }
      } else {
        var names = new Set();
        if ( /*#__PURE__*/React.isValidElement(filter) || /*#__PURE__*/React.isValidElement(filter === null || filter === void 0 ? void 0 : filter.dom)) {
          names = new Set(((filter === null || filter === void 0 ? void 0 : filter.items) || []).filter(function (item) {
            return !item.isHidden;
          }).map(function (item) {
            var rawName = item === null || item === void 0 ? void 0 : item.value;
            if (!rawName) return undefined;
            return Array.isArray(rawName) ? rawName.join(",") : String(rawName);
          }));
        } else {
          names = new Set(((filter === null || filter === void 0 ? void 0 : filter.list) || []).map(function (item) {
            var rawName = item === null || item === void 0 ? void 0 : item.name;
            if (!rawName) return undefined;
            return Array.isArray(rawName) ? rawName.join(",") : String(rawName);
          }).filter(Boolean));
        }
        var excluded = new Set((localSettings === null || localSettings === void 0 ? void 0 : localSettings.excludedFilterFields) || []);
        var allowed = new Set(Array.from(names).filter(function (k) {
          return !excluded.has(k);
        }));
        var filtered = {};
        Object.keys(persistedFilters || {}).forEach(function (k) {
          if (allowed.has(k)) {
            filtered[k] = persistedFilters[k];
          } else {
            shouldUpdate = true;
          }
        });
        if (Object.keys(filtered).length !== Object.keys(persistedFilters || {}).length) {
          shouldUpdate = true;
        }
        nextFilters = filtered;
      }
      if (shouldUpdate) {
        setTableSettingToLocalStorage({
          tableId: tableId,
          tableSettingObj: {
            filters: nextFilters
          },
          currentViewMode: currentViewMode,
          currentSettingHash: currentSettingHash
        });
      }
    } catch (e) {
      // ignore
    }
  }, []);
  return {
    setTableSetting: setTableSetting,
    tableSetting: tableSetting
  };
};
export default useTableSetting;