"use strict";

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); }

var _reactDndHtml5Backend = _interopRequireDefault(require("react-dnd-html5-backend"));

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

var _reactDom = _interopRequireDefault(require("react-dom"));

var _ = _interopRequireDefault(require(".."));

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

var _reactDnd = require("react-dnd");

var _excluded = ["isDragging", "isOver", "connectDragSource", "connectDropTarget", "moveRow", "className"],
    _excluded2 = ["excludeProvider"];

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

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _extends() { _extends = Object.assign || 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(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 _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; }

var _ref = _["default"],
    SelectionRow = _ref.SelectionRow;
var dragingIndex = -1;

function MyRow(props) {
  var _classnames;

  var isDragging = props.isDragging,
      isOver = props.isOver,
      connectDragSource = props.connectDragSource,
      connectDropTarget = props.connectDropTarget,
      moveRow = props.moveRow,
      className = props.className,
      others = _objectWithoutProperties(props, _excluded);

  var opacity = isDragging ? 0 : 1;

  var style = _objectSpread(_objectSpread({}, others.style), {}, {
    cursor: 'move'
  });

  var cls = (0, _classnames2["default"])((_classnames = {}, _defineProperty(_classnames, className, className), _defineProperty(_classnames, 'drop-over-upward', isOver && others.index < dragingIndex), _defineProperty(_classnames, 'drop-over-downward', isOver && others.index > dragingIndex), _classnames));
  return /*#__PURE__*/_react["default"].createElement(SelectionRow, _extends({}, others, {
    style: _objectSpread(_objectSpread({}, style), {
      opacity: opacity
    }),
    className: cls,
    wrapper: function wrapper(row) {
      return connectDragSource(connectDropTarget(row));
    }
  }));
}

var NewRow = (0, _reactDnd.DropTarget)('row', {
  drop: function drop(props, monitor) {
    var dragIndex = monitor.getItem().index;
    var hoverIndex = props.index;

    if (dragIndex === hoverIndex) {
      return;
    }

    props.moveRow(dragIndex, hoverIndex);
    monitor.getItem().index = hoverIndex;
  }
}, function (connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver()
  };
})((0, _reactDnd.DragSource)('row', {
  beginDrag: function beginDrag(props) {
    dragingIndex = props.index;
    return {
      id: props.record[props.primaryKey],
      index: props.rowIndex
    };
  }
}, function (connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging()
  };
})(MyRow));

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

  var _super = _createSuper(InnerTable);

  function InnerTable(props) {
    var _this;

    _classCallCheck(this, InnerTable);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "moveRow", function (dragIndex, hoverIndex) {
      var onSort = _this.props.onSort;
      var dragRow = _this.state.dataSource[dragIndex];

      var dataSource = _toConsumableArray(_this.state.dataSource);

      dataSource.splice(dragIndex, 1);
      dataSource.splice(hoverIndex, 0, dragRow);

      _this.setState({
        dataSource: dataSource
      });

      onSort && onSort(_this.state.dataSource);
    });

    _this.state = {
      dataSource: _toConsumableArray(props.dataSource)
    };
    return _this;
  }

  _createClass(InnerTable, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.dataSource && JSON.stringify(nextProps.dataSource) !== JSON.stringify(this.state.dataSource)) {
        this.setState({
          dataSource: _toConsumableArray(nextProps.dataSource)
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          excludeProvider = _this$props.excludeProvider,
          restProps = _objectWithoutProperties(_this$props, _excluded2); // eslint-disable-line


      var tableProps = _objectSpread(_objectSpread({}, restProps), {}, {
        dataSource: this.state.dataSource,
        rowProps: function rowProps(props, index) {
          return {
            index: index,
            moveRow: _this2.moveRow
          };
        },
        components: {
          Row: NewRow
        }
      });

      return /*#__PURE__*/_react["default"].createElement(_["default"], tableProps);
    }
  }]);

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

var SortableTable = /*#__PURE__*/function (_React$Component2) {
  _inherits(SortableTable, _React$Component2);

  var _super2 = _createSuper(SortableTable);

  function SortableTable() {
    _classCallCheck(this, SortableTable);

    return _super2.apply(this, arguments);
  }

  _createClass(SortableTable, [{
    key: "render",
    value: function render() {
      var ComponentName = (0, _reactDnd.DragDropContext)(_reactDndHtml5Backend["default"])(InnerTable);
      return /*#__PURE__*/_react["default"].createElement(ComponentName, this.props);
    }
  }]);

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

var result = [{
  id: '001',
  time: 1951,
  title: {
    name: 'The Old Man and the Sea'
  }
}, {
  id: '002',
  time: 1925,
  title: {
    name: 'the great gatsby'
  }
}, {
  id: '003',
  time: 1719,
  title: {
    name: 'The adventures of Robinson Crusoe'
  }
}];

var Demo = /*#__PURE__*/function (_React$Component3) {
  _inherits(Demo, _React$Component3);

  var _super3 = _createSuper(Demo);

  function Demo() {
    var _this3;

    _classCallCheck(this, Demo);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this3 = _super3.call.apply(_super3, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this3), "state", {
      dataSource: result
    });

    _defineProperty(_assertThisInitialized(_this3), "onRemove", function (id) {
      var dataSource = _this3.state.dataSource;
      var index = -1;
      dataSource.forEach(function (item, i) {
        if (item.id === id) {
          index = i;
        }
      });

      if (index !== -1) {
        dataSource.splice(index, 1);

        _this3.setState({
          dataSource: dataSource
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this3), "renderOper", function (value, index, record) {
      return /*#__PURE__*/_react["default"].createElement("a", {
        onClick: _this3.onRemove.bind(_assertThisInitialized(_this3), record.id)
      }, "Remove(", record.id, ")");
    });

    return _this3;
  }

  _createClass(Demo, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(SortableTable, {
        dataSource: this.state.dataSource,
        onSort: console.log
      }, /*#__PURE__*/_react["default"].createElement(_["default"].Column, {
        title: "Id",
        dataIndex: "id",
        width: 100,
        lock: true
      }), /*#__PURE__*/_react["default"].createElement(_["default"].Column, {
        title: "Title",
        dataIndex: "title.name",
        width: 400
      }), /*#__PURE__*/_react["default"].createElement(_["default"].Column, {
        title: "Time",
        dataIndex: "time",
        width: 300
      }), /*#__PURE__*/_react["default"].createElement(_["default"].Column, {
        title: "operate",
        cell: this.renderOper,
        width: 300,
        lock: "right"
      })));
    }
  }]);

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

_reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(Demo, null), document.getElementById('table-demo-27'));