const {
  api,
  alertTip,
  imgName,
  wxLogin,
  getProtocol
} = require('../../lib/util.js')
var t = {}
let timer = null
Page({
  data: {
    imgBg: imgName('bg.png'),
    tipTime: 3,
    fade: false,
  },
  onLoad: function(query) {},
  onShow: function() {
    this.animation = wx.createAnimation()
    this.setData({
      tipTime: 3
    })
    // this.createAnimation()
    this.loginBycode()
  },
  createAnimation() {
    // const animation = wx.createAnimation({
    //   duration: 2000,
    //   timingFunction: '"ease-out"',
    //   delay: 0,
    // })
    this.animation.opacity(1).step({
      duration: 3000,
      timingFunction: 'ease-out'
    })
    this.setData({
      animationData: this.animation.export()
    })
  },
  login() {
    return wxLogin()
      .then(code => {
        return Promise.resolve(code)
      })
      .catch(err => {
        alertTip('请同意微信登录，才能收到报警推送。')
      })
  },
  getCarList() {
    let that = this
    return api.post('device/userBindingDeviceList')
      .then(res => {
        console.log('设备列表：', res)
        if (res.items.length > 0) {
          return true
        } else {
          return false
        }
      })
  },
  logAfter(user) {
    let {
      userMapp
    } = user
    //有车
    this.getCarList()
      .then(hasCar => {
        if (hasCar) {
          //有使用的车辆 跳到用车
          wx.switchTab({
            url: '/pages/user_index/user_index',
          })
          return
        } else {
          //没车绑定车辆
          wx.redirectTo({
            url: '/pages/device_bind/device_bind',
          })
        }
      })
      .catch(err => {
        console.log(err)
        wx.redirectTo({
          url: '/pages/register2/register2',
        })
      })
  },
  loginBycode() {
    let user = wx.getStorageSync('user')
    if (user) {
      clearInterval(timer)
      timer = setInterval(() => {
        this.setData({
          tipTime: this.data.tipTime - 1
        })
        if (this.data.tipTime == 2) {
          this.createAnimation()
        }
        if (this.data.tipTime == 0) {
          clearInterval(timer)
          this.logAfter(user)
        }
      }, 1000)
    } else {
      timer = setInterval(() => {
        this.setData({
          tipTime: this.data.tipTime - 1
        })
        if (this.data.tipTime == 2) {
          this.createAnimation()
        }
        if (this.data.tipTime == 0) {
          clearInterval(timer)
          wx.redirectTo({
            url: '/pages/register2/register2',
          })
        }
      }, 1000)
    }
  },
})