import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styles from '../form.less'
import classNames from 'classnames/bind'

const classBind = classNames.bind(styles)

export default class Button extends Component {
    static propTypes = {
        disabled: PropTypes.bool,
        loading: PropTypes.bool,
        onClick: PropTypes.func,
        children: PropTypes.any,
        timeout: PropTypes.number
    }
    static defaultProps = {
        timeout: 0,
        enterSub: false,
        loading: false,
        onClick: () => true,
        children: '确认'
    }
    state = {
        loading: this.props.loading || false,
        timeout: this.props.timeout || 0,
        disabled: this.props.disabled || 0,
        text: null
    }
    timer = null

    componentWillReceiveProps (nextProps) {
        if (this.props.loading !== nextProps.loading) {
            this.setState({loading: nextProps.loading})
        }
    }

    componentWillUnmount () {
        this._resetTime()
    }

    _resetTime = () => {
        clearInterval(this.timer)
        this.timer = null
        this.setState({disabled: false, text: '重新获取', timeout: this.props.timeout})
    }

    handleClick = () => {
        const {onClick} = this.props
        if (onClick()) {
            if (this.state.timeout > 0) {
                this.setState({disabled: true})
                this.timer = setInterval(() => {
                    this.setState({timeout: this.state.timeout - 1})
                    if (this.state.timeout <= 0) {
                        this._resetTime()
                    }
                }, 1000)
            }
        }
    }

    render () {
        const {children} = this.props
        let className = classBind(
            'btnSub',
            {'loading': this.state.loading},
            {'disabled': this.state.disabled || this.state.loading}
        )
        return (
            <button disabled={this.state.disabled} onClick={this.handleClick}
                    className={className}>
                {this.timer && this.state.timeout > 0 ? this.state.timeout : this.state.text || children}
            </button>
        )
    }
}
