var _excluded = ["header", "mainAction", "quickAction", "regularFilter", "advancedFilter", "isCollapse", "showSearchBtn", "searchBtnProps", "toolBar", "columns", "url", "pageKey", "pageSizeKey", "method", "params", "formatSort", "formatParams", "formatResult", "requestWhenMount", "showPagination", "pageSizeList", "showSkeleton", "skeletonSize", "actionRef", "dataSource", "filterDebounce"];

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 _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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 _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(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Table, Pagination, Message } from '@alicloudfe/components';
import genProColumnToColumn from './utils/genProColumnToColumn';
import { baseClass, useRequest, request as utilResquest, getDeepValue, getMessage, pickProps } from '@teamix/utils';
import './index.scss';
import Layout from './components/Layout';
import { useActionType } from './utils';
import getTableProps from './utils/getTableProps';
import getTableSortIcons from './utils/getTableSortIcons';
import FullScreen from './components/ToolBar/Fullscreen';
import { createForm, toJS } from '@teamix/pro-form';
import debounce from 'lodash.debounce';
export * from './typing'; // 导出 ProActions 组件

export * from '@teamix/pro-actions';
export { default as ActionButton } from '@teamix/pro-actions';
import { registerActionHandler } from '@teamix/pro-actions';
var cls = baseClass('teamix-pro-table');
/**
 * 处理原生传入的 columns 以便于 选择列 方便处理
 * @param columns 原生传入的 columns
 * @returns
 */

var processColumns = function processColumns(columns) {
  return columns.filter(function (item) {
    return item.columnFilters !== false;
  });
};
/** 默认请求翻页参数 */


var globalPageKey = 'currentPage';
var globalPageSizeKey = 'pageSize';

var globalFormatSort = function globalFormatSort(sort) {
  if (Object.keys(sort).length > 0) {
    return {
      sort: sort
    };
  }

  return {};
};

var ProTable = function ProTable(props) {
  var header = props.header,
      mainAction = props.mainAction,
      quickAction = props.quickAction,
      regularFilter = props.regularFilter,
      advancedFilter = props.advancedFilter,
      isCollapse = props.isCollapse,
      _props$showSearchBtn = props.showSearchBtn,
      showSearchBtn = _props$showSearchBtn === void 0 ? false : _props$showSearchBtn,
      searchBtnProps = props.searchBtnProps,
      toolBar = props.toolBar,
      propsColumns = props.columns,
      url = props.url,
      pageKey = props.pageKey,
      pageSizeKey = props.pageSizeKey,
      _props$method = props.method,
      method = _props$method === void 0 ? 'get' : _props$method,
      _props$params = props.params,
      propsParams = _props$params === void 0 ? {} : _props$params,
      formatSort = props.formatSort,
      _props$formatParams = props.formatParams,
      formatParams = _props$formatParams === void 0 ? function (params) {
    return params;
  } : _props$formatParams,
      formatResult = props.formatResult,
      _props$requestWhenMou = props.requestWhenMount,
      requestWhenMount = _props$requestWhenMou === void 0 ? true : _props$requestWhenMou,
      _props$showPagination = props.showPagination,
      showPagination = _props$showPagination === void 0 ? true : _props$showPagination,
      _props$pageSizeList = props.pageSizeList,
      pageSizeList = _props$pageSizeList === void 0 ? [5, 10, 20, 50, 100] : _props$pageSizeList,
      _props$showSkeleton = props.showSkeleton,
      propsShowSkeleton = _props$showSkeleton === void 0 ? true : _props$showSkeleton,
      _props$skeletonSize = props.skeletonSize,
      skeletonSize = _props$skeletonSize === void 0 ? 5 : _props$skeletonSize,
      propsActionRef = props.actionRef,
      dataSource = props.dataSource,
      _props$filterDebounce = props.filterDebounce,
      filterDebounce = _props$filterDebounce === void 0 ? 300 : _props$filterDebounce,
      otherProps = _objectWithoutProperties(props, _excluded);

  var targetPageKey = pageKey || globalPageKey;
  var targetPageSizeKey = pageSizeKey || globalPageSizeKey;
  var targetFormatSort = formatSort || globalFormatSort;

  var _useState = useState(1),
      _useState2 = _slicedToArray(_useState, 2),
      currentPage = _useState2[0],
      setCurrentPage = _useState2[1];

  var _useState3 = useState(props.pageSize || 10),
      _useState4 = _slicedToArray(_useState3, 2),
      pageSize = _useState4[0],
      setPageSize = _useState4[1];

  var _useState5 = useState(0),
      _useState6 = _slicedToArray(_useState5, 2),
      total = _useState6[0],
      setTotal = _useState6[1];

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      data = _useState8[0],
      setData = _useState8[1];

  var _useState9 = useState(props.sort || {}),
      _useState10 = _slicedToArray(_useState9, 2),
      sort = _useState10[0],
      setSort = _useState10[1];

  var _useState11 = useState(requestWhenMount && propsShowSkeleton),
      _useState12 = _slicedToArray(_useState11, 2),
      showSkeleton = _useState12[0],
      setShowSkeleton = _useState12[1]; // 首次加载，渲染骨架屏


  var skeletonDataSource = new Array(skeletonSize).fill({});
  var requestDataKey = method.toLowerCase() === 'get' ? 'params' : 'data';
  var tableRef = useRef(null);
  var actionRef = useRef(); // 传给 table 的过滤后的 columns

  var _useState13 = useState(processColumns(propsColumns !== null && propsColumns !== void 0 ? propsColumns : [])),
      _useState14 = _slicedToArray(_useState13, 2),
      filteredColumns = _useState14[0],
      setFilteredColumns = _useState14[1];

  var _useState15 = useState('medium'),
      _useState16 = _slicedToArray(_useState15, 2),
      size = _useState16[0],
      _setSize = _useState16[1]; // 全屏显示 className


  var _useState17 = useState(false),
      _useState18 = _slicedToArray(_useState17, 2),
      fullscreenState = _useState18[0],
      setFullscreenState = _useState18[1];
  /** 筛选区域 form */


  var regularFilterForm = useMemo(function () {
    return createForm();
  }, []);
  var advancedFilterForm = useMemo(function () {
    return createForm();
  }, []);
  useEffect(function () {
    if (typeof propsActionRef === 'function' && actionRef.current) {
      // @ts-ignore
      propsActionRef(actionRef.current);
    }
  }, [propsActionRef]);
  useEffect(function () {
    setFilteredColumns(processColumns(propsColumns !== null && propsColumns !== void 0 ? propsColumns : []));
  }, [propsColumns]); // 绑定 Actions

  useActionType(actionRef, {
    fullScreen: function fullScreen() {
      var state = !fullscreenState;
      setFullscreenState(state);
      return state;
    },
    setColumn: function setColumn(newColumns) {
      setFilteredColumns(processColumns(newColumns));
    },
    setSize: function setSize(mode) {
      _setSize(mode);
    },
    refresh: function refresh(params) {
      return request(params);
    }
  }); // 将 Actions 绑定到传入的 propsActionRef 中

  if (propsActionRef) {
    propsActionRef.current = actionRef.current;
  } // 请求表格数据工具函数


  var getData = useRequest(function (params) {
    return _defineProperty({
      url: url,
      method: method
    }, requestDataKey, params);
  }, {
    // 使用 request 方法代替 fetch
    requestMethod: function requestMethod(params) {
      return utilResquest(params);
    },
    manual: true,
    onSuccess: function onSuccess(result) {
      props.onSuccess && props.onSuccess(result);
      var nextData = result;

      if (formatResult) {
        if (typeof formatResult === 'function') {
          nextData = formatResult(result) || {};
        } else if (_typeof(formatResult) === 'object') {
          var dataTotal = getDeepValue(formatResult.total, result);
          nextData = {
            data: getDeepValue(formatResult.data, result) || [],
            total: isNaN(dataTotal) ? 0 : Number(dataTotal)
          };
        }
      }

      function onFormatResult(next) {
        props.onFormatResult && props.onFormatResult(next); // 设置 dataSource、total

        setData(next.data || []);
        setTotal(next.total || next.data.length);
        setShowSkeleton(false);
      }

      if (nextData instanceof Promise) {
        nextData.then(function (res) {
          onFormatResult(res);
        }).catch(function () {
          onFormatResult({});
        });
      } else {
        onFormatResult(nextData);
      }
    },
    onError: function onError(error) {
      setShowSkeleton(false);

      if (props.onError) {
        props.onError(error);
      } else {
        Message.error(error.toString());
      }
    }
  }); // 请求函数

  function request(params) {
    var _objectSpread2;

    var sortParams = targetFormatSort(sort); // 筛选区请求参数

    var regularFilterParams = toJS(regularFilterForm.values);
    var advancedFilterParams = toJS(advancedFilterForm.values); // 格式化后的请求参数

    var requestData = formatParams(_objectSpread(_objectSpread({}, !showPagination ? _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, regularFilterParams), advancedFilterParams), propsParams), sortParams) : _objectSpread(_objectSpread(_objectSpread(_objectSpread((_objectSpread2 = {}, _defineProperty(_objectSpread2, targetPageKey, currentPage), _defineProperty(_objectSpread2, targetPageSizeKey, pageSize), _objectSpread2), regularFilterParams), advancedFilterParams), propsParams), sortParams)), params));

    if (requestData) {
      // console.log('requestData', requestData);
      getData.run(requestData);
    }
  }

  useEffect(function () {
    if (requestWhenMount) {
      // TODO: add SearchParams
      request();
    }
  }, []);

  function onSort(dataIndex, order) {
    var nextSort = _defineProperty({}, dataIndex, order);

    setSort(nextSort);
    request(targetFormatSort(nextSort));
  } // 自动搜索


  function onFilterChange(hasFilterChange) {
    if (!hasFilterChange) {
      props.onFilterChange && props.onFilterChange(_objectSpread(_objectSpread({}, toJS(regularFilterForm.values)), toJS(advancedFilterForm.values)));
    }

    if (!showSearchBtn) {
      setCurrentPage(1);
      request(_defineProperty({}, targetPageKey, 1));
    }
  } // 点击搜索


  function onSearch(hasSearch) {
    if (!hasSearch) {
      props.onSearch && props.onSearch(_objectSpread(_objectSpread({}, toJS(regularFilterForm.values)), toJS(advancedFilterForm.values)));
    }

    setCurrentPage(1);
    request(_defineProperty({}, targetPageKey, 1));
  }

  var renderTable = function renderTable() {
    if (propsColumns) {
      return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Layout, {
        header: header,
        mainAction: mainAction,
        quickAction: quickAction,
        toolBar: toolBar,
        actionRef: actionRef,
        columns: propsColumns,
        regularFilter: regularFilter,
        advancedFilter: advancedFilter,
        isCollapse: isCollapse,
        regularFilterForm: regularFilterForm,
        advancedFilterForm: advancedFilterForm,
        showSearchBtn: showSearchBtn,
        searchBtnProps: searchBtnProps,
        onFilterChange: debounce(onFilterChange, filterDebounce),
        // 有搜索按钮不用防抖
        onSearch: onSearch
      }), /*#__PURE__*/React.createElement(Table, _objectSpread({
        dataSource: showSkeleton ? skeletonDataSource : data || props.dataSource,
        columns: genProColumnToColumn(filteredColumns, showSkeleton, actionRef),
        loading: !showSkeleton && (getData.loading || props.loading),
        className: cls(),
        size: size,
        onSort: onSort,
        sort: sort,
        sortIcons: getTableSortIcons()
      }, pickProps(getTableProps(), otherProps))));
    } else {
      // 不传 columns 直接返回原始 Table
      return /*#__PURE__*/React.createElement(Table, _objectSpread({
        className: cls()
      }, pickProps(getTableProps(), otherProps)));
    }
  };

  var renderFooter = function renderFooter() {
    function onChangePagination(currentPage) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      setCurrentPage(currentPage);
      request(_objectSpread(_defineProperty({}, targetPageKey, currentPage), params));
    }

    function onChangePaginationSize(currentPageSize) {
      setPageSize(currentPageSize);
      request(_defineProperty({}, targetPageSizeKey, currentPageSize));
    }

    if (showPagination) {
      return /*#__PURE__*/React.createElement("div", {
        className: cls('footer')
      }, /*#__PURE__*/React.createElement(Pagination, _objectSpread({
        className: cls('pagination'),
        onChange: function onChange(number) {
          return onChangePagination(number);
        },
        total: total,
        totalRender: function totalRender(total) {
          return getMessage('total', {
            total: total
          });
        },
        pageSize: pageSize,
        current: currentPage,
        shape: "arrow-only",
        pageSizeList: pageSizeList,
        pageSizeSelector: total > (props.pageSize || 10) * 2 ? 'dropdown' : false,
        pageSizePosition: "end",
        type: total / pageSize <= 2 ? 'simple' : 'normal',
        onPageSizeChange: function onPageSizeChange(number) {
          return onChangePaginationSize(number);
        }
      }, props.paginationProps)));
    }
  };

  return /*#__PURE__*/React.createElement(FullScreen, {
    visible: fullscreenState,
    actionRef: actionRef
  }, /*#__PURE__*/React.createElement("div", {
    className: cls({
      '': true,
      fullscreen: fullscreenState
    }),
    ref: tableRef
  }, renderTable(), renderFooter()));
}; // 注册 action 里面的弹层表格


registerActionHandler('dialog-table', 'dialog', {
  component: ProTable,
  closeable: true,
  size: 'medium'
});
registerActionHandler('drawer-table', 'dialog', {
  component: ProTable,
  closeable: true,
  dialogType: 'drawer',
  size: 'medium'
});
export default ProTable;