const {
  api,
  alertTip,
  imgName,
  toastTip,
  wxLogin,
  getProtocol
} = require('../../lib/util.js')
var t = {}
let timer = null
Page({
  data: {
    imgBg: imgName('loginbg.jpg'),
    imgLight1: imgName('logo_light1.png'),
    imgLight2: imgName('logo_light2.png'),
    inputPhone: null,
    inputMeg: null,
    // receiveMsg:null,
    inputPassword: null,
    inputPasswordAgain: null,
    inputEmail: null,
    msgLoading: false,
    agree: false,
    hasAuth: false,
    setTimeSec: 60,
    limitSec: 60,
    sex: true,
    phoneNum: null, //输入的号码
    code: '',
    encryptedData: '',
    iv: '',
    unionid: '',
    firstLoad: true
  },
  onLoad: function(query) {
    this.login()
  },
  onShow: function() {},
  onChange(event) {
    const detail = event.detail;
    console.log(detail.value)
    this.setData({
      'sex': detail.value
    })

  },
  numInput(e) {
    this.setData({
      [e.target.id]: e.detail.value
    })
  },
  getMsg() {
    let inputPhone = this.data.inputPhone
    let _this = this
    if (!/^1\d{10}/.test(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
        })
      })
  },
  hascheck(e) {
    console.log(this.data.agree)
    this.setData({
      agree: !this.data.agree
    })
  },
  toProtocol: function() {
    getProtocol(1)
      .then(res => {
        console.log(res)
      })
      .catch(err => {
        console.error(err)
        alertTip(err.errMsg || err)
      })
  },
  getUserInfo(e) {
    console.log(e)
    if (!e.detail.encryptedData) {
      toastTip({
        title: '您拒绝了授权请求',
        icon: 'none'
      })
      return
    }
    let {
      iv,
      encryptedData
    } = e.detail
    this.setData({
      iv,
      encryptedData
    })
    if (this.data.firstLoad) {
      this.data.firstLoad = false
      this.loginBycode()
    } else {
      this.login().then(r => {
        this.loginBycode()
      })
    }
  },
  getCarList() {
    let that = this
    return api.post('device/userBindingDeviceList')
      .then(res => {
        console.log('设备列表：', res)
        if (res.items.length > 0) {
          return true
        } else {
          return false
        }
      })
  },
  bindPhone() {
    let This = this
    //绑定手机号
    if (This.canBind(true)) {
      this.login()
        .then(code => {
          api.post('user/regist', {
              mobile: This.data.inputPhone,
              encryptedData: This.data.encryptedData,
              iv: This.data.iv,
              Vcode: This.data.inputMeg,
              unionid: This.data.unionid,
              type: '2'
            })
            .then(res => {
              // wx.showModal({
              //   title: '提示',
              //   content: res.message,
              //   showCancel: false,
              //   success: function (res) {
              //     if (res.confirm) {
              //       wx.reLaunch({
              //         url: '/pages/welcome2/welcome2',
              //       })
              //     }
              //   }
              // })
              console.log('注册成功：', res)
              wx.setStorageSync('user', res.data)
              this.logAfter(res)
            })
            .catch(err => {
              console.log('注册失败：', err)
              alertTip(err)
            })
        })
        .catch(err => {
          console.log(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 (!this.data.inputEmail) {
    //   willTip && alertTip('请输入邮箱！')
    //   return false
    // }
    // if (this.data.inputMeg != this.data.receiveMsg) {
    //   console.log(this.data.inputMeg ,this.data.receiveMsg)
    //   willTip && alertTip('验证码不正确！')
    //   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
    // }

    // if (!this.data.agree) {
    //   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)
  },
  login() {
    return wxLogin()
      .then(code => {
        console.log(code)
        this.setData({
          code
        })
        return code
      })
      .catch(err => {
        alertTip('请同意微信登录，才能收到报警推送。')
      })
  },
  logAfter(res) {
    wx.setStorageSync('user', res.data)
    //有车
    wx.navigateBack()    
  },
  loginBycode() {
    let body = {
      code: this.data.code,
      encryptedData: this.data.encryptedData,
      iv: this.data.iv,
      type: '2'
    }
    api.post('bms/user/login', body, {}, false, true)
      .then(res => {
        console.log(res)
        if (res.data.code == '0') {
          toastTip({
            title: '请绑定手机号',
            icon: 'none'
          })
          this.setData({
            hasAuth: true,
            unionid: res.data.userMapp.unionid
          })
          wx.setNavigationBarTitle({
            title: '用户注册',
          })
        } else {
          this.logAfter(res)
        }
      })
      .catch((err) => {
        console.log(err)
        if (err != 'null') {
          alertTip(err)
        } else {
          this.setData({
            hasAuth: true
          })
        }
        wx.setNavigationBarTitle({
          title: '用户注册',
        })
      })
  },
})