// pages/login/index.js
const app = getApp();
const toHomePage = () => {
  wx.reLaunch({
    url: '/pages/index/index',
  })
}
Page({
  data: {

  },
  onShow() {
    wx.showLoading({
      title: '登录中...',
    })
    
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        app.$http.postForm('/user/openidLogin', {
          code: res.code,
          customerId: app.$util.customerId
        }).then(({
          status,
          data = {},
          msg
        }) => {
          if (status == 0) {
            const {
              token
            } = data;
            app.getUserInfo(token);
            app.isLogin = true;
            toHomePage();
          } else {
            app.isLogin = false;
            toHomePage();
          }
        }).catch(() => {
          toHomePage();
        })
      },
      fail() {
        toHomePage();
      }
    })
  },
  onHide() {
    wx.hideLoading();
  }
})