import Taro, { Component } from '@tarojs/taro'
import { connect } from '@tarojs/redux'
import './index.scss'
import { getCodeMessage,putRegister} from '@services/getCode'
import { Input, Button } from '@tarojs/components'
import * as actions from '@actions/user'
@connect(state => state.user, { ...actions })
export default class Index extends Component {
  config = {
    navigationBarTitleText: '个人中心'
  }
  state = {
    isClick:false,
    time:60,
    tel:'',
    code:''
  }


  onChange=(e)=>{
    this.setState({
      tel: e.detail.value
    })
  }

  onChangeCode=(e)=>{
    this.setState({
      code: e.detail.value
    })
  }

  getCode(){
    const {isClick}=this.state
    const Phone=this.state.tel

    if (!(/^1[3|4|5|7|8|9][0-9]\d{4,8}$/.test(Phone)) || Phone.length != 11) {
        Taro.showToast({
          title: '输入的手机号格式不对，请重新输入',
          icon: 'none'
        })
        return
    }

    if(!isClick){
      this.goTime()
      this.setState({
        isClick:true
      })
      const {tel}=this.state
      getCodeMessage(tel).then(res => {

      })
    }else{
      Taro.showToast({
        title: '已经获取验证码，请在一分钟之后重试',
        icon: 'none'
      })
      return
    }
  }

  goTime(){
    const that=this
    var timer=setInterval(function () {
      var {time}=that.state
      if(time>0){
        var time2=time-1
        that.setState({
          time:time2
        })
      }else{
        clearInterval(timer)
        that.setState({
          time:60,
          isClick:false
        })
      }
    },1000)
  }

  putMessage(){
    const {tel,code}=this.state
    const payload = {
      tel:tel,
      code:code
    }
    putRegister(payload).then(res => {
      console.log('---bind-->', res)

      this.props.dispatchUpdateUserInfoNew(res.personId)
        Taro.showLoading({
          title: '登录中...',
          duration: 1000
        })
        setTimeout(function(){
          Taro.reLaunch({
            url: `/pages/person/index`
          })
        },1000)
    })
  }

  render() {
    return (
      <View className='page'>
        <View className='login'>
          <View className='login-info login-info_tel'>
            <Text>手机号</Text>
            <Input onInput={this.onChange.bind(this)} maxlength="11" type='number' className='tel' placeholder='请输入手机号'></Input>
          </View>
          <View className='login-info login-info_code'>
            <Input onInput={this.onChangeCode.bind(this)} type='number' className='code' placeholder='请输入验证码'></Input>
            <Button onClick={this.getCode} className='getCode' >
              {isClick?time+'s':'获取验证码'}
            </Button>
          </View>
        </View>
        <View onClick={this.putMessage} className='login-btn'>立即登录</View>
      </View>
    )
  }
}
