const { api, alertTip } = require('../../lib/util.js')
var t = {}
Page({
  data: {
    inputPhone: null,
    inputMeg: null,
    inputPassword: null,
    receiveMsg:'',
    inputPasswordAgain: null,
    msgLoading: false,
    setTimeSec: 60,
    limitSec: 60
  },
  onLoad: function (query) {

  },
  onShow: function () {

  },
  numInput(e) {
    this.setData({
      [e.target.id]: e.detail.value
    })
  },
  getMsg() {
    let _this = this
    if (!/^1\d{10}/.test(this.data.inputPhone)) {
      alertTip('请输入正确的手机号！')
      return
    }

    _this.timer()
    //请求验证码api
    api.get('user/message', { mobile: Number(this.data.inputPhone) })
      .then(res => {
        alertTip('验证码已发送')
      })
      .catch(err => {
        alertTip('获取验证码请求失败')
        clearInterval(t)
        _this.setData({
          msgLoading: false
        })
      })
  },
  bindPhone() {
    let This = this
    //绑定手机号
    if (This.canBind(true)) {
      api.post('user/editPassBymobile', {
        mobile: Number(This.data.inputPhone),
        newPass: This.data.inputPassword,
        VCode: This.data.inputMeg
      })
        .then(res => {
          alertTip('修改密码成功',()=>{
            wx.redirectTo({
              url: '/pages/welcome2/welcome2',
            })
          })
        })
        .catch(err => {
          alertTip(err)
        })
    }
  },
  canBind(willTip) {
    if (!/^1\d{10}/.test(this.data.inputPhone)) {
      willTip && alertTip('请输入正确的手机号！')
      return false
    }
    if (!/\d{4}/i.test(this.data.inputMeg)) {
      willTip && alertTip('请输入4位数字的验证码！')
      return false
    }
    if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/.test(this.data.inputPassword)) {
      willTip && alertTip('请输入6-12位包含数字和字母的密码！')
      return false
    }
    if (this.data.inputPasswordAgain != this.data.inputPassword) {
      willTip && alertTip('两次输入的密码不一样！')
      return false
    }
    return true
  },
  // 重发验证码定时器
  timer: function () {
    var count = this.data.setTimeSec
    var that = this
    that.setData({
      limitSec: count,
      msgLoading: true
    })
    clearInterval(t)
    t = setInterval(function () {
      if (count != 0) {
        count--
        that.setData({
          limitSec: count
        })
      } else {
        clearInterval(t)
        that.setData({
          limitSec: count,
          msgLoading: false
        })
      }
    }, 1000)
  }
})