import _objectSpread from "@babel/runtime/helpers/esm/objectSpread";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";

/**
 * fixTable.jsx
 *
 * @Author: apple
 * @Date: 2017/12/29 00:19
 */
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import easyToMap from '../util/easyToMap';
import ChevronRight from '../icons/internals/ChevronRight';
import ExpandMore from '../icons/internals/ExpandMore';
import TableHeader from './TableHeader';
import TableTbody from './TableTbody';
import ColGroup from './colGroup';
import TableHeaderRow from './TableHeaderRow';
import pubsub from '../util/observer';
import merge from '../util/merge';
import Checkbox from '../checkbox';
/**
 * @ignore
 * */

var ItemTable =
/*#__PURE__*/
function (_React$Component) {
  _inherits(ItemTable, _React$Component);

  function ItemTable(props, context) {
    var _this;

    _classCallCheck(this, ItemTable);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(ItemTable).call(this, props, context));

    _defineProperty(_assertThisInitialized(_this), "handleMouseOn", function () {
      var _this$props = _this.props,
          position = _this$props.position,
          activeMouse = _this$props.activeMouse;
      activeMouse(position);
    });

    _defineProperty(_assertThisInitialized(_this), "handleBodyScrollPosition", function (e) {
      var _this$props2 = _this.props,
          handleBodyScrollVertical = _this$props2.handleBodyScrollVertical,
          position = _this$props2.position;
      var target = e.target;

      var _assertThisInitialize = _assertThisInitialized(_this),
          thead = _assertThisInitialize.thead,
          scrollTbody = _assertThisInitialize.scrollTbody;

      if (target.scrollLeft !== _this.lastScrollLeft) {
        if (target === scrollTbody && thead) {
          thead.scrollLeft = target.scrollLeft;
        } else if (target === thead && scrollTbody) {
          scrollTbody.scrollLeft = target.scrollLeft;
        }
      }

      _this.lastScrollLeft = target.scrollLeft;

      if (e.target.className !== 'ne-table-item-header') {
        handleBodyScrollVertical && handleBodyScrollVertical(e, position);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleBtnListener", function (event, id, type) {
      var _this$props3 = _this.props,
          dataSource = _this$props3.dataSource,
          checkboxCallback = _this$props3.checkboxCallback;

      var idArray = _toConsumableArray(_this.state[type]);

      var isContainId = idArray.filter(function (item) {
        return id === item;
      }).length;
      var idArrayLen = idArray.length;
      var dataSourceLen = dataSource.length;

      if (id === 'header') {
        if (idArrayLen === 0 || idArrayLen > 0 && idArrayLen < dataSourceLen) {
          idArray = dataSourceLen ? easyToMap(dataSourceLen) : ['all'];
        } else {
          idArray = [];
        }
      } else if (isContainId) {
        idArray.forEach(function (item, index) {
          if (item === id) {
            idArray.splice(index, 1);
          }
        });
      } else {
        idArray.push(id);
      }

      _this.setState(_defineProperty({}, type, idArray));

      if (type === 'checkboxArray') {
        checkboxCallback(_this.state.data.filter(function (item, index) {
          var bool = false;
          idArray.forEach(function (id) {
            if (id === index) {
              bool = true;
            }
          });
          return bool;
        }));
      }
    });

    _defineProperty(_assertThisInitialized(_this), "initTableColumns", function () {
      var _this$props4 = _this.props,
          checkbox = _this$props4.checkbox,
          columns = _this$props4.columns,
          dataSource = _this$props4.dataSource,
          position = _this$props4.position,
          expandOpt = _this$props4.expandOpt,
          children = _this$props4.children;
      var _this$state = _this.state,
          checkboxArray = _this$state.checkboxArray,
          expandRowIds = _this$state.expandRowIds;
      var renderColumns = merge(columns);
      _this.rules = []; // 展开类型

      var showExpand = expandOpt && expandOpt.display && position !== 'right' || children;

      if (showExpand) {
        var expandBtn = function expandBtn(id) {
          var filterArray = expandRowIds.filter(function (item) {
            return item - 1 === id;
          });
          var type = filterArray.length ? 'down-arrow' : 'right-arrow';
          var Component = filterArray.length ? ExpandMore : ChevronRight;
          var icon = React.createElement(Component, {
            style: {
              userSelect: 'none'
            }
          });

          if ((expandOpt || children).display) {
            icon = (expandOpt || children).expandIcon;

            if (filterArray.length) {
              icon = (expandOpt || children).shrinkIcon;
            }
          }

          return icon;
        };

        renderColumns.unshift({
          key: 'expandBtn',
          width: 50,
          renderHeader: function renderHeader() {
            return React.createElement("div", null);
          },
          render: expandBtn
        });
      } // 多选框


      if (checkbox) {
        var checkElm = function checkElm(id) {
          var checked = '';

          if (checkboxArray.length === dataSource.length && checkboxArray.length) {
            checked = 'checked';
          } else {
            var filterArray = checkboxArray.filter(function (item) {
              return item === id;
            });
            checked = filterArray.length ? 'checked' : '';
          }

          return React.createElement(Checkbox, {
            checked: checked,
            onChange: function onChange(event) {
              return _this.handleBtnListener(event, id, 'checkboxArray');
            }
          });
        };

        renderColumns.unshift({
          key: 'checkbox',
          width: 50,
          renderHeader: checkElm,
          render: checkElm
        });
      }

      renderColumns.forEach(function (item) {
        _this.rules.push(item.key);
      });
      return renderColumns;
    });

    _defineProperty(_assertThisInitialized(_this), "handleSetSort", function (key, id) {
      var _this$props5 = _this.props,
          columns = _this$props5.columns,
          onSort = _this$props5.onSort,
          checkbox = _this$props5.checkbox,
          expandOpt = _this$props5.expandOpt,
          children = _this$props5.children;

      var sortState = _objectSpread({}, _this.state.sortState);

      var nextType = '';

      switch (_this.state.sortState[key]) {
        case 'sort':
          nextType = 'sort-down';
          break;

        case 'sort-down':
          nextType = 'sort-up';
          break;

        case 'sort-up':
          nextType = 'sort';
          break;

        default:
          return;
      }

      Object.keys(sortState).forEach(function (item) {
        sortState[item] = 'sort';
      });
      sortState[key] = nextType;

      if (checkbox) {
        id -= 1;
      }

      if (expandOpt && expandOpt.display || children && children.display) {
        id -= 1;
      }

      _this.setState({
        sortState: _objectSpread({}, sortState, _defineProperty({}, key, nextType))
      }, function () {
        onSort && onSort(columns[id], nextType);
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleInnerScrollEvent", function (elm) {
      var _this$props6 = _this.props,
          handleInnerScrollEvent = _this$props6.handleInnerScrollEvent,
          tbodyRef = _this$props6.tbodyRef;
      tbodyRef && tbodyRef(elm);
      _this.scrollTbody = elm;
      handleInnerScrollEvent && handleInnerScrollEvent(elm);
    });

    _defineProperty(_assertThisInitialized(_this), "getTableRef", function (el) {
      var tableRef = _this.props.tableRef;
      _this.tableItemRef = el;
      tableRef && tableRef(el);
    });

    var _this$props7 = _this.props,
        _dataSource = _this$props7.dataSource,
        _columns = _this$props7.columns;
    var _sortState = {};
    _this.rules = [];

    _columns.forEach(function (item) {
      var sort = item.sort,
          key = item.key;

      if (sort) {
        _sortState[key] = 'sort';
      }
    });

    _this.pubsubEvent = [];
    _this.state = {
      showExpandContent: [],
      checkboxArray: [],
      expandRowIds: [],
      data: _dataSource,
      rowHeightArray: [],
      tdWidthArray: [],
      expandSumRow: 0,
      sortState: _objectSpread({}, _sortState)
    };
    return _this;
  }

  _createClass(ItemTable, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var scroll = this.props.scroll;

      if (scroll.y) {
        this.scrollTbody.addEventListener('scroll', this.handleBodyScrollPosition, false);
        this.scrollTbody.addEventListener('mouseover', this.handleMouseOn, false);
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _this$props8 = this.props,
          dataSource = _this$props8.dataSource,
          scrollTop = _this$props8.scrollTop,
          columns = _this$props8.columns;

      if (JSON.stringify(dataSource) !== JSON.stringify(nextProps.dataSource)) {
        this.setState({
          data: nextProps.dataSource,
          expandRowIds: [],
          checkboxArray: []
        });
      }

      if (JSON.stringify(columns) !== JSON.stringify(nextProps.columns)) {
        var sortState = {};
        nextProps.columns.forEach(function (item) {
          var sort = item.sort,
              key = item.key;

          if (sort) {
            sortState[key] = 'sort';
          }
        });
        this.setState({
          sortState: _objectSpread({}, sortState)
        });
      }

      if (nextProps.scrollTop !== scrollTop) {
        this.scrollTbody.scrollTop = nextProps.scrollTop;
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      for (var item in this.pubsubEvent) {
        pubsub.unsubscribe(item);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props9 = this.props,
          position = _this$props9.position,
          onClickTh = _this$props9.onClickTh,
          styles = _this$props9.styles,
          textCenter = _this$props9.textCenter,
          prefixCls = _this$props9.prefixCls,
          hideTableTitle = _this$props9.hideTableTitle,
          stripe = _this$props9.stripe,
          columnsId = _this$props9.columnsId,
          shouldScroll = _this$props9.shouldScroll,
          scroll = _this$props9.scroll,
          theadRef = _this$props9.theadRef,
          tbodyRef = _this$props9.tbodyRef,
          tdWidthArray = _this$props9.tdWidthArray,
          warpWidth = _this$props9.warpWidth,
          rowHeightArray = _this$props9.rowHeightArray,
          scrollBarWidth = _this$props9.scrollBarWidth,
          allBorder = _this$props9.allBorder,
          warpBorder = _this$props9.warpBorder,
          handleMouseEnter = _this$props9.handleMouseEnter,
          handleMouseLeave = _this$props9.handleMouseLeave,
          checkbox = _this$props9.checkbox,
          baseHeaderHeight = _this$props9.baseHeaderHeight,
          expandOpt = _this$props9.expandOpt,
          children = _this$props9.children,
          mainTbody = _this$props9.mainTbody,
          pubsubEventString = _this$props9.pubsubEventString,
          hover = _this$props9.hover,
          noDataRender = _this$props9.noDataRender,
          theadRowRef = _this$props9.theadRowRef,
          showFixTable = _this$props9.showFixTable,
          mainDataSource = _this$props9.mainDataSource,
          containerWidth = _this$props9.width;
      var _this$state2 = this.state,
          data = _this$state2.data,
          expandRowIds = _this$state2.expandRowIds,
          sortState = _this$state2.sortState,
          tbodyScroll = _this$state2.tbodyScroll;
      var renderColumns = this.initTableColumns(); // 赋予固定栏整体宽度

      var innerTableWidth = 0;

      var renderStyle = _objectSpread({}, styles);

      if (position === 'left' || position === 'right') {
        columnsId.forEach(function (id) {
          if (position === 'left') {
            if (checkbox) {
              innerTableWidth += 50;
            }

            if (expandOpt && expandOpt.display || children && children.display) {
              innerTableWidth += 50;
            }
          }

          if (tdWidthArray[id]) {
            innerTableWidth += tdWidthArray[id];
          }
        });
        var width = innerTableWidth;

        if (position === 'right') {
          width = scrollBarWidth && shouldScroll ? innerTableWidth + scrollBarWidth - 1 : innerTableWidth - 1;
        }

        renderStyle.width = width;
      } else {
        renderStyle.width = scrollBarWidth || shouldScroll ? containerWidth : containerWidth + scrollBarWidth;
      }

      var tableClassName = classNames("".concat(prefixCls, "-").concat(position, "-fixed"), {
        'ne-table-exist-scroll-y': scroll.y && allBorder && !warpBorder,
        'ne-table-visible': showFixTable && position !== 'main',
        'ne-table-hidden': !showFixTable && position !== 'main'
      });
      var theadClassName = classNames("".concat(prefixCls, "-thead"), {
        'ne-table-border-none': position === 'right' || position === 'left'
      }, {
        'display-none': hideTableTitle
      });
      var tbodyClassName = classNames("".concat(prefixCls, "-tbody"), {
        'ne-table-border-none': position === 'right' || position === 'left'
      });
      var headerStyle = {
        overflowY: 'scroll',
        overflowX: position === 'main' && shouldScroll ? 'auto' : 'hidden'
      };

      if (scroll.y) {
        if (position === 'main') {
          headerStyle.maxHeight = scroll.y;
        } else {
          headerStyle.maxHeight = +scroll.y.split('px')[0] - 15;

          if (!scrollBarWidth || !shouldScroll) {
            headerStyle.maxHeight = +scroll.y.split('px')[0];
          }
        }
      } else {
        headerStyle.overflowY = 'hidden';
      }

      var selfPrefixCls = "".concat(prefixCls, "-item");
      var theadProps = {
        theadClassName: theadClassName,
        renderColumns: renderColumns,
        handleSetSort: this.handleSetSort,
        sortState: sortState,
        onClickTh: onClickTh,
        textCenter: textCenter,
        tdWidthArray: tdWidthArray,
        warpWidth: warpWidth,
        position: position,
        prefixCls: selfPrefixCls,
        scroll: tbodyScroll,
        tableHeaderRowRef: function tableHeaderRowRef(el) {
          theadRowRef && theadRowRef(el);
          _this2.theadRow = el;
        },
        tableHeaderRef: function tableHeaderRef(el) {
          theadRef && theadRef(el);
          _this2.thead = el;
        },
        width: renderStyle.width,
        height: baseHeaderHeight,
        handleBodyScrollLeft: this.handleBodyScrollPosition
      };
      var tableHeaderRowProps = Object.assign({}, theadProps);
      var tbodyProps = {
        tbodyClassName: tbodyClassName,
        data: data,
        expandRowIds: expandRowIds,
        renderColumns: renderColumns,
        selfPrefixCls: selfPrefixCls,
        stripe: stripe,
        rowHeightArray: rowHeightArray,
        position: position,
        tableTbodyRef: function tableTbodyRef(el) {
          tbodyRef && tbodyRef(el);
          _this2.tbody = el;
        },
        handleBodyScrollLeft: this.handleBodyScrollPosition,
        rules: this.rules,
        handleMouseEnter: handleMouseEnter,
        handleMouseLeave: handleMouseLeave,
        mainTbody: mainTbody,
        pubsubEventString: pubsubEventString,
        expandOpt: expandOpt,
        children: children,
        checkbox: checkbox,
        hover: hover,
        noDataRender: noDataRender,
        mainDataSource: mainDataSource
      };
      return React.createElement("div", {
        className: tableClassName,
        ref: this.getTableRef
      }, scroll.y && React.createElement(TableHeader, theadProps), React.createElement("div", {
        className: "".concat(selfPrefixCls, "-tbody"),
        style: headerStyle,
        ref: this.handleInnerScrollEvent
      }, React.createElement("table", {
        style: renderStyle
      }, React.createElement(ColGroup, {
        renderColumns: renderColumns
      }), !scroll.y && React.createElement(TableHeaderRow, tableHeaderRowProps), React.createElement(TableTbody, tbodyProps))));
    }
  }]);

  return ItemTable;
}(React.Component);

_defineProperty(ItemTable, "propTypes", {
  expandOpt: PropTypes.object,
  children: PropTypes.object,
  expandRender: PropTypes.func
});

_defineProperty(ItemTable, "defaultProps", {
  expandRender: function expandRender() {
    return React.createElement("div", null, "\u5C55\u5F00\u680F");
  }
});

export default ItemTable;