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); }
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; }
import { useEffect, useMemo, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import { getCurrentViewModeFromLocalStorage, getTableSettingByCurrentViewMode, setTableSettingToLocalStorage } from "../../../table/Table/utils";
var useTableQuery = function useTableQuery(props, currentSettingHash) {
  var _tabs$items, _tabs$items2;
  var filterBy = props.filterBy,
    sortBy = props.sortBy,
    tabs = props.tabs,
    localSettings = props.localSettings;
  var tableId = useMemo(function () {
    if (props.__designMode === 'design') {
      return 'designMode-mock-table-id';
    }
    return (props === null || props === void 0 ? void 0 : props.currentComponentId) || props.__id;
  }, [props.__id, props.__designMode, props === null || props === void 0 ? void 0 : props.currentComponentId]);
  var currentViewMode = useMemo(function () {
    return getCurrentViewModeFromLocalStorage(tableId) || 'grid';
  }, [tableId]);

  // 分页配置
  var _useState = useState({
      page: 1,
      pageSize: 20,
      filter: (tabs === null || tabs === void 0 || (_tabs$items = tabs.items) === null || _tabs$items === void 0 || (_tabs$items = _tabs$items[0]) === null || _tabs$items === void 0 ? void 0 : _tabs$items.filterBy) || filterBy || {},
      sort: (tabs === null || tabs === void 0 || (_tabs$items2 = tabs.items) === null || _tabs$items2 === void 0 || (_tabs$items2 = _tabs$items2[0]) === null || _tabs$items2 === void 0 ? void 0 : _tabs$items2.sortBy) || sortBy
    }),
    _useState2 = _slicedToArray(_useState, 2),
    queryPageConfig = _useState2[0],
    setQueryPageConfig = _useState2[1];
  var getInitialValues = useMemoizedFn(function () {
    try {
      if (!tableId) return {};
      var setting = getTableSettingByCurrentViewMode(tableId, currentViewMode);
      console.log('setting22', setting);
      return (setting === null || setting === void 0 ? void 0 : setting.filters) || {};
    } catch (e) {
      return {};
    }
  });

  // 初始读取本地 filters（若开启本地记忆且 scope 包含 filters）
  useEffect(function () {
    var _localSettings$scope;
    if (!tableId) return;
    var enable = !!(localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope = localSettings.scope) !== null && _localSettings$scope !== void 0 && _localSettings$scope.includes('filters'));
    if (!enable) return;
    var setting = getTableSettingByCurrentViewMode(tableId, currentViewMode);
    var persisted = (setting === null || setting === void 0 ? void 0 : setting.filters) || {};
    if (persisted && Object.keys(persisted).length > 0) {
      setQueryPageConfig(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          filter: _objectSpread(_objectSpread({}, prev.filter), persisted)
        });
      });
    }
  }, [tableId, currentViewMode, JSON.stringify(localSettings)]);

  // 分页变化
  var handleValuesChange = useMemoizedFn(function (params, allParams) {
    var _localSettings$scope2;
    var _ref = params.pagination || {},
      page = _ref.page,
      size = _ref.size;
    var nextFilterForSave = null;
    setQueryPageConfig(function (prev) {
      var sort = prev.sort || sortBy;
      var filter = prev.filter;
      if ("tabs" in params) {
        var _params$tabs, _params$tabs2;
        sort = ((_params$tabs = params.tabs) === null || _params$tabs === void 0 ? void 0 : _params$tabs.sortBy) || sortBy || "";
        var tabsFilter = ((_params$tabs2 = params.tabs) === null || _params$tabs2 === void 0 ? void 0 : _params$tabs2.filterBy) || {};
        filter = _objectSpread(_objectSpread({}, prev.filter), tabsFilter);
        nextFilterForSave = filter;
      }
      if ("order_by" in params) {
        var _allParams$tabs;
        sort = params.order_by || ((_allParams$tabs = allParams.tabs) === null || _allParams$tabs === void 0 ? void 0 : _allParams$tabs.sortBy) || sortBy;
      }
      return _objectSpread(_objectSpread({}, prev), {}, {
        page: size !== prev.pageSize ? 1 : page !== null && page !== void 0 ? page : prev.page,
        pageSize: size !== null && size !== void 0 ? size : prev.pageSize,
        sort: sort,
        filter: filter
      });
    });

    // 当 tabs 变化导致 filter 变更时，同步写入本地（遵循 localSettings）
    var enable = !!(localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope2 = localSettings.scope) !== null && _localSettings$scope2 !== void 0 && _localSettings$scope2.includes('filters'));
    if (enable && tableId && nextFilterForSave) {
      var excluded = new Set((localSettings === null || localSettings === void 0 ? void 0 : localSettings.excludedFilterFields) || []);
      var filtered = {};
      Object.keys(nextFilterForSave).forEach(function (k) {
        if (!excluded.has(k)) {
          filtered[k] = nextFilterForSave[k];
        }
      });
      setTableSettingToLocalStorage({
        tableId: tableId,
        tableSettingObj: {
          filters: filtered
        },
        currentViewMode: currentViewMode,
        currentSettingHash: currentSettingHash
      });
    }
  });
  var handleFilterChange = useMemoizedFn(function (changedFields, allFields) {
    var _localSettings$scope3;
    var nextFilter = _objectSpread({}, allFields);
    setQueryPageConfig(function (prev) {
      return _objectSpread(_objectSpread({}, prev), {}, {
        page: 1,
        filter: _objectSpread(_objectSpread(_objectSpread({}, prev.filter), nextFilter), filterBy || {})
      });
    });

    // 写入本地（仅当开启本地记忆且 scope 包含 filters）
    var enable = !!(localSettings !== null && localSettings !== void 0 && localSettings.enable && (_localSettings$scope3 = localSettings.scope) !== null && _localSettings$scope3 !== void 0 && _localSettings$scope3.includes('filters'));
    if (enable && tableId) {
      // 按 excludedFilterFields 过滤写入
      var excluded = new Set((localSettings === null || localSettings === void 0 ? void 0 : localSettings.excludedFilterFields) || []);
      var filtered = {};
      Object.keys(nextFilter || {}).forEach(function (k) {
        if (!excluded.has(k)) {
          filtered[k] = nextFilter[k];
        }
      });
      setTableSettingToLocalStorage({
        tableId: tableId,
        tableSettingObj: {
          filters: filtered
        },
        currentViewMode: currentViewMode,
        currentSettingHash: currentSettingHash
      });
    }
  });
  var refreshData = useMemoizedFn(function () {
    setQueryPageConfig(function (prev) {
      return _objectSpread(_objectSpread({}, prev), {}, {
        page: 1
      });
    });
  });
  var refreshCurrentPage = useMemoizedFn(function () {
    setQueryPageConfig(function (prev) {
      return _objectSpread({}, prev);
    });
  });
  return {
    queryPageConfig: queryPageConfig,
    setQueryPageConfig: setQueryPageConfig,
    handleValuesChange: handleValuesChange,
    refreshData: refreshData,
    handleFilterChange: handleFilterChange,
    refreshCurrentPage: refreshCurrentPage,
    getInitialValues: getInitialValues
  };
};
export default useTableQuery;