import Taro, { Component } from '@tarojs/taro'
import './index.scss'

export default class extends Component {
  state = {
    sec: 0,
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.countdown !== this.props.countdown) {
      if (nextProps.countdown) {
        let s = 0
        const tk = setInterval(() => {
          s += 1
          this.setState({ sec: s })
  
          if (s >= this.props.countdown) {
            clearInterval(tk)
          }
        }, 1000)
      } else {
        this.setState({ sec: 0 })
      }
    }
  }

  handleClick = (disable) => {
    if (disable) return;

    if (this.props.onClick) {
      this.props.onClick()
    }
  }

  render() {
    const disable = this.props.countdown > 0 && this.state.sec < this.props.countdown ? 'disable' : ''
    
    return (
      <View className={`btn-step ${disable}`} onClick={() => this.handleClick(disable)}>
        {this.props.text}
        {
          disable ? ` (${this.props.countdown - this.state.sec}s) ` : ''
        }
      </View>
    )

  }
}
