'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = undefined;

var _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; };

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _EditButton = require('../Button/EditButton');

var _EditButton2 = _interopRequireDefault(_EditButton);

var _SaveButton = require('../Button/SaveButton');

var _SaveButton2 = _interopRequireDefault(_SaveButton);

var _AddButton = require('../Button/AddButton');

var _AddButton2 = _interopRequireDefault(_AddButton);

var _TimeButton = require('../Button/TimeButton');

var _TimeButton2 = _interopRequireDefault(_TimeButton);

var _hoc = require('../../hoc');

var _hoc2 = _interopRequireDefault(_hoc);

var _visualizations = require('../../visualizations');

var _board = require('./board');

var _board2 = _interopRequireDefault(_board);

var _CardSetting = require('../CardSetting');

var _CardSetting2 = _interopRequireDefault(_CardSetting);

var _util = require('../../util');

var _FormDialog = require('../FormDialog');

var _FormDialog2 = _interopRequireDefault(_FormDialog);

var _link = require('../../constant/link');

var _Hook = require('../Icon/Hook');

var _Hook2 = _interopRequireDefault(_Hook);

require('./DropMenu.less');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * Created by baoyinghai on 5/26/17.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */


var RcItem = function RcItem(props) {
  var className = props.isHit ? 'time-menu-item hit' : 'time-menu-item';
  return _react2.default.createElement(
    'div',
    { onClick: props.onClick, className: className },
    _react2.default.createElement(_Hook2.default, null),
    _react2.default.createElement(
      'span',
      { className: 'desc-wrapper' },
      props.desc
    )
  );
};

var DropDown = function DropDown(props) {
  var value = props.value,
      show = props.show,
      onHandleChange = props.onHandleChange,
      switchHandler = props.switchHandler;

  if (!show) return null;
  var handle = function handle(v) {
    return function () {
      switchHandler && switchHandler();
      onHandleChange && onHandleChange(v);
    };
  };
  return _react2.default.createElement(
    'div',
    { className: 'dashboard drop-down-wrapper' },
    _react2.default.createElement('div', { className: 'arrow-up' }),
    _react2.default.createElement(
      'div',
      { className: 'small-title' },
      '\u81EA\u52A8\u5237\u65B0\u95F4\u9694'
    ),
    _react2.default.createElement(RcItem, { isHit: value === 0, desc: '\u5173\u95ED', onClick: handle(0) }),
    _react2.default.createElement(RcItem, { isHit: value === 1, desc: '  1 \u5206\u949F', onClick: handle(1) }),
    _react2.default.createElement(RcItem, { isHit: value === 5, desc: '  5 \u5206\u949F', onClick: handle(5) }),
    _react2.default.createElement(RcItem, { isHit: value === 10, desc: '10 \u5206\u949F', onClick: handle(10) }),
    _react2.default.createElement(RcItem, { isHit: value === 15, desc: '15 \u5206\u949F', onClick: handle(15) }),
    _react2.default.createElement(RcItem, { isHit: value === 30, desc: '30 \u5206\u949F', onClick: handle(30) }),
    _react2.default.createElement(RcItem, { isHit: value === 60, desc: '60 \u5206\u949F', onClick: handle(60) })
  );
};

var DashBoard = function (_React$Component) {
  _inherits(DashBoard, _React$Component);

  function DashBoard() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, DashBoard);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = DashBoard.__proto__ || Object.getPrototypeOf(DashBoard)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      model: 'view',
      cards: _this.props.cards,
      querySql: '',
      panelDefinitionId: -1,
      showDropDown: false,
      freshTime: 0,
      builtInType: null
    }, _this.renderCards = function () {
      return _this.state.cards.map(function (card) {
        var Comp = _visualizations.Visualizations[card.chartType];
        if (!Comp) {
          console.error('comp is null');
        }
        if (_this.state.model === 'view') {
          Comp = _hoc2.default.layout(_hoc2.default.loadData(Comp));
        } else {
          Comp = [_hoc2.default.setable, _hoc2.default.loadData, _hoc2.default.layout, _hoc2.default.moveable].reduce(function (initValue, fn) {
            return fn(initValue);
          }, Comp);
        }
        return _react2.default.createElement(Comp, _extends({ key: card.index, freshTime: _this.state.freshTime, calculateHitBitBeside: _this.calculateHitBitBeside, updateLayout: _this.updateLayout, removeCard: _this.removeCard }, card, { setting: _visualizations.setting[card.chartType], updateSetting: _this.updateSetting }));
      });
    }, _this.calculateHitBitBeside = function (index) {
      return (0, _board.calculateHitBit)(_this.state.cards.filter(function (card) {
        return card.index !== index;
      }));
    }, _this.updateSetting = function (key, setting, title) {
      // chartSetting
      _this.setState({
        cards: _this.state.cards.map(function (card) {
          if (card.index === key) {
            card.chartSetting = setting;
            if (title) {
              card.title = title;
            }
          }
          return card;
        })
      }, function () {
        _this.setState({
          cardsList: _this.renderCards()
        });
      });
    }, _this.updateLayout = function (key, layout) {
      _this.setState({
        cards: _this.state.cards.map(function (card) {
          if (card.index === key) {
            card.layout = layout;
          }
          return card;
        })
      }, function () {
        _this.setState({
          cardsList: _this.renderCards()
        });
      });
    }, _this.removeCard = function (index) {
      _this.setState({
        cards: _this.state.cards.filter(function (card) {
          return card.index !== index;
        })
      }, function () {
        _this.setState({
          cardsList: _this.renderCards()
        });
      });
    }, _this.save = function () {
      _this.setState({
        model: 'view'
        // cards: [...this.state.cards]
      }, function () {
        _this.setState({
          cardsList: _this.renderCards()
        });
      });
      var updateCards = _this.props.updateCards;

      updateCards && updateCards(_this.state.cards);
      // save
    }, _this.create = function () {
      var self = _this;
      (0, _util.fetch)(_link.getPublicMetaData, {}, function (response) {
        var dataSource = response || [];
        var body = function body(props) {
          return _react2.default.createElement(_FormDialog2.default, {
            title: '\u6570\u636E\u6E90',
            dataSource: dataSource,
            submit: function submit(value) {
              if (value) {
                if (value.methodType === 1) {
                  var card = dataSource.filter(function (f) {
                    return f.panelDefinitionId === value.panelDefinitionId;
                  })[0];
                  self.addCards({
                    title: card.chartType || 'table',
                    layout: _extends({}, self.calculatePosition(8, 5), {
                      width: 8, height: 5
                    }),
                    chartType: card.chartType || 'table',
                    querySql: card.querySql,
                    chartSetting: {},
                    panelDefinitionId: value.panelDefinitionId,
                    builtInType: card.builtInType,
                    deptId: card.deptId,
                    publicType: card.publicType
                  });
                } else if (value.panelDefinitionId === -1) {
                  self.setState({ model: 'create', builtInType: null, querySql: '', panelDefinitionId: -1 });
                } else {
                  var tag = dataSource.filter(function (d) {
                    return d.panelDefinitionId === value.panelDefinitionId;
                  })[0];
                  self.setState({ model: 'create', builtInType: tag.builtInType, querySql: tag.querySql, panelDefinitionId: value.panelDefinitionId });
                }
              }
            },
            onClick: props.callback,
            createBottomButtons: props.createBottomButtons
          });
        };
        (0, _util.popModal)('卡片新增', body);
      }, function (error) {
        console.log(error);
        (0, _util.popAlert)('请求数据异常');
      });
    }, _this.cancel = function () {
      _this.setState({
        model: 'edit'
      });
    }, _this.showTime = function () {
      _this.showDropDown();
    }, _this._renderButtons = function () {
      var ret = [];
      if (_this.state.model === 'view') {
        ret.push(_react2.default.createElement(_EditButton2.default, { onClick: function onClick() {
            _this.setState({ model: 'edit' }, function () {
              _this.setState({
                cardsList: _this.renderCards()
              });
            });
            _this.props.switchNavBar(false);
          } }));
      } else if (_this.state.model === 'edit') {
        ret.push(_react2.default.createElement(_SaveButton2.default, { onClick: _this.save }));
        ret.push(_react2.default.createElement(_TimeButton2.default, { onClick: _this.showTime }));
        ret.push(_react2.default.createElement(_AddButton2.default, { onClick: _this.create }));
      }
      return ret;
    }, _this.addCards = function (newCard) {
      _this.setState({
        model: 'edit',
        cards: _this.state.cards.map(function (card, index) {
          card.index = index;
          return card;
        }).concat(newCard)
      }, function () {
        _this.setState({
          cardsList: _this.renderCards()
        });
      });
    }, _this.calculatePosition = function (width, height) {
      return (0, _board.calculatePosition)(width, height, _this.state.cards);
    }, _this.handleChange = function (v) {
      _this.setState({
        freshTime: v
      });
    }, _this.showDropDown = function () {
      _this.setState({
        showDropDown: !_this.state.showDropDown
      });
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(DashBoard, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var _this2 = this;

      if (this.state.model === 'view' && JSON.stringify(nextProps.cards) !== JSON.stringify(this.state.cards)) {
        this.setState({
          cards: nextProps.cards
        }, function () {
          _this2.setState({
            cardsList: _this2.renderCards()
          });
        });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      if (this.state.model === 'create') {
        return _react2.default.createElement(_CardSetting2.default, {
          builtInType: this.state.builtInType,
          querySql: this.state.querySql,
          cancel: this.cancel,
          addCards: this.addCards,
          calculatePosition: this.calculatePosition,
          panelDefinitionId: this.state.panelDefinitionId
        });
      }
      var DropDownMenu = (0, _util.closeWhileClickSpace)(DropDown, {
        defaultShow: this.state.showDropDown,
        querySelector: 'button-bar'
      });
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { className: 'button-bar' },
          this._renderButtons(),
          this.state.model === 'edit' && this.state.showDropDown && _react2.default.createElement(DropDownMenu, { value: this.state.freshTime, switchHandler: this.showDropDown, onHandleChange: this.handleChange })
        ),
        _react2.default.createElement(
          _board2.default,
          { model: this.state.model, cards: this.state.cards },
          this.state.cardsList
        )
      );
    }
  }]);

  return DashBoard;
}(_react2.default.Component);

exports.default = DashBoard;