const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
const user = require('../../../services/user.js');

//获取应用实例
const app = getApp()
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    navUrl: ''
  },

  onLoad: function (options) {
    let that = this;
    if (wx.getStorageSync("navUrl")) {
      that.setData(
        {
          navUrl: wx.getStorageSync("navUrl")
        }
      )
    }else{
      that.setData(
        {
          navUrl: '/pages/index/index'
        }
      )
    }
  },

  bindGetUserInfo: function (e) {
    let that = this;
    // console.log(e.detail.userInfo)
    // console.log(that.data.navUrl);
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.getUserInfo({
            withCredentials: true,
            success: function (succRes) {
              // console.log(res);
              //登录远程服务器
              wx.request({
                url: api.AuthLoginByWeixin,
                data: {
                  code: res.code, userInfo: succRes, storeId: wx.getStorageSync('storeId'), merchSn: wx.getStorageSync('merchSn')
                },
                method: 'POST',
                header: {
                  'Content-Type': 'application/json'
                },
                success: function (wxRes) {
                  if (wxRes.data.errno === 0) {
                    //存储用户信息
                    wx.setStorageSync('userInfo', wxRes.data.data.userInfo);
                    wx.setStorageSync('token', wxRes.data.data.token);
                    wx.setStorageSync('userId', wxRes.data.data.userId);

                    if (that.data.navUrl && that.data.navUrl == '/pages/index/index') {
                      wx.switchTab({
                        url: that.data.navUrl,
                      });
                    } else if (that.data.navUrl) {
                      wx.redirectTo({
                        url: that.data.navUrl,
                      });
                    }
                    console.log("登录成功");
                  }
                },
                fail: function (err) {
                  console.log("failed");
                }
              });
            },
            fail: function (err) {
              console.log("重新认证");
            }
          });
        } else {
          console.log("failed");
        }
      },
      fail: function (err) {
        console.log("failed");
      }
    });

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})
