const util = require('../../../utils/util.js');
const app = getApp();
const crypto=require("../../../utils/crypto")
Page({
  data: {
    loginName: '',
    code: '',
    time: 0,
    userInfo: app.globalData.userInfo
  },
  onShow() {
    this.setData({ userInfo: app.globalData.userInfo });
  },
  sendCode() {
    let that = this;
    if(that.data.time>0) return false;
    if (util.isEmpty(this.data.loginName)) {
      util.showTips("请输入手机号码");
      return false;
    }
    if (util.isPhone(this.data.loginName)) {
      util.showTips("请输入正确的手机号码");
      return false;
    }
    if (this.data.loginName.length == 11 && this.data.userInfo.loginName == this.data.loginName) {
      util.showTips("当前手机号和绑定手机号一致,请勿重复绑定");
      return false;
    }
    let key=crypto.encrypted(this.data.loginName)
    util.sendMessage({ phone: this.data.loginName, type: "phone",time:120,key:key }, (res) => {
      that.setData({time:res.text})
    })
  },
  submit() {
    let that = this;
    if (util.isEmpty(this.data.loginName)) {
      util.showTips("请输入手机号码");
      return false;
    }
    if (util.isPhone(this.data.loginName)) {
      util.showTips("请输入正确的手机号码");
      return false;
    }
    if (util.isEmpty(this.data.code)) {
      util.showTips("请输入验证码");
      return false;
    }
    if (this.data.code.length != 6) {
      util.showTips("请输入6位验证码");
      return false;
    }
    util.ajax({
      func:'v2/user/phone',
      data:{ phone: that.data.loginName, vcode: that.data.code }
      },function(res){
      if (res.code == 0) {
        let userInfo = app.globalData.userInfo;
        userInfo.loginName = that.data.loginName;
        userInfo.phoneNum = that.data.loginName;
        app.globalData.userInfo = userInfo;
        wx.setStorageSync("WXuserInfo", userInfo)
        wx.navigateBack();
      } else {
        util.showTips(res.reason)
      }
    })
  },
  loginNameInput(e){
    this.setData({loginName:e.detail.value})
    if (e.detail.value.length == 11 && this.data.userInfo.loginName == e.detail.value) {
      util.showTips("当前手机号和绑定手机号一致,请勿重复绑定");
    }
  },
  codeInput(e) {
    this.setData({ code: e.detail.value })
  }
})