"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _antd = require("antd");
var _index = _interopRequireDefault(require("../ButtonGroup/index"));
require("./style/index.less");
var _ConfigContext = require("../ConfigContext");
var _lodash = _interopRequireDefault(require("lodash"));
var _index3 = _interopRequireDefault(require("./style/index"));
var _useLanguage = require("../hooks/use-language");
var _excluded = ["data", "rowKey", "rowSelection", "columns", "hideOrderNumber", "orderNumber", "className", "emptyText", "codes", "permissionCodes", "columnsConfig", "title", "buttonGroup", "buttonGroupConfig", "min", "batchButtonGroup", "buttonGroupPlacement", "sortOrders", "paginationConfig", "extra", "rowSelectedConfig", "headerAlert"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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 _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; }
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; }
// @ts-ignore
var StandardTable = /*#__PURE__*/_react.default.forwardRef(function (props, ref) {
  var _InitFanContext$local;
  var lang = (0, _useLanguage.useLanguageObject)(); // 当前使用的语言包
  var InitFanContext = (0, _react.useContext)(_ConfigContext.FanContext);
  var language = (InitFanContext === null || InitFanContext === void 0 || (_InitFanContext$local = InitFanContext.locale) === null || _InitFanContext$local === void 0 ? void 0 : _InitFanContext$local.locale) || 'zh-CN';
  var providerConfig = InitFanContext['StandardTable'] || {}; // 使用上下文（全局配置）设置扩展的配置项

  var componentName = 'spec-standard-table';
  var _useStyle = (0, _index3.default)(componentName),
    _useStyle2 = _slicedToArray(_useStyle, 2),
    wrapSSR = _useStyle2[0],
    hashId = _useStyle2[1];
  // const ref= React.createRef<Card>();
  var tableRef = (0, _react.useRef)();
  var tableOuterRef = (0, _react.useRef)();
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      initialInstance: tableRef === null || tableRef === void 0 ? void 0 : tableRef.current
    };
  });
  var _providerConfig$props = _objectSpread(_objectSpread({}, providerConfig), props),
    _providerConfig$props2 = _providerConfig$props.data,
    data = _providerConfig$props2 === void 0 ? {} : _providerConfig$props2,
    rowKey = _providerConfig$props.rowKey,
    rowSelection = _providerConfig$props.rowSelection,
    columns = _providerConfig$props.columns,
    hideOrderNumber = _providerConfig$props.hideOrderNumber,
    _providerConfig$props3 = _providerConfig$props.orderNumber,
    orderNumber = _providerConfig$props3 === void 0 ? {} : _providerConfig$props3,
    className = _providerConfig$props.className,
    emptyText = _providerConfig$props.emptyText,
    codes = _providerConfig$props.codes,
    permissionCodes = _providerConfig$props.permissionCodes,
    _providerConfig$props4 = _providerConfig$props.columnsConfig,
    columnsConfig = _providerConfig$props4 === void 0 ? {} : _providerConfig$props4,
    title = _providerConfig$props.title,
    buttonGroup = _providerConfig$props.buttonGroup,
    buttonGroupConfig = _providerConfig$props.buttonGroupConfig,
    min = _providerConfig$props.min,
    batchButtonGroup = _providerConfig$props.batchButtonGroup,
    _providerConfig$props5 = _providerConfig$props.buttonGroupPlacement,
    buttonGroupPlacement = _providerConfig$props5 === void 0 ? 'right' : _providerConfig$props5,
    sortOrders = _providerConfig$props.sortOrders,
    paginationConfig = _providerConfig$props.paginationConfig,
    extra = _providerConfig$props.extra,
    rowSelectedConfig = _providerConfig$props.rowSelectedConfig,
    headerAlert = _providerConfig$props.headerAlert,
    rest = _objectWithoutProperties(_providerConfig$props, _excluded);
  // 加上类型修复 TS:2322 报警
  var resetColumns = [_objectSpread(_objectSpread({
    width: language === 'en' || language === 'en-US' ? 100 : 76,
    align: 'center',
    title: (lang === null || lang === void 0 ? void 0 : lang['table.column.order']) || '序号',
    key: 'orderNum',
    // fixed: 'left',
    // render: (text, o, index) => pagination ?  (pagination.current - 1) * pagination.pageSize + index + 1 : index + 1,
    render: function render(text, record, index) {
      return (index || 0) + 1;
    }
  }, (columnsConfig === null || columnsConfig === void 0 ? void 0 : columnsConfig.orderNumber) || {}), orderNumber)];
  var _data$list = data.list,
    list = _data$list === void 0 ? [] : _data$list,
    pagination = data.pagination;
  var paginationProps = _objectSpread(_objectSpread({
    // showQuickJumper: true,
    className: 'spec-pagination',
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '15', '20', '30', '50'],
    showTotal: function showTotal(total, range) {
      var unitKey = "".concat((lang === null || lang === void 0 ? void 0 : lang['table.pagination.unit']) || '条');
      return "".concat(range[0], "-").concat(range[1], " ").concat(unitKey, ",").concat((lang === null || lang === void 0 ? void 0 : lang['table.pagination.total']) || '共', " ").concat(total, " ").concat(unitKey);
    },
    // Total ${total} items
    pageSize: (pagination === null || pagination === void 0 ? void 0 : pagination.pageSize) || (pagination === null || pagination === void 0 ? void 0 : pagination.size)
  }, paginationConfig), pagination);
  if (columns) {
    var recombinationColumns = columns.map(function (colItem) {
      var action = columnsConfig.action,
        otherColumn = columnsConfig.otherColumn;
      if (colItem.type === 'action') {
        var _colItem, _colItem2, _colItem3;
        colItem.width = ((_colItem = colItem) === null || _colItem === void 0 ? void 0 : _colItem.width) || (action === null || action === void 0 ? void 0 : action.width) || (colItem.buttonGroup.length > 1 ? 130 : 80);
        colItem.align = ((_colItem2 = colItem) === null || _colItem2 === void 0 ? void 0 : _colItem2.align) || (action === null || action === void 0 ? void 0 : action.align) || 'center';
        colItem.title = ((_colItem3 = colItem) === null || _colItem3 === void 0 ? void 0 : _colItem3.title) || (action === null || action === void 0 ? void 0 : action.title) || (lang === null || lang === void 0 ? void 0 : lang['table.column.action']) || '操作';
        colItem.key = 'control';
        colItem = _objectSpread(_objectSpread(_objectSpread({}, action || {}), colItem), {}, {
          ellipsis: false
        }); //  Object.assign(action || {}, colItem, { ellipsis: false }) // 操作列不配置ellipsis
        // colItem.fixed = colItem.fixed || 'right'
        colItem.render = function (text, record, rowIndex) {
          // 按钮列表组
          var renderTableButtonGroup = function renderTableButtonGroup(buttonGroup) {
            if (!buttonGroup) return '-';
            var recombinationGroup = []; // 重组数据
            // 类型为数组
            if (Array.isArray(buttonGroup)) recombinationGroup = buttonGroup;
            // 类型为方法
            if (typeof buttonGroup === 'function') recombinationGroup = buttonGroup(text, record, rowIndex); // 方法返回数组结构
            // 判断是否是数组且长度大于0时 ？{如下结构渲染} ： {按buttonGroup返回的node渲染}
            if (Array.isArray(buttonGroup) || typeof buttonGroup === 'function') {
              var _colItem4, _colItem5, _colItem6;
              if (recombinationGroup.length === 0) return '-';
              return /*#__PURE__*/_react.default.createElement(_index.default, _extends({
                type: "action",
                min: colItem.min || 2 // 配置按钮展示最少数量，其他的将会被折叠
                ,
                options: recombinationGroup,
                codes: codes,
                permissionCodes: permissionCodes,
                rowParams: {
                  text: text,
                  record: record,
                  rowIndex: rowIndex
                }
                // dropdownConfig={colItem.buttonGroupConfig || {}}
                ,
                moreText: (_colItem4 = colItem) === null || _colItem4 === void 0 ? void 0 : _colItem4.moreText,
                moreIcon: (_colItem5 = colItem) === null || _colItem5 === void 0 ? void 0 : _colItem5.moreIcon
              }, ((_colItem6 = colItem) === null || _colItem6 === void 0 ? void 0 : _colItem6.buttonGroupConfig) || {}));
            } else {
              return buttonGroup;
            }
          };
          return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, renderTableButtonGroup(colItem.buttonGroup));
        };
        return _objectSpread({}, colItem);
      } else if (!colItem.render) {
        // 若未配置render，则给加个默认的返回方法
        colItem.render = function (text, record, rowIndex) {
          return text || text === 0 ? text : '-';
        };
        if (sortOrders && (sortOrders.hasOwnProperty(colItem.key) || sortOrders.hasOwnProperty(colItem.dataIndex))) {
          colItem.sortOrder = (sortOrders === null || sortOrders === void 0 ? void 0 : sortOrders[colItem.key]) || (sortOrders === null || sortOrders === void 0 ? void 0 : sortOrders[colItem.dataIndex]) || (sortOrders === null || sortOrders === void 0 ? void 0 : sortOrders[colItem.key]) || null;
          colItem.sortOrderExtra = true;
        } else {
          if (colItem.sortOrderExtra) {
            delete colItem.sortOrder;
          }
        }
        // return Object.assign({ ellipsis: undefined, render: undefined }, { ...otherColumns, ...colItem });  // ellipsis要配置在render之前
        return _objectSpread(_objectSpread({}, otherColumn), colItem);
      }
      if (sortOrders && (sortOrders.hasOwnProperty(colItem.key) || sortOrders.hasOwnProperty(colItem.dataIndex))) {
        colItem.sortOrder = (sortOrders === null || sortOrders === void 0 ? void 0 : sortOrders[colItem.key]) || (sortOrders === null || sortOrders === void 0 ? void 0 : sortOrders[colItem.dataIndex]) || (sortOrders === null || sortOrders === void 0 ? void 0 : sortOrders[colItem.key]) || null;
        colItem.sortOrderExtra = true;
      } else {
        if (colItem.sortOrderExtra) {
          delete colItem.sortOrder;
        }
      }
      // return Object.assign({ ellipsis: undefined, render: undefined }, { ...otherColumns, ...colItem }) // ellipsis要配置在render之前
      // return { ...otherColumn, ...colItem }
      return _objectSpread(_objectSpread({}, otherColumn), colItem);
    });
    resetColumns = hideOrderNumber ? recombinationColumns : resetColumns.concat(recombinationColumns);
  }
  var RenderExtraButtonGroup = function RenderExtraButtonGroup(exProps) {
    // @ts-ignore
    var _providerConfig$props6 = _objectSpread(_objectSpread({}, providerConfig), props),
      rowSelection = _providerConfig$props6.rowSelection;
    var buttonGroup = exProps.buttonGroup,
      batchButtonGroup = exProps.batchButtonGroup;
    // 只有配置rowSelection才显示对应的批量按钮组
    var list = _lodash.default.unionBy(rowSelection && (rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.type) !== 'radio' && (batchButtonGroup || []), buttonGroup || []);
    return /*#__PURE__*/_react.default.createElement(_index.default, _extends({
      options: list,
      min: min,
      codes: codes,
      permissionCodes: permissionCodes
    }, buttonGroupConfig));
  };

  // 根据placement判断按钮组显示在左边还是右边，
  var placeButtonGroup = batchButtonGroup || buttonGroup ? /*#__PURE__*/_react.default.createElement(RenderExtraButtonGroup, {
    buttonGroup: buttonGroup,
    batchButtonGroup: batchButtonGroup
  }) : null;
  var placeTitle = title ? /*#__PURE__*/_react.default.createElement("span", {
    className: 'ant-card-head-title-name'
  }, title) : null;
  var notShowHead = !extra && !placeButtonGroup && !placeTitle; // 不显示ant-card-head
  // 显示选中扩展展示
  var RenderRowSelectionBlock = function RenderRowSelectionBlock() {
    if (!(rowSelectedConfig !== null && rowSelectedConfig !== void 0 && rowSelectedConfig.show) || !rowSelection) return null;
    var hasSelectedKeys = rowSelection && rowSelection.hasOwnProperty('selectedRowKeys') && rowSelection !== null && rowSelection !== void 0 && rowSelection.selectedRowKeys ? rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.selectedRowKeys : rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.defaultSelectedRowKeys;
    // selectedRowKeys 优先级高于 defaultSelectedRowKeys
    if (hasSelectedKeys.length) {
      var _rowSelectedConfig$re;
      return /*#__PURE__*/_react.default.createElement("div", {
        className: 'spec-standard-table-row-selection-block'
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: 'spec-standard-table-row-selection-block-count'
      }, "\u5DF2\u9009: ", hasSelectedKeys === null || hasSelectedKeys === void 0 ? void 0 : hasSelectedKeys.length), /*#__PURE__*/_react.default.createElement("div", {
        className: 'spec-standard-table-row-selection-block-cancel',
        onClick: function onClick() {
          rowSelection === null || rowSelection === void 0 || rowSelection.onChange([], []);
        }
      }, "\u53D6\u6D88\u9009\u62E9"), /*#__PURE__*/_react.default.createElement("div", {
        className: 'spec-standard-table-row-selection-block-content'
      }, rowSelectedConfig !== null && rowSelectedConfig !== void 0 && rowSelectedConfig.render ? /*#__PURE__*/_react.default.createElement("div", {
        className: 'spec-standard-table-row-selection-block-render'
      }, rowSelectedConfig === null || rowSelectedConfig === void 0 || (_rowSelectedConfig$re = rowSelectedConfig.render) === null || _rowSelectedConfig$re === void 0 ? void 0 : _rowSelectedConfig$re.call(rowSelectedConfig, {
        selectedRowKeys: rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.selectedRowKeys,
        defaultSelectedRowKeys: rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.defaultSelectedRowKeys
      })) : null, /*#__PURE__*/_react.default.createElement(_index.default, _extends({
        rowParams: {
          record: {
            selectedRowKeys: rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.selectedRowKeys,
            defaultSelectedRowKeys: rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.defaultSelectedRowKeys
          }
        }
      }, (rowSelectedConfig === null || rowSelectedConfig === void 0 ? void 0 : rowSelectedConfig.buttonGroupConfig) || {}))));
    }
    return null;
  };
  return wrapSSR( /*#__PURE__*/_react.default.createElement(_antd.Card, {
    className: (0, _classnames.default)(componentName, 'standard-table', className, hashId),
    variant: 'borderless',
    title: notShowHead ? null : buttonGroupPlacement === 'left' ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, placeTitle, placeButtonGroup) : placeTitle,
    extra: notShowHead ? null : buttonGroupPlacement === 'left' ? extra : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, placeButtonGroup, extra),
    ref: tableOuterRef
  }, headerAlert ? /*#__PURE__*/_react.default.createElement("div", {
    className: 'spec-standard-table-alert'
  }, headerAlert) : null, RenderRowSelectionBlock(), /*#__PURE__*/_react.default.createElement(_antd.Table, _extends({
    ref: tableRef,
    rowKey: rowKey || 'id',
    rowSelection: rowSelection ? _objectSpread({
      columnWidth: 56
    }, rowSelection) : rowSelection,
    dataSource: list,
    pagination: !pagination ? false : paginationProps,
    columns: resetColumns,
    locale: {
      filterConfirm: (lang === null || lang === void 0 ? void 0 : lang['global.confirm.text']) || '确定',
      filterReset: (lang === null || lang === void 0 ? void 0 : lang['global.reset.text']) || '重置',
      emptyText: emptyText || (lang === null || lang === void 0 ? void 0 : lang['global.empty.text']) || '暂无数据'
    }
  }, rest, {
    // @ts-ignore
    onChange: function onChange(pagination, filters, sorter, extra) {
      var _rest$onChange;
      var sorterParams = {}; // 取当前列表中有配置排序条件
      // (columns || []).forEach((cItem: any) => {
      //   if (cItem.hasOwnProperty('sorter') && cItem.type !== 'action') {
      //     // 加这个赋值处理是为了避免sorter为空时，原url已经加上了排序值，但是未清空
      //     sorterParams[`${sortPrefixToUrl}${cItem?.key || cItem?.dataIndex}`] = undefined
      //   }
      // })
      var sorters = [];
      if (Array.isArray(sorter)) {
        // 多个条件
        sorters = sorter.map(function (item) {
          return _objectSpread({}, item);
        }).filter(function (item) {
          return item.columnKey;
        });
      } else {
        // 单个条件(需要判断是否有columnKey）
        if (sorter !== null && sorter !== void 0 && sorter.columnKey) {
          sorters.push(_objectSpread({}, sorter));
        }
      }
      // 取当前字段的排序值
      // let orders: any = {};
      (sorters || []).forEach(function (item) {
        if (item !== null && item !== void 0 && item.columnKey) {
          sorterParams["".concat(item === null || item === void 0 ? void 0 : item.columnKey)] = item === null || item === void 0 ? void 0 : item.order;
        }
        // sorterParams[`${sortPrefixToUrl}${item?.columnKey}`] = item?.order
      });
      rest === null || rest === void 0 || (_rest$onChange = rest.onChange) === null || _rest$onChange === void 0 || _rest$onChange.call(rest, _objectSpread(_objectSpread({}, pagination), {}, {
        size: pagination.pageSize,
        orders: sorters.map(function (item) {
          return {
            column: item.columnKey,
            asc: item.order == 'ascend'
          };
        }),
        // 对象
        sorters: sorters,
        // 数组
        sorterParams: sorterParams // 对象
      }), filters, sorter, extra);
    }
  }))));
});
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(StandardTable);