import React, { Component } from 'react';
import PropTypes from 'prop-types';

const defaultCicle = 10;//默认到计时
/**
 *
 * 倒计时
 * @class TimerTool
 * @extends {Component}
 */
class TimerTool extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: defaultCicle,
      timeContent: defaultCicle + 's',
      showContent: true
    };
  }

  componentWillMount(){
    const { delayed } = this.props;
    delayed && this.setState({ time: delayed, timeContent: delayed + 's' });
  }

  componentDidMount() {
    this.count();
  }

  componentWillUnmount(){
    clearInterval(this.timer);
  }

  count = () => {
    clearInterval(this.timer);
    let { time: ti } = this.state;
    const { delayed } = this.props;
    let delayTime = delayed ? delayed : defaultCicle;
    this.timer = setInterval(() => {
      if (ti > 1) {
        ti = ti - 1;
        this.setState({ time: ti, timeContent: ti + 's' });
      } else {
        clearInterval(this.timer);
        this.setState({ time: delayTime, timeContent: delayTime + 's',showContent: false });
        const { autoClick } = this.props;
        autoClick && autoClick();
      }
    }, 1000);
  }

  initTime =()=>{
    clearInterval(this.timer);
    const { delayed } = this.props;
    let delayTime = delayed ? delayed : defaultCicle;
    this.setState({ time: delayTime, timeContent: delayTime + 's',showContent: false });
  }

  render() {
    let { timeContent,showContent } = this.state;
    return (
      <span style={{ color: '#ffc000' }}>{showContent ? `(${timeContent})` : ''}</span>
    );
  }
}

TimerTool.propTypes = {
  delayed: PropTypes.Object,
  autoClick: PropTypes.func
};
export default TimerTool;
