<template>
  <div style="margin-top: 20px">
    <el-form label-width="80px" style="width:400px">
      <el-form-item label="手机号码" >
        <el-input v-model="phoneBindingForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input placeholder="验证码内容" v-model="phoneBindingForm.verifyCode" class="input-with-select">
          <el-button slot="append" @click="getVerifyCode">{{hasVerifyCode ? codeTime : '获取验证码'}}</el-button>
        </el-input>
        <span v-if="hasVerifyCode">验证码已发送到您手机上</span>
      </el-form-item>
    </el-form>
    <el-button type="primary" plain style="margin-left: 80px" @click="bindingMobile">完成绑定</el-button>
  </div>

</template>

<script>
  import Http from '@/js/http.js'
  import {storageGet} from '@/js/index'
  import {notify} from '@/constants/index'
  export default {
    name: "BindingMobile",
    data(){
      return{
        phoneBindingForm:{
          phone:'',
          verifyCode:''
        },
        hasVerifyCode:false,
        codeTime:10,
        user:{}
      }
    },
    methods:{
      setUserInfo() {
        this.user = storageGet('user') && storageGet('user').userVO;
      },
      getVerifyCode(){
        let params = {
          id:this.user.id,
          mobile:this.phoneBindingForm.phone
        }
        Http.put('/api/verify/mobile',params).then((res)=>{
          this.hasVerifyCode = true;
          let _this = this;
          let codeTimer = setInterval(function () {
            if(_this.codeTime > 0 ){
              _this.codeTime--;
            }else{
              clearInterval(codeTimer);
              _this.hasVerifyCode = false;
              this.codeTime = 10;
            }
          },1000)
        }).catch(err=> {
          notify('error', '绑定手机失败:' + err.data);
        })
      },
      bindingMobile(){
        let params = {
          id:this.user.id,
          mobile:this.phoneBindingForm.phone,
          verifyCode: this.phoneBindingForm.verifyCode
        };
        Http.put('/api/user/mobile',params).then(res=>{
          if(res.code === 20000){
            notify('success', '绑定成功');
            this.$router.push({path:'/personal/phoneBinding'});
            //需要更改vuex和storage中得user
            console.log(storageGet(user));
         }
        }).catch(err=> {
          notify('error', err.data);
        })
      }
    },
    mounted() {
      this.setUserInfo()

    }
  }
</script>

<style scoped>

</style>
