// pages/login/login.js
const utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginCode: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  onShow: function () {
    utils.getLoginCode().then(res => {
      this.setData({
        loginCode: res.code
      })
      console.log('wx.login=>code=>', res.code)
    }).catch(res => {
      console.log('login=>wx.login登录失败=>' + res)
    })
  },

  //员工授权登录
  login() {
    let params = {
      code: this.data.loginCode,
      reqChannel: 5
    }
    utils.axios({
      method: 'post',
      url: '/auth/wx/login',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '登录中...',
          mask: true
        })
      },
      complete() {
        wx.hideLoading()
      },
      success: res => {
        let result = res.data
        if (result.loginFlag) {
          this.loginSuccess(result)
        } else {
          wx.navigateTo({
            url: '/pages/loginBind/loginBind?uid=' + result.unionId
          })
        }
      }
    })
  },

  //登录成功后的执行函数
  loginSuccess(result) {
    utils.toast('登录成功')
    let userInfo = {
      roles: result.usertype,
      mobile: result.account,
      userName: result.userName,
      roleName: result.roleName
    }
    wx.setStorageSync('userInfo', userInfo)
    wx.setStorageSync('token', result.token)
    wx.setStorageSync('expirationTime', result.expirationTime)
    // utils.getCompany().then(res => {
    //   wx.setStorageSync('company', res.data)
    // })
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },


  //单纯的获取uid
  getUid() {
    wx.navigateTo({
      url: '/pages/loginBind/loginBind'
    })
  },

  //返回首页
  toHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: '诺信云',
      path: '/pages/index/index'
    }
  }
})