const app = getApp();
Page({
  data: {
    canClick: false,
    codeBtnTxt: "发送验证码",
    loginName: '',
    code:'',
  },
  onLoad(options){
    this.setData({
      userId:options.userId
    })
  },
  setLoginName: function (e) { //手机号输入校验
    var loginName = e.detail.value.replace(/[^\d]/g, "").substr(0, 11)
    //验证手机号
    var myreg = /^[1][0-9]{10}$/;
    this.setData({
      loginName,
      canClick: myreg.test(loginName)
    })
  },
  setCode: function (e) { //验证码输入绑定
    this.setData({
      code: e.detail.value.replace(/[^\d]/g, "").substr(0, 6)
    })
  },
  getValidCode: function (e) {
    //验证手机号
    var myreg = /^[1][0-9]{10}$/;
    if (!myreg.test(this.data.loginName)) {
      app.showToptip(this, "worning", "手机号输入有误")
      return;
    }
    var that = this
    wx.showLoading({
      title: '发送中...',
      mask: true
    })
    app.requestP({
      url: "/sms/getSmsCodeByMobile",
      method: 'post',
      contentType: "application/json",
      needToken: false,
      data: {
        mobile: that.data.loginName
      }
    }).then((res) => {
      app.showToptip(that, "success", "发送成功")
      that.data.lastSendTime = Date.now()
      that.setData({
        canClick: false
      })
      //定时器触发倒计时，
      var times = 60
      var i = setInterval(function () {
        times--
        if (times == 0) {
          that.setData({
            canClick: true,
            codeBtnTxt: "获取验证码",
          })
          clearInterval(i)
        } else {
          that.setData({
            codeBtnTxt: "重新获取" + times + "s",
          })
        }
      }, 1000)
    }).catch(function (r) {
      app.showToptip(that, "error", r.data.msg)
    })
  },
  editPhone(){
    var that = this;
    var phoneNumber = that.data.loginName;
    var phonereg = /^[1][0-9]{10}$/;
    var userId = thiat.data.userId;
    if (!phonereg.test(phoneNumber)) {
      app.showToptip(that, "worning", "手机号输入有误")
      return;
    }
    var smsCode = that.data.code
    if (!smsCode) {
      app.showToptip(that, "worning", "验证码输入有误")
      return;
    }
    wx.showLoading({
      mask: true
    })
    app.requestP({
      url:'/user/editPhoneNumber',
      method:'post',
      contentType:' application/json',
      data:{
        phonenumber,
        smsCode,
        userId,
      }
    }).then(res=>{
      wx.removeStorageSync("token")
      wx.redirectTo({
        url: '/pages/login/login?phoneNumber='+phoneNumber
      })
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }).error(err=>{
      app.showToptip(that, "worning", err.msg)
    })
  }
})