/**
 * Created by baoyinghai on 5/31/17.
 */
import React from 'react';
import { sqlApi } from '../constant/link';
import { fetch } from '../util';
import Loading from '../components/Icon/Loading';

const dataCache = {};

let freshTime = 0;
let timer = null;

const refreshData = () => {
  Object.keys(dataCache).forEach(key => {
    const params = key.split('&');
    fetch(sqlApi, {requestParamsBean: {sql: params[0], builtInType: params[1]}}, data => {
      if ('Process' === params[1]) {
        dataCache[key] = (data && data.contentList) || [];
      } else {
        dataCache[key] = data;
      }
    }, 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,
// };

export default Comp => class extends React.Component {

  state = {
    dataSource: [],
    error: false,
  };

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

  componentWillMount() {
    const { querySql, builtInType } = this.props;
    const cacheKey = querySql + '&' + builtInType;
    return new Promise((resolve, reject) => {
      if (dataCache[cacheKey]) {
        resolve(dataCache[cacheKey]);
      } else {
        fetch(sqlApi, { requestParamsBean: {sql: querySql, builtInType} }, response => {
          let data = response;
          if ('Process' === builtInType) {
            data = (response && response.contentList) || [];
          }
          dataCache[cacheKey] = [...data];
          resolve(data);
        }, reject);
      }
    }).then(response => {
      this.setState({
        dataSource: response || [],
        error: false
      });
    }).catch(error => {
      // console.error(JSON.stringify(error));
      dataCache[cacheKey] = [];
      this.setState({
        error: true
      });
    });
  }

  render() {
    if ((!this.state.dataSource || this.state.dataSource.length === 0) && !this.state.error) {
      return (
        <div className="loading-page"><Loading index={this.props.index} /></div>
      );
    }
    return (
      <Comp {...this.props} exception={this.state.error} dataSource={this.state.dataSource}/>
    );
  }
}