// var Parse = getApp().Parse;
// var app = getApp()
// const { wxLogin } = require('./utils/login')
const CONFIG = require("config.js");
let config = {
  appid: CONFIG.default.appid,
  company: CONFIG.default.company,
  rootPage: CONFIG.default.rootPage,
}
const plugin = requirePlugin('fm-plugin')
const { Parse, checkAuth } = plugin

Page({
  /**
   * 页面的初始数据
   */
  data: {
    splashUrl: wx.getStorageSync("enabledOptions")[0],
    loading:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    wx.setStorageSync("invite", null);
    let str = decodeURIComponent(options.q); //扫描二维码获得的跳转链接
    let obj = this.getParaName(str)
    if (obj && obj.invite) {
      wx.setStorageSync("invite", obj.invite);
    }
    obj && Object.keys(obj).forEach(key=> options[key] = obj[key])
    this.setData({
      options: options
    })
    let {
      time,
      dramaId,
      roomId,
      orderId,
      shopId,
      invite,
      activityId,
      company,
      inviteHost
    } = options
    time && wx.setStorageSync("time", time);
    dramaId && wx.setStorageSync("dramaId", dramaId);
    roomId && wx.setStorageSync("roomId", roomId);
    orderId && wx.setStorageSync("orderId", orderId);
    shopId && wx.setStorageSync("shopId", shopId);
    invite && wx.setStorageSync("invite", invite);
    activityId && wx.setStorageSync("activityId", activityId);
    inviteHost && wx.setStorageSync("inviteHost", true);
    if (company) getApp().globalData.toCompany = true;
    plugin.init(config, wx.getStorageSync('invite'))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: async function () { },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    await this.review()
  },

  async review(force){
    try {
      let options = this.data.options
      let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath
      if (options) {
        let objArr = Object.keys(options)
        if (objArr && objArr.length > 0) {
          let parms = '?'
          objArr.forEach((o, index) => {
            if (index > 0) {
              parms += '&' + o + '=' + options[o]
            } else {
              parms += o + '=' + options[o]
            }
          })
          url += parms
        }
      }

      let currentUser = Parse.User.current()
      console.log(Parse.User.current())
      if (!currentUser || force) {
        // let data = await wxLogin()
        // if (data.statusCode == 200) {
         let r = await checkAuth(true)
         console.log(r);
        //  getApp().Parse = Parse
        //  getApp().checkAuth = checkAuth
         if(!r) return
        // }
      } else {
        this.updateUser(currentUser.id)
      }
      getApp().Parse = Parse
      getApp().checkAuth = checkAuth
      if (!await this.getCompanyServerExpire(url)) {
        return
      }
      console.log(url);
      wx.redirectTo({
          url: url,
      });
    }
    catch (err) {
      console.log(err);
      /* 登录身份信息到期，重新登陆 */
      if((err?.message.indexOf('Session token is expired') != -1 || err?.message.indexOf('Invalid session token') != -1) && !force){
        let invite = wx.getStorageSync('invite')
        wx.clearStorageSync()
        invite && wx.setStorageSync('invite', invite)
        /* 强制重新登录 */
        this.review(true)
        return
      }
      this.setData({
        loading:false
      })
      wx.showModal({
        title: '温馨提示',
        content: '服务器正在升级，请稍后重试。',
        showCancel: false,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {
            wx.exitMiniProgram()
          }
        },
      });
    }
  },

  async updateUser(id) {
    let User = new Parse.Query('_User')
    let user = await User.get(id)
    let invite = wx.getStorageSync('invite')
    //查询邀请人user
    let query = new Parse.Query("_User")
    query.equalTo('objectId', invite)
    let result = await query.first()
    if (result && result.id && result.get("invite")?.id == user.id) {
      console.error('邀请人不能是自己的下级')
      return
    }
    if (invite && !user.get('invite') && user.id != invite && !user.get('agentLevel')) {
      console.log('上下级绑定成功');
      user.set('invite', {
        __type: "Pointer",
        className: "_User",
        objectId: invite
      })
      user.set('agent', {
        __type: "Pointer",
        className: "_User",
        objectId: invite
      })
      await Parse.Cloud.run('user_save', {
        userJson: user.toJSON()
      })
    }
  },
  async getCompanyServerExpire(url) {
    let query = new Parse.Query('Company')
    query.equalTo('objectId', getApp().globalData.company)
    query.select('expireDate', 'expireMap')
    let com = await query.first()
    if (com?.id && com?.get('expireDate')) {
      let now = + new Date()
      let expireTime = + new Date(com?.get('expireDate'))
      if (com?.get('expireMap') && com.get('expireMap')[getApp().globalData.appid]) {
        expireTime = + new Date(com.get('expireMap')[getApp().globalData.appid])
      }
      if (now >= expireTime) {
        console.log('服务器到期');
        wx.reLaunch({
          url: `common-page/pages/loading/index?url=${url}`,
        });
        return
      }
    }
    return true
  },

  onUnload: function () {
    wx.setStorageSync("active", 0);
  },
  getParaName(url) {
    if (!url || url.indexOf('?') == -1) {
      return
    }
    let paraname = url.split('?')[1]
    return this.setObject(paraname) //封装成对象
  },
  setObject(paraArr) {
    let obj = {}
    let arr1 = paraArr.split('&')
    arr1.forEach(item => {
      let str = item.split('=')
      let key = str[0]
      let val = str[1]
      obj[key] = val
    })
    return obj
  }
});