"use strict";

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

var _tslib = require("tslib");

var _react = _interopRequireDefault(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _dialog = _interopRequireDefault(require("../dialog"));

var _get = _interopRequireDefault(require("lodash/get"));

var _balloon = _interopRequireDefault(require("../balloon"));

var _consoleComponents = require("@alicloud/console-components");

var _Actions = _interopRequireDefault(require("./Actions"));

var _page = _interopRequireDefault(require("../page"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var BalloonIcon = _balloon["default"].Icon;

var LPTable =
/** @class */
function (_super) {
  (0, _tslib.__extends)(LPTable, _super);

  function LPTable(props) {
    var _this = _super.call(this, props) || this;

    _this.rowSelectionProxy = function (rowSelection, batchActionContent) {
      if (rowSelection || batchActionContent) {
        var rowSelecttion_ = rowSelection || {};
        var onChange_1 = rowSelecttion_.onChange,
            onSelect_1 = rowSelecttion_.onSelect,
            onSelectAll_1 = rowSelecttion_.onSelectAll;
        var rowSelectionTemp = (0, _tslib.__assign)((0, _tslib.__assign)({
          columnProps: function columnProps() {
            return {
              "width": 30,
              "align": 'right'
            };
          },
          selectedRowKeys: _this.state.selectedRowKeys
        }, rowSelecttion_), {
          onChange: function onChange(selectedRowKeys_, records) {
            _this.setState({
              selectedRowKeys: selectedRowKeys_
            }, function () {
              onChange_1 && onChange_1(selectedRowKeys_, records);
            });
          },
          onSelect: function onSelect(selected, record, records) {
            onSelect_1 && onSelect_1(selected, record, records);
          },
          onSelectAll: function onSelectAll(selected, records) {
            onSelectAll_1 && onSelectAll_1(selected, records);
          }
        });
        return rowSelectionTemp;
      } else {
        return undefined;
      }
    };

    _this.columnCell = function (value, index, data, column, noBalloon, balloonProps) {
      if (noBalloon === void 0) {
        noBalloon = false;
      }

      var cell = column.cell;

      if (cell instanceof Function) {
        var t = cell(value, index, data);

        if (Object.prototype.toString.call(t) === '[object String]') {
          value = t;
        } else {
          return t;
        }
      } else {
        if (typeof value === "string") {
          value = value.trim() === "" ? '-' : value.toString();
        } else if (value === null) {
          value = '-';
        } else if (value === undefined) {
          value = '-';
        }

        return !noBalloon && column.width ? /*#__PURE__*/_react["default"].createElement(_balloon["default"], (0, _tslib.__assign)({}, balloonProps, {
          overShowBalloon: true,
          trigger: value
        }), value) : value;
      }

      return value;
    };

    _this.getActionable = function (visible, data, defaultValue) {
      var isVisible = defaultValue;

      if (typeof visible === 'function') {
        isVisible = visible(data);
      }

      if (typeof visible === 'boolean') {
        isVisible = visible;
      }

      return isVisible;
    };

    _this.generateActions = function (value, index, data, actions) {
      var rowSelection = _this.props.rowSelection;
      var _a = actions.buttons,
          buttons = _a === void 0 ? [] : _a,
          _b = actions.max,
          max = _b === void 0 ? 0 : _b,
          _c = actions.maxText,
          maxText = _c === void 0 ? '更多' : _c;
      max = max === 0 ? buttons.length : max;
      var visibleButtons = buttons.filter(function (item) {
        var visible = _this.getActionable(item.visible, {
          item: data,
          index: index
        }, true);

        return visible;
      });
      var inSideButtons = visibleButtons.slice(max - 1);
      var outSideButtons = inSideButtons.length > 1 ? visibleButtons.slice(0, max - 1) : visibleButtons.slice(0, max);

      var proxyActionOnClick = function proxyActionOnClick(e, data, index, item) {
        if (rowSelection) {
          var selectedRowKeyAfterClick = item.onClick && item.onClick(e, data, index, rowSelection.selectedRowKeys ? rowSelection.selectedRowKeys : _this.state.selectedRowKeys);

          if (selectedRowKeyAfterClick && Array.isArray(selectedRowKeyAfterClick)) {
            _this.setState({
              selectedRowKeys: selectedRowKeyAfterClick
            });
          }
        } else {
          item.onClick && item.onClick(e, data, index, []);
        }
      };

      return /*#__PURE__*/_react["default"].createElement("span", null, outSideButtons.map(function (item, actionIndex) {
        var textButton = /*#__PURE__*/_react["default"].createElement(_Actions["default"], {
          key: index + 1 * actionIndex + value + 1,
          action: item,
          rawData: data,
          rawIndex: index,
          content: item.content,
          onClick: function onClick(e, data, index) {
            proxyActionOnClick(e, data, index, item);
          },
          disabled: _this.getActionable(item.disabled, {
            item: data,
            index: index
          }, false)
        });

        return _this.renderTextButton(textButton, item, index, actionIndex);
      }), max > 0 && inSideButtons.length > 1 && /*#__PURE__*/_react["default"].createElement(_consoleComponents.Dropdown, {
        triggerType: "click",
        trigger: /*#__PURE__*/_react["default"].createElement("span", {
          className: "lp-datagrid-actions"
        }, maxText, /*#__PURE__*/_react["default"].createElement(_consoleComponents.Icon, {
          style: {
            marginLeft: 1
          },
          type: 'caret-down',
          size: "xxs"
        }))
      }, /*#__PURE__*/_react["default"].createElement(_consoleComponents.Menu, null, inSideButtons.map(function (item, actionIndex) {
        return /*#__PURE__*/_react["default"].createElement(_consoleComponents.Menu.Item, {
          key: index + 1 * actionIndex + 100,
          disabled: item.disabled,
          onClick: function onClick(e) {
            proxyActionOnClick(e, data, index, item);
          }
        }, /*#__PURE__*/_react["default"].createElement(_Actions["default"], {
          action: item,
          rawData: data,
          rawIndex: index,
          content: item.content,
          visible: item.visible,
          disabled: _this.getActionable(item.disabled, {
            item: data,
            index: index
          }, false)
        }));
      }))));
    };

    _this.returnBatchActionContent = function (batchActionContent) {
      var propsselectedRowKeys = (0, _get["default"])(_this.props, 'rowSelection.selectedRowKeys', undefined);
      var propsselectedRowKeysLength = (0, _get["default"])(_this.props, 'rowSelection.selectedRowKeys.length', 0);
      var disableState = propsselectedRowKeys ? propsselectedRowKeysLength > 0 : _this.state.selectedRowKeys.length > 0;
      var bts = batchActionContent.map(function (item, index) {
        if (item.visiabled === false) {
          return null;
        } else if (item && /*#__PURE__*/_react["default"].isValidElement(item)) {
          return /*#__PURE__*/_react["default"].cloneElement(item, {
            className: "lp-diyBatchActionContent",
            key: "batchActionContent" + index
          });
        } else if (item) {
          return /*#__PURE__*/_react["default"].createElement(_consoleComponents.Button, {
            key: 'batchActionContent' + item.name,
            size: item.size ? item.size : 'medium',
            disabled: item.disabled != undefined ? item.disabled : disableState ? false : true,
            onClick: function onClick() {
              if (propsselectedRowKeysLength > 0) {
                item.onClick ? item.onClick(propsselectedRowKeys) : '';

                _this.setState({
                  selectedRowKeys: []
                });
              } else if (item.comfirmProps) {
                var onOk_ = function onOk_() {
                  _this.setState({
                    selectedRowKeys: []
                  });

                  item.comfirmProps.onOk && item.comfirmProps.onOk(_this.state.selectedRowKeys);
                };

                var onCancel_ = function onCancel_() {
                  item.comfirmProps.onCancel && item.comfirmProps.onCancel(_this.state.selectedRowKeys);
                };

                var onClose_ = function onClose_() {
                  item.comfirmProps.onClose && item.comfirmProps.onClose(_this.state.selectedRowKeys);
                };

                _dialog["default"].LPConfirm((0, _tslib.__assign)((0, _tslib.__assign)({}, item.comfirmProps), {
                  onOk: onOk_,
                  onCancel: onCancel_,
                  onClose: onClose_
                }));
              } else {
                item.onClick ? item.onClick(_this.state.selectedRowKeys) : '';

                _this.setState({
                  selectedRowKeys: []
                });
              }
            }
          }, item.name);
        } else {
          return null;
        }
      });

      if (bts.length > 0) {
        bts.unshift( /*#__PURE__*/_react["default"].createElement(_consoleComponents.Checkbox, {
          key: _this.TableId + "_checkBox",
          disabled: !disableState,
          checked: disableState,
          onChange: function onChange() {
            _this.setState({
              selectedRowKeys: []
            });

            _this.props.batchClearAction && _this.props.batchClearAction();
          }
        }));
      }

      return bts;
    };

    _this.renderfooter = function (paginationConfig, batchActionContent) {
      if (_this.props.dataSource && _this.props.dataSource.length === 0 || paginationConfig === undefined && batchActionContent === undefined) {
        return null;
      }

      if (paginationConfig.total > paginationConfig.pageSizeList[0] || batchActionContent && batchActionContent.length > 0) {
        var showTotal = paginationConfig.showTotal,
            rest = (0, _tslib.__rest)(paginationConfig, ["showTotal"]);
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "lp-datagrid-pagination"
        }, /*#__PURE__*/_react["default"].createElement("div", {
          className: "lp-datagrid-pagination-btn"
        }, batchActionContent && _this.returnBatchActionContent(batchActionContent)), paginationConfig.total > paginationConfig.pageSizeList[0] ? /*#__PURE__*/_react["default"].createElement("div", {
          className: "lp-datagrid-pagination-wrap"
        }, /*#__PURE__*/_react["default"].createElement(_consoleComponents.Pagination, (0, _tslib.__assign)({}, rest))) : null);
      } else {
        return null;
      }
    };

    _this.renderColums = function (columns, dataSource, noBalloon) {
      return columns.map(function (column, index) {
        var balloonProps = column.balloonProps,
            tips = column.tips,
            title = column.title,
            _a = column.iconType,
            iconType = _a === void 0 ? 'help' : _a,
            _b = column.iconColor,
            iconColor = _b === void 0 ? '#ccc' : _b,
            _c = column.iconSize,
            iconSize = _c === void 0 ? 'small' : _c,
            rest = (0, _tslib.__rest)(column, ["balloonProps", "tips", "title", "iconType", "iconColor", "iconSize"]);

        var title_ = _this.generateTitle(tips, title, iconType, iconColor, iconSize);

        if (column.isSpecialIndex) {
          var changedDataIndex_1 = column.dataIndex.replace('.', '_');
          dataSource = dataSource.map(function (item) {
            var v = item[column.dataIndex];
            delete item[column.dataIndex];
            item[changedDataIndex_1] = v;
          });
          column.dataIndex = changedDataIndex_1;
          delete column.isSpecialIndex;
        }

        return /*#__PURE__*/_react["default"].createElement(_consoleComponents.Table.Column, (0, _tslib.__assign)({}, rest, {
          title: title_,
          key: index,
          cell: function cell(value, index, data) {
            return _this.columnCell(value, index, data, column, noBalloon, column.balloonProps);
          }
        }));
      });
    };

    _this.getPaginationConfig = function (pagination, batchActionContent, locale) {
      if (pagination || batchActionContent) {
        var defaultPagination = {
          showTotal: true,
          size: 'medium',
          defaultCurrent: 1,
          pageSize: 10,
          total: 0,
          pageSizeSelector: 'dropdown',
          pageSizePosition: 'start',
          pageSizeList: [5, 10, 20]
        };
        var locale_ = {
          prev: '上一页',
          next: '下一页',
          goTo: '到第',
          page: '页',
          go: '确定',
          pageSize: '每页显示'
        };
        locale = Object.assign(locale_, locale);

        if (locale.total) {
          if (typeof locale.total === 'function') {
            defaultPagination.totalRender = locale.total;
          } else {
            defaultPagination.totalRender = function () {
              return locale.totaltotal.replace("{total}", "" + (pagination.total ? pagination.total : 0)).replace("{current}", "" + (pagination.current ? pagination.current : 1));
            };
          }
        } else {
          defaultPagination.totalRender = function () {
            return "\u5171\u6709{total}\u6761, ".replace("{total}", "" + (pagination.total ? pagination.total : 0));
          };
        }

        var paginationConfig = (0, _tslib.__assign)((0, _tslib.__assign)((0, _tslib.__assign)({}, defaultPagination), pagination), {
          locale: locale
        });

        if (!paginationConfig.showTotal) {
          defaultPagination.totalRender = undefined;
        }

        return paginationConfig;
      } else {
        return undefined;
      }
    };

    _this.state = {
      selectedRowKeys: []
    };
    _this.TableId = "Table" + Math.random();
    return _this;
  }

  LPTable.prototype.generateTitle = function (tips, title, iconType, iconColor, iconSize) {
    if (iconType === void 0) {
      iconType = 'help';
    }

    if (iconColor === void 0) {
      iconColor = '#ccc';
    }

    var titleContent = title;

    if (tips) {
      if (typeof titleContent === 'function') {
        titleContent = titleContent();
      }

      title = function title() {
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "lp-datagrid-th"
        }, /*#__PURE__*/_react["default"].createElement(BalloonIcon, {
          title: titleContent,
          iconSize: iconSize,
          iconColor: iconColor,
          iconType: iconType
        }, tips));
      };
    }

    return title;
  };

  LPTable.prototype.renderTextButton = function (textButton, item, index, actionIndex) {
    if (item.balloonConfig) {
      return /*#__PURE__*/_react["default"].createElement(_balloon["default"], (0, _tslib.__assign)({
        align: "tr",
        maxLine: 1,
        closable: false,
        key: index + 1 * actionIndex + 1
      }, item.balloonConfig, {
        trigger: textButton
      }), item.balloonConfig.text);
    } else {
      return textButton;
    }
  };

  LPTable.prototype.render = function () {
    var _this = this;

    var _a = this.props,
        groupHeader = _a.groupHeader,
        //
    groupFooter = _a.groupFooter,
        //
    pagination = _a.pagination,
        //
    actions = _a.actions,
        //
    batchActionContent = _a.batchActionContent,
        //
    columns = _a.columns,
        //
    isLoading = _a.isLoading,
        //
    dataSource = _a.dataSource,
        //
    emptyContent = _a.emptyContent,
        //
    empty = _a.empty,
        //
    _b = _a.noBalloon,
        //
    noBalloon = _b === void 0 ? false : _b,
        //
    baseEmpty = _a.baseEmpty,
        //
    rowSelection = _a.rowSelection,
        //
    _c = _a.primaryKey,
        //
    primaryKey = _c === void 0 ? 'id' : _c,
        locale = _a.locale,
        batchClearAction = _a.batchClearAction,
        config = (0, _tslib.__rest)(_a, ["groupHeader", "groupFooter", "pagination", "actions", "batchActionContent", "columns", "isLoading", "dataSource", "emptyContent", "empty", "noBalloon", "baseEmpty", "rowSelection", "primaryKey", "locale", "batchClearAction"]); //改变table的rowSelection

    var rowSelection_ = this.rowSelectionProxy(rowSelection, batchActionContent);
    var paginationConfig = this.getPaginationConfig(pagination, batchActionContent, locale);
    var ResultemptyContent = emptyContent ? emptyContent : baseEmpty ? /*#__PURE__*/_react["default"].createElement("div", null, empty ? empty : "暂无数据") : /*#__PURE__*/_react["default"].createElement(_page["default"].empty, {
      type: "noContent",
      title: empty ? empty : "暂无数据"
    });
    var renderColumsContent = this.renderColums(columns, dataSource, noBalloon);
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("lp-datagrid", baseEmpty && 'lp-datagrid-baseEmpty')
    }, /*#__PURE__*/_react["default"].createElement(_consoleComponents.Table, (0, _tslib.__assign)({
      primaryKey: primaryKey,
      hasBorder: false,
      isZebra: false,
      id: this.TableId,
      loading: isLoading,
      sortIcons: {
        desc: /*#__PURE__*/_react["default"].createElement(_consoleComponents.Icon, {
          style: {
            top: '4px',
            left: '7px'
          },
          type: 'arrow-down',
          size: "xxs"
        }),
        asc: /*#__PURE__*/_react["default"].createElement(_consoleComponents.Icon, {
          style: {
            top: '-4px',
            left: '7px'
          },
          type: 'arrow-up',
          size: "xxs"
        })
      },
      dataSource: dataSource
    }, config, {
      emptyContent: ResultemptyContent,
      rowSelection: rowSelection_
    }), groupHeader ? /*#__PURE__*/_react["default"].createElement(_consoleComponents.Table.GroupHeader, (0, _tslib.__assign)({}, groupHeader)) : null, groupFooter ? /*#__PURE__*/_react["default"].createElement(_consoleComponents.Table.GroupFooter, (0, _tslib.__assign)({}, groupFooter)) : null, renderColumsContent, actions ? /*#__PURE__*/_react["default"].createElement(_consoleComponents.Table.Column, (0, _tslib.__assign)({
      key: "action",
      width: actions.width,
      title: actions.title
    }, actions.props, {
      cell: function cell(value, index, data) {
        return _this.generateActions(value, index, data, actions);
      }
    })) : null), this.renderfooter(paginationConfig, batchActionContent));
  };

  return LPTable;
}(_react["default"].Component);

var _default = LPTable;
exports["default"] = _default;