<template>
  <div >
    <van-nav-bar
      title="登录"      
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
      style="background-color:#ececec;"
    />

    <van-form @submit="onSubmit">
    <van-field
      v-model="phone"
      type="tel"
      placeholder="手机号"
      :rules="[{ required: true, message: '请填写手机号' }]"
    />
    <van-field
      v-model="vericode"
     
      placeholder="验证码"
      :rules="[{  message: '请填写验证码' }]"
    >
    <template #button>
      <van-button size="small" type="default" @click="sendSms" ref="send" native-type="button"  :disabled="isdisabled">{{text}}</van-button>
    </template>
    </van-field>
    <div style="margin: 16px;">
      <van-button round block type="info" native-type="submit">提交</van-button>
    </div>
  </van-form>
  </div>
</template>

<script>
import {login,sendSms} from '@/common/api/loginApi.js'
export default {
  name: 'login',
  data () {
    return {
      phone: '',
      vericode: '',
      count:60,
      isdisabled:false,
      text:"获取验证码"
    }
  },
  methods: {
    onSubmit () {
      console.info('phone', this.phone)
      console.info('vericode', this.vericode)
      var data = {phone: this.phone, vericode: this.vericode}
      login(data).then((res) => {
        console.info('res', res);
        let obj=res;
        //console.info('result',obj.result);
        if(!obj.isSuccess){
          this.$toast(obj.errMsg);
          return;
        }
        //设置状态中的各种值
        this.$store.commit('setResult',obj.isSuccess);
        this.$store.commit('setCode',obj.code);
        this.$store.commit('setMsg',obj.errMsg);
        this.$store.commit('setData',obj.data); 
        this.$store.commit('setToken',obj.tnToken);
        //console.info('cookie',this.$cookie)
        this.$cookie.set('obj',JSON.stringify(obj) );      //设置cookie
        this.$router.push('/BindHouse');
      });
    },
    onClickLeft () {
      // this.$toast('返回')
      console.info('left')
    },
    onClickRight () {
      // this.$toast('按钮')
    },
    sendSms(){    //发送手机验证码
      var selft=this;
      sendSms(this.phone).then((res)=>{
        console.info('sendSms res',res);
        if(!res.isSuccess){
          this.$toast(res.errMsg);
          return;
          
        }
        if(res.data=="success"){
          selft.GetNumber();
        }

      })
    },
    GetNumber()   //发送短信验证码后间隔一定时间才能重新发送
    {
      let self=this;
        var timer = setInterval(function () {
        self.count--
        self.text = self.count + '秒后重新获取'
       self.isdisabled=true;
       
        if (self.count <= 0) {
          self.isdisabled = false
          self.text = '获取验证码'
          clearInterval(timer)
        }
      }, 1000);
    }
    
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
