import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { deepEqual } from 'amos-tool';
/**
 * InitReuestRemoteApi
 *
 * @class InitReuestRemoteApi
 * @extends {Component}
 */
class InitReuestRemoteApi extends Component {

  static propTypes = {
    tableAction: PropTypes.func,
    innerParamsValue: PropTypes.object,
    otherValue: PropTypes.any,
    onSuccess: PropTypes.func,
    onBefore: PropTypes.func,
    onError: PropTypes.func,
    initRequest: PropTypes.bool,
    reloadKey: PropTypes.any
  };

  static defaultProps = {
    onError() { },
    onBefore() { },
    onSuccess() { }
  };

  constructor(props) {
    super(props);
    this.initRequest = true;
    this.state = {

    };
  }

  componentDidMount() {
    const { initRequest } = this.props;
    initRequest && this.onInit();
  }

  componentDidUpdate(prevProps) {
    if (this.props.reloadKey !== prevProps.reloadKey) {
      this.onInit();
    }
    if (!deepEqual(this.props.otherValue, prevProps.otherValue)) {
      this.onInit();
    }
  }

  isGlobalChange = (globalValue = {}, newGlobalValue = {}, refreshGlobals) => {
    return refreshGlobals.some(e => {
      if (!deepEqual(globalValue[e], newGlobalValue[e])) {
        return true;
      }
      return false;
    });
  }


  onInit = () => {
    const { innerParamsValue, tableAction, otherValue, onSuccess, onBefore, onError } = this.props;
    onBefore && onBefore();
    tableAction(innerParamsValue, otherValue).then((data) => {
      onSuccess(data, this.initRequest);
      this.initRequest = false;
    }).catch(onError);
  }

  render() {
    return null;
  }
}

export default InitReuestRemoteApi;
