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; }
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); }
import { useMemo, useRef, useState, useCallback } from 'react';
import useDataSource from "../../dataSourceComponents/hooks/useDataSource";
import { formatListResult } from "../utils/formatData";
var defaultPagination = {
  pageNumber: 1,
  pageSize: 10
};
var useHandleAction = function useHandleAction() {
  var initialParams = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var options = arguments.length > 1 ? arguments[1] : undefined;
  var form = arguments.length > 2 ? arguments[2] : undefined;
  var _useDataSource = useDataSource(),
    list = _useDataSource.list,
    get = _useDataSource.get,
    update = _useDataSource.update,
    create = _useDataSource.create,
    destroy = _useDataSource.destroy,
    getCurrentRecord = _useDataSource.getCurrentRecord;

  // 参数规范化：如果 options 为 true，使用默认分页配置
  var normalizedOptions = options === true ? defaultPagination : _typeof(options) === 'object' ? options : {};
  var pageNumber = normalizedOptions.pageNumber,
    pageSize = normalizedOptions.pageSize;
  var enablePagination = pageNumber !== undefined && pageSize !== undefined;

  //  缓存初始参数（用于 reset）
  var initialParamsRef = useRef(initialParams);
  var _useState = useState({
      pageNumber: pageNumber !== null && pageNumber !== void 0 ? pageNumber : 1,
      pageSize: pageSize !== null && pageSize !== void 0 ? pageSize : 10
    }),
    _useState2 = _slicedToArray(_useState, 2),
    pagination = _useState2[0],
    setPagination = _useState2[1];
  var run = list.run,
    params = list.params,
    listData = list.data;

  /**
   * 查询方法 - 合并当前分页和新参数进行查询
   * @param newParams 新的查询参数
   * @description 如果启用分页，会自动重置到第一页
   */
  var onSearch = useCallback(function (newParams) {
    var _initialParamsRef$cur;
    var searchParams = _objectSpread(_objectSpread(_objectSpread({}, (params === null || params === void 0 ? void 0 : params[0]) || {}), ((_initialParamsRef$cur = initialParamsRef.current) === null || _initialParamsRef$cur === void 0 ? void 0 : _initialParamsRef$cur.list) || {}), newParams);
    if (enablePagination) {
      searchParams = _objectSpread(_objectSpread({}, searchParams), {}, {
        pageNumber: 1,
        // 查询时始终重置到第一页
        pageSize: pagination.pageSize
      });
      if (pagination.pageNumber !== 1) {
        setPagination(function (prev) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            pageNumber: 1
          });
        });
      }
    }

    // run(formatListParams(searchParams));  // 算了 外部传什么 是什么吧
    run(searchParams);
  }, [enablePagination, pagination.pageNumber, pagination.pageSize, params, run]);

  /**
   * 重置方法 - 重置到初始参数和初始分页
   */
  var onReset = useCallback(function () {
    var _initialParamsRef$cur2;
    var formValues = (form === null || form === void 0 ? void 0 : form.getFieldsValue()) || {};
    var resetParams = _objectSpread(_objectSpread({}, ((_initialParamsRef$cur2 = initialParamsRef.current) === null || _initialParamsRef$cur2 === void 0 ? void 0 : _initialParamsRef$cur2.list) || {}), formValues);
    if (enablePagination) {
      setPagination({
        pageNumber: pageNumber !== null && pageNumber !== void 0 ? pageNumber : 1,
        pageSize: pageSize !== null && pageSize !== void 0 ? pageSize : 10
      });
      resetParams = _objectSpread(_objectSpread({}, resetParams), {}, {
        pageNumber: pageNumber !== null && pageNumber !== void 0 ? pageNumber : 1,
        pageSize: pageSize !== null && pageSize !== void 0 ? pageSize : 10
      });
    }
    run(resetParams);
  }, [run, enablePagination, pagination, pageNumber, pageSize]);

  /**
   *  分页
   */
  var onPageChange = useCallback(function (pageNumber, pageSize) {
    var _initialParamsRef$cur3;
    if (!enablePagination) {
      console.warn('分页功能未启用');
      return;
    }
    if (pageNumber < 1 || pageSize < 1) return;
    setPagination({
      pageNumber: pageNumber,
      pageSize: pageSize
    });
    var lastParams = (params === null || params === void 0 ? void 0 : params[0]) || _objectSpread({}, ((_initialParamsRef$cur3 = initialParamsRef.current) === null || _initialParamsRef$cur3 === void 0 ? void 0 : _initialParamsRef$cur3.list) || {});
    run(_objectSpread(_objectSpread({}, lastParams), {}, {
      pageNumber: pageNumber,
      pageSize: pageSize
    }));
  }, [enablePagination, params, run]);
  return useMemo(function () {
    return {
      list: _objectSpread(_objectSpread({}, list), {}, {
        data: formatListResult(listData),
        onSearch: onSearch,
        onReset: onReset,
        onPageChange: onPageChange
      }, enablePagination ? {
        pagination: pagination
      } : {}),
      get: get,
      update: update,
      create: create,
      destroy: destroy,
      getCurrentRecord: getCurrentRecord
    };
  }, [list, get, update, create, destroy, getCurrentRecord, pagination]);
};
export default useHandleAction;