'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 _class, _temp, _initialiseProps; /**
                                      * Created by baoyinghai on 5/31/17.
                                      */


var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _SaveButton2 = _interopRequireDefault(_SaveButton);

var _CancelButton = require('../Button/CancelButton');

var _CancelButton2 = _interopRequireDefault(_CancelButton);

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

var _SettingButton = require('../Button/SettingButton');

var _SettingButton2 = _interopRequireDefault(_SettingButton);

var _Arrow = require('../Icon/Arrow');

var _Arrow2 = _interopRequireDefault(_Arrow);

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

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

var _SQLEditor = require('../SQLEditor');

var _SQLEditor2 = _interopRequireDefault(_SQLEditor);

var _Setting = require('../Setting');

var _Setting2 = _interopRequireDefault(_Setting);

require('./CardSetting.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; }

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

  if (!show) return null;
  return _react2.default.createElement(
    'div',
    { className: 'drop-down-wrapper' },
    _react2.default.createElement('div', { className: 'arrow-up' }),
    items.map(function (v) {
      return _react2.default.createElement(
        'div',
        { className: v === value ? 'item is-focus' : 'item', onClick: function onClick() {
            var onHandleChange = props.onHandleChange,
                switchHandler = props.switchHandler;

            switchHandler && switchHandler();
            onHandleChange && onHandleChange(v);
          } },
        v.toLocaleUpperCase()
      );
    })
  );
};

var CardSetting = (_temp = _class = function (_React$Component) {
  _inherits(CardSetting, _React$Component);

  function CardSetting(props) {
    _classCallCheck(this, CardSetting);

    var _this = _possibleConstructorReturn(this, (CardSetting.__proto__ || Object.getPrototypeOf(CardSetting)).call(this, props));

    _initialiseProps.call(_this);

    _this.querySql = _this.props.querySql;
    _this.sqlModify = false;
    return _this;
  }

  _createClass(CardSetting, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.fetchData(true);
      this.setState({ containerHeight: window.innerHeight - 250 });
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var Comp = _visualizations.Visualizations[this.state.visualizationName];
      var DropDownMenu = (0, _util.closeWhileClickSpace)(DropDown, {
        defaultShow: this.state.showDropDown,
        querySelector: 'select-group'
      });
      var width = window.innerWidth - 70;
      var height = this.state.containerHeight - 30;
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { className: 'button-bar' },
          this._renderButtons()
        ),
        _react2.default.createElement(_SQLEditor2.default, { setSqlStr: this.setSqlStr, sqlStr: this.querySql }),
        _react2.default.createElement(
          'div',
          { className: 'card-setting-wrapper' },
          _react2.default.createElement(
            'div',
            { className: 'select-group' },
            this.renderVisualization(),
            _react2.default.createElement(
              'div',
              { onClick: this.showDropDown, className: 'arrow-wrapper' },
              _react2.default.createElement(_Arrow2.default, null)
            ),
            _react2.default.createElement(DropDownMenu, { value: this.state.visualizationName, switchHandler: this.showDropDown, items: Object.keys(_visualizations.Visualizations), onHandleChange: this.handleChange })
          ),
          _visualizations.setting[this.state.visualizationName] && _react2.default.createElement(_SettingButton2.default, { style: { float: 'left', marginTop: '-4px' }, onClick: this.popSettingModel }),
          _react2.default.createElement(
            'a',
            { className: 'run-button', onClick: function onClick(e) {
                return _this2.fetchData();
              } },
            this.state.buttonDesc
          ),
          _react2.default.createElement(
            'div',
            { className: 'chart-create-container', style: { height: this.state.containerHeight + 'px' } },
            this.state.dataSource.length > 0 && Comp ? _react2.default.createElement(Comp, { chartSetting: this.state.chartSetting, dataSource: this.state.dataSource, width: width, height: height }) : _react2.default.createElement(
              'div',
              { style: { width: width, height: height, lineHeight: height + 'px' } },
              '\u6CA1\u6709\u6570\u636E'
            )
          )
        )
      );
    }
  }]);

  return CardSetting;
}(_react2.default.Component), _initialiseProps = function _initialiseProps() {
  var _this3 = this;

  this.state = {
    visualizationName: 'table',
    buttonDesc: '刷新数据',
    dataSource: [],
    chartSetting: {},
    showDropDown: false,
    containerHeight: 400
  };

  this.handleChange = function (value) {
    _this3.setState({
      visualizationName: value
    });
  };

  this.fetchData = function (isInit) {
    var self = _this3;
    var sqlStr = self.querySql;
    var builtInType = self.props.builtInType;
    if (sqlStr) {
      (0, _util.fetch)(_link.sqlApi, { requestParamsBean: { sql: sqlStr, builtInType: builtInType } }, function (response) {
        console.log(response);
        var data = response;
        if ('Process' === builtInType) {
          data = response && response.contentList || [];
        }
        self.sqlModify = false;
        _this3.setState({
          dataSource: data || [],
          chartSetting: {}
        });
      }, function (error) {
        (0, _util.popAlert)(error);
      });
    } else {
      !isInit && (0, _util.popAlert)('请输入sql语句查询数据');
    }
  };

  this.updateSetting = function (key, setting, title) {
    _this3.setState({
      chartSetting: setting,
      title: title
    });
  };

  this.popSettingModel = function () {
    if (!_this3.state.dataSource || _this3.state.dataSource.length === 0) {
      (0, _util.popAlert)('请选择数据源！');
    } else {
      (function () {
        var settingProps = _visualizations.setting[_this3.state.visualizationName];
        var body = function body(props) {
          return _react2.default.createElement(_Setting2.default, _extends({}, settingProps, { title: _this3.props.title, chartSetting: _this3.state.chartSetting, index: -1, updateSetting: _this3.updateSetting, onClick: props.callback, createBottomButtons: props.createBottomButtons, dataSource: _this3.state.dataSource }));
        };
        (0, _util.popModal)(_this3.state.visualizationName, body);
      })();
    }
  };

  this.showDropDown = function () {
    _this3.setState({
      showDropDown: !_this3.state.showDropDown
    });
  };

  this.renderVisualization = function () {
    return _react2.default.createElement(
      'a',
      { className: 'visualization-label', onClick: _this3.showDropDown },
      _this3.state.visualizationName.toLocaleUpperCase()
    );
  };

  this.calculatePosition = function (width, height) {
    var calculatePosition = _this3.props.calculatePosition;

    return calculatePosition(width, height);
  };

  this.save = function () {
    // TODO: 是否可以保存
    if (_this3.sqlModify) {
      (0, _util.popAlert)('sql语句变更，请刷新数据！');
      return;
    }
    if (_this3.querySql) {
      _this3.props.addCards({
        title: _this3.state.title || _this3.state.visualizationName,
        layout: _extends({}, _this3.calculatePosition(8, 5), {
          width: 8, height: 5
        }),
        chartType: _this3.state.visualizationName,
        querySql: _this3.querySql,
        chartSetting: _this3.state.chartSetting,
        panelDefinitionId: _this3.props.panelDefinitionId,
        builtInType: _this3.props.builtInType
      });
    } else {
      _this3.props.cancel();
    }
  };

  this._renderButtons = function () {
    var ret = [];
    ret.push(_react2.default.createElement(_SaveButton2.default, { onClick: _this3.save }));
    ret.push(_react2.default.createElement(_CancelButton2.default, { onClick: _this3.props.cancel }));
    return ret;
  };

  this.setSqlStr = function (value) {
    _this3.querySql = value;
    _this3.sqlModify = true;
  };
}, _temp);
exports.default = CardSetting;