'use strict';

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

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 _link = require('../constant/link');

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

var _Loading = require('../components/Icon/Loading');

var _Loading2 = _interopRequireDefault(_Loading);

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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/31/17.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */


var dataCache = {};

var freshTime = 0;
var timer = null;

var refreshData = function refreshData() {
  Object.keys(dataCache).forEach(function (key) {
    var params = key.split('&');
    (0, _util.fetch)(_link.sqlApi, { requestParamsBean: { sql: params[0], builtInType: params[1] } }, function (data) {
      if ('Process' === params[1]) {
        dataCache[key] = data && data.contentList || [];
      } else {
        dataCache[key] = data;
      }
    }, function (err) {
      console.log(err);
    });
  });
};

// const queryBean = {
// pageIndex: null,
// itemsPerPage:null,
// requestParamsBean: {sql:, builtInType:’’ },
// requestFilterFields: this.state.requestFilterFields,
// requestOrderFields: this.state.orderFields,
// isAdvance: this.state.isAdvance,
// };

exports.default = function (Comp) {
  return function (_React$Component) {
    _inherits(_class2, _React$Component);

    function _class2() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, _class2);

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

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = _class2.__proto__ || Object.getPrototypeOf(_class2)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
        dataSource: [],
        error: false
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    _createClass(_class2, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps) {
        if (!isNaN(nextProps.freshTime)) {
          if (freshTime !== nextProps.freshTime) {
            if (timer) {
              window.clearInterval(timer);
            }
            freshTime = nextProps.freshTime;
            if (freshTime) {
              timer = window.setInterval(refreshData, freshTime * 1000 * 60);
            }
          }
        }
      }
    }, {
      key: 'componentWillMount',
      value: function componentWillMount() {
        var _this2 = this;

        var _props = this.props,
            querySql = _props.querySql,
            builtInType = _props.builtInType;

        var cacheKey = querySql + '&' + builtInType;
        return new Promise(function (resolve, reject) {
          if (dataCache[cacheKey]) {
            resolve(dataCache[cacheKey]);
          } else {
            (0, _util.fetch)(_link.sqlApi, { requestParamsBean: { sql: querySql, builtInType: builtInType } }, function (response) {
              var data = response;
              if ('Process' === builtInType) {
                data = response && response.contentList || [];
              }
              dataCache[cacheKey] = [].concat(_toConsumableArray(data));
              resolve(data);
            }, reject);
          }
        }).then(function (response) {
          _this2.setState({
            dataSource: response || [],
            error: false
          });
        }).catch(function (error) {
          // console.error(JSON.stringify(error));
          dataCache[cacheKey] = [];
          _this2.setState({
            error: true
          });
        });
      }
    }, {
      key: 'render',
      value: function render() {
        if ((!this.state.dataSource || this.state.dataSource.length === 0) && !this.state.error) {
          return _react2.default.createElement(
            'div',
            { className: 'loading-page' },
            _react2.default.createElement(_Loading2.default, { index: this.props.index })
          );
        }
        return _react2.default.createElement(Comp, _extends({}, this.props, { exception: this.state.error, dataSource: this.state.dataSource }));
      }
    }]);

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