"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _react() {
  const data = _interopRequireWildcard(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _antd() {
  const data = require("antd");

  _antd = function _antd() {
    return data;
  };

  return data;
}

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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(n); 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(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

const useCallData = (getData, effects, options) => {
  const _useState = (0, _react().useState)(options.defaultData),
        _useState2 = _slicedToArray(_useState, 2),
        list = _useState2[0],
        setList = _useState2[1];

  const _useState3 = (0, _react().useState)(true),
        _useState4 = _slicedToArray(_useState3, 2),
        loading = _useState4[0],
        setLoading = _useState4[1];

  const _useState5 = (0, _react().useState)(1),
        _useState6 = _slicedToArray(_useState5, 2),
        pageIndex = _useState6[0],
        setPageIndex = _useState6[1];

  const _useState7 = (0, _react().useState)(false),
        _useState8 = _slicedToArray(_useState7, 2),
        hasMore = _useState8[0],
        setHasMore = _useState8[1];

  const _ref = options || {},
        _ref$manual = _ref.manual,
        manual = _ref$manual === void 0 ? false : _ref$manual;

  const _ref2 = options && options.fetchMore ? options.fetchMore : {},
        _ref2$pageSize = _ref2.pageSize,
        pageSize = _ref2$pageSize === void 0 ? 20 : _ref2$pageSize;

  const fetchList = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator(function* (isAppend) {
      setLoading(true);

      const _yield$getData = yield getData({
        pageIndex,
        pageSize
      }),
            data = _yield$getData.data,
            success = _yield$getData.success,
            message = _yield$getData.message;

      if (success !== false) {
        if (isAppend && list) {
          const newList = _objectSpread({}, data);

          Object.keys(data || {}).forEach(key => {
            // 自动合并返回中的数组
            if (Array.isArray(data[key]) && list[key]) {
              newList[key] = list[key].concat(data[key]);
            }
          });
          setList(newList);
        } else {
          setList(data);
        } // 判断是否还有更多


        let totalCount = 0;
        Object.keys(data || {}).forEach(key => {
          // 后端返回的总数的字段都是类似 totalOrderCount 这样格式的
          if (/total\S+Count/.test(key) && typeof data[key] === 'number') {
            totalCount = data[key];
          }
        });

        if (totalCount > pageSize * pageIndex) {
          // 还可以翻页
          setHasMore(true);
        } else {
          setHasMore(false);
        }
      } else {
        _antd().message.error(message);
      }

      setLoading(false);
    });

    return function fetchList(_x) {
      return _ref3.apply(this, arguments);
    };
  }();

  const fetchMore = () => {
    setPageIndex(pageIndex + 1);
    fetchList(true);
  };

  (0, _react().useEffect)(() => {
    if (manual === false) {
      fetchList();
    }
  }, effects || []);
  return {
    data: list,
    loading,
    fetch: fetchList,
    fetchMore,
    hasMore,
    setList
  };
};

var _default = useCallData;
exports.default = _default;