import * as React from 'react';
import { Props, State } from './type';

export default class CountDown extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  public componentWillReceiveProps(props) {
    this.refresh(props)
  }

  public componentDidMount() {
    this.refresh(this.props)
  }

  public refresh(props){
    const {startTime, endTime} = props;
    if(!startTime || !endTime) return;
    const nowDate = new Date();
    const isStart = nowDate >= startTime;
    const isEnd = nowDate > endTime;

    this.setState({
      isStart,
      isEnd
    })

    if(isStart && !isEnd){
      const refreshTime = () => {
        let countDown = this.countDown(startTime, endTime)
        this.setState({
          countDown
        })
      }
      refreshTime()
      setInterval(()=>refreshTime(), 1000)
    }
  }

  public countDown(startTime, endTime){
    let endDate = new Date(endTime);
    //当前时间
    let nowDate = new Date();
    if(nowDate > endDate){
      return 'end'
    }else if(nowDate < startTime){
      return 'notStart'
    }
    //相差的总秒数
    let totalSeconds = parseInt((endDate - nowDate) / 1000);
    //天数
    let days = Math.floor(totalSeconds / (60 * 60 * 24));
    //取模（余数）
    let modulo = totalSeconds % (60 * 60 * 24);
    //小时数
    let hours = Math.floor(modulo / (60 * 60));
    modulo = modulo % (60 * 60);
    //分钟
    let minutes = Math.floor(modulo / 60);
    //秒
    let seconds = modulo % 60;
    return{
      days, hours, minutes, seconds
    }
  }

  public render() {
    return (
      <div>
        {
          !this.state.isStart ?
          "敬请期待" :
          this.state.isEnd ?
          "活动已结束" :
          <div>
            活动截止倒计时：
            <span className="time-w">{this.state.countDown.days}</span>天
            <span className="time-w">{this.state.countDown.hours}</span>时
            <span className="time-w">{this.state.countDown.minutes}</span>分
            <span className="time-w">{this.state.countDown.seconds}</span>秒
          </div>
        }
      </div>
    )
  }
}
