/**
 * Created by baoyinghai on 4/18/17.
 */
import React from 'react';
import { iconWrapper } from '../../framework/utils/IconHelper';

export default class BackTop extends React.Component {

  static defaultProps = {
    offset: 300
  };

  constructor(props) {
    super(props);
    this.refStr = 'back-to-top' + new Date().getTime();
  }

  _goToTop = e => {
    if (window.scrollTo) {
      window.scrollTo({ behavior: 'smooth', top: 0 });
    }
  };

  _showButton = e => {
    if (window.scrollY > this.props.offset) {
      const ele = document.getElementById(this.refStr);
      if (ele && !ele.style.display) {
        ele.style.display = 'block';
      }
    } else {
      const ele = document.getElementById(this.refStr);
      if (ele && ele.style.display) {
        ele.style.display = '';
      }
    }
  };

  componentDidMount() {
    window.addEventListener('scroll', this._showButton);
  }

  componentWillUnmount() {
    window.addEventListener('scroll', this._showButton);
  }


  render() {
    const { className = '', style = {}, size = 36 } = this.props;
    return (
      <div id={this.refStr} className={'back-to-top ' + className} onClick={this._goToTop}>
        {iconWrapper('icon-icobacktop', undefined, undefined, undefined, Object.assign({}, style, { fontSize: size + 'px' }))}
      </div>
    );
  }
}
