import React from 'react';
require('./index.css');
const initCount = -1;
export default class ClockComponent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            count : initCount,
            timer : null
        };
        this.time = 1000;
        this.beginCountBack = this.beginCountBack.bind(this)
    }

    componentWillMount(){
        let {totalTime} = this.props;
        if(totalTime && totalTime > 0){
            this.setState({
                count : totalTime
            },()=>{
                this.beginCountBack()
            })
        }

    }

    componentWillReceiveProps(){
    }

    componentWillUnmount(){
        window.clearTimeout(this.state.timer);
        this.setState({
            timer : null,
            count : initCount
        })
    }

    beginCountBack(){
        let {callback} = this.props;
        let that = this;
        if(!this.state.timer && this.state.count >= 0){
            let count = this.state.count - 1;
            this.state.timer = window.setTimeout(()=>{
                if(count >= 0){
                    window.clearTimeout(that.state.timer);
                    that.setState({
                        timer : null,
                        count : count
                    },()=>{
                        that.beginCountBack();
                    })
                }else{
                    //倒计时结束
                    window.clearTimeout(that.state.timer);
                    that.setState({
                        timer : null
                    },()=>{
                        callback();
                    })

                }
            },this.time)
        }

    }

    render(){
        let props = this.props;
        return(
            <div className={"clockComponent font32"} style={props.style}>
                {
                    props.text ? <span className={"clockText"}>{props.text}</span> : <img className={"clockIcon"} src={UTILPATH.localImg.clockIcon} alt=""/>
                }
                <span className={"clockTime"}>{this.state.count}s</span>
            </div>
        )
    }
}