import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'

import './index.scss'

export default class extends Component {

  state = {
    sec: 0
  }

  handleClick = (left) => {
    if (!this.props.require()) return;
    if (!this.props.countdown) return;

    // 计时中
    if (left > 0 && left < this.props.countdown) return;
    
    if (this.props.onClick) {
      this.props.onClick().then(() => {
        // 开始跑表
        if (this.props.countdown) {
          let s = 0
          this.setState({ sec: s })
    
          const tk = setInterval(() => {
            if (s >= this.props.countdown) {
              clearInterval(tk)
              this.setState({ sec: 0 })
            } else {
              s += 1
              this.setState({ sec: s })
            }
          }, 1000)
        }
      })
    }
  }

  render() {
    const { sec } = this.state
    const { countdown } = this.props
    const left = countdown - sec

    return (
      <View className="captcha" onClick={() => this.handleClick(left)}>
        {
          left > 0 && left < countdown ? `${left}s 后重试` : '获取验证码'
        }        
      </View>
    )
  }
}