const service = require('./utils/service.js');
const tim = require('./utils/tim.js');
const Util = require('./utils/util.js');
App({
  globalData: {
    userInfo: null,
    isLogin: false,
    sessionRecord: false,
    headerHeight: 0,
    statusBarHeight: 0,
    isDebug: true,
  },
  onLaunch: function (options) {
    console.log("onLaunch")
    var that = this
    wx.login({
      success: function (msg) {
        service.getOpenId(msg.code).then((res) => {
          wx.setStorageSync('user', res); //存储openid
          return service.getUserData(res.openid)
        }).then((res) => {
          wx.setStorageSync('data', res)
          console.log('%c查询成功', "color:#04BE02", res);
          that.globalData.userInfo = res;
          if (Util.isEmpty(res.unionid)) return service.breakPromise();
          else return service.getUserSig(res.unionid)
        }).then((res) => {
          return tim.login(res.data.userid, res.data.sign)
        }).then(function (imResponse) {
          console.log('%c登录成功', "color:#04BE02", imResponse);
          if (imResponse.data.repeatLogin === true) {
            // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
            console.log('"%c本次登录操作为重复登录', "color:#ff0000", imResponse.data.errorInfo);
          }
        }).catch(function (imError) {
          console.log('"%c登录失败', "color:#ff0000", imError); // 登录失败
          console.warn('login error:', imError); // 登录失败的相关信息
        });
      }
    })
    const {
      model,
      system,
      statusBarHeight
    } = wx.getSystemInfoSync()
    let headHeight
    if (/iphone\s{0,}x/i.test(model)) {
      headHeight = 88
    } else if (system.indexOf('Android') !== -1) {
      headHeight = 68
    } else {
      headHeight = 64
    }
    this.globalData.headerHeight = headHeight
    this.globalData.statusBarHeight = statusBarHeight
  },
  onShow:function(){
    console.log("onShow")
  },
  onHide:function(){
    console.log("onHide")
  },

  ///小程序强制更新
  forcedUpdate: function () {
    service.forcedUpdate().then((res) => {
      if (res.code == 1) {
        if (res.data.is_required == 1) {
          if (wx.canIUse('getUpdateManager')) {
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
              if (res.hasUpdate) {
                updateManager.onUpdateReady(function () {})
                updateManager.onUpdateFailed(function () {})
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
          }
        }
      }
    })
  },
  //个人信息
  getUserData: function (data) {
    var that = this;
    service.getUserData(data).then((res) => {
      console.log("res", res)
      that.globalData.userInfo = res;
      wx.setStorageSync('data', res)
    })
  },
  //登录方法
  getUserInfo: function (cb) {
    var that = this;
    //登录
    wx.login({
      success: function (msg) {
        wx.getUserInfo({
          success: function (res) {
            if (msg.code) {
              var data = {};
              data.code = msg.code;
              data.encryptedData = res.encryptedData;
              data.iv = res.iv;
              data.type = 1;
              service.addUserInfo(data).then((res) => {
                console.log('%c添加成功', "color:#04BE02", res);
                that.globalData.unionid = res.unionId;
                that.getUserData(res.openId)
                if (Util.isEmpty(res.unionId)) return service.breakPromise();
                else return service.getUserSig(res.unionId)
              }).then((res) => {
                return tim.login(res.data.userid, res.data.sign)
              }).then(function (imResponse) {
                that.globalData.isLogin = true;
                typeof cb == "function" && cb(that.globalData.unionid)
                console.log('%c登录成功', "color:#04BE02", imResponse.data.errorInfo);
                if (imResponse.data.repeatLogin === true) {
                  // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
                  console.log('"%c本次登录操作为重复登录', "color:#ff0000", imResponse.data.errorInfo);
                }
              }).catch(function (imError) {
                typeof cb == "function" && cb(that.globalData.unionid)
                console.log('"%c登录失败', "color:#ff0000", imError); // 登录失败
                console.warn('login error:', imError); // 登录失败的相关信息
              });
            }
          },
          fail: function (e) {
            var data = {
              code: msg.code,
              type: 0
            };
            service.addUserInfo(data).then((res) => {
              typeof cb == "function" && cb(res)
            })
          }
        })
      },
      fail: function (err) {
        typeof cb == "function" && cb(err)
        console.log("login失败")
      }
    })
  },
  getaddFriend: function (add_unionid, type) {
    var that = this;
    // if (this.globalData.userInfo) {
    //   typeof cb == "function" && cb(this.globalData.userInfo)
    // } else {
    //调用登录接口
    wx.login({
      success: function (res1) {
        wx.setStorageSync("code", res1)
        wx.getUserInfo({
          success: function (res) {
            // that.globalData.userInfo = res.userInfo;
            // that.globalData.refuse = 1;
            // typeof cb == "function" && cb(that.globalData.userInfo)
            wx.setStorageSync('userInfo', res.userInfo);
            if (res1.code) {
              var data = {};
              data.add_unionid = add_unionid;
              data.options_type = type;
              data.code = res1.code;
              data.encryptedData = res.encryptedData;
              data.iv = res.iv;
              service.appAddFriend(data).then(addres => {
                if (addres.code == 1 || addres.code == 3) {
                  console.log('添加成功！')
                  if (type == 1) {}
                } else {
                  wx.setStorageSync('addFriend', true);
                  console.log('添加失败！')
                }
              });
            }
          },
          fail: function (e) {}
        })
      },
      fail: function (err) {
        console.log("添加失败err", err)
      }
    })
    // }
  },
})