// app.js
import { cEvent } from './utils/event.js'
const Promise = require('lib/bluebird')
var utils = require('utils/util.js')
var commonFunc = require('utils/common.js')
var contants = require('utils/const.js')
var cityJson = require('utils/city.js')
var wxService = require('utils/wxService')
let config = require('./configScreen/configScreen');
const envInfo = require('config/index').envInfo
let isPlusVip = false

App({
  onLaunch: function (e) {
    console.log('onLaunch---',e);
   //  "navigationStyle": "custom"
   // 默认 false
   wx.setStorageSync('reLoginErr', false)
    try {
      this.isFromQiyeConsoleIn(e);
      
      let res = wx.getSystemInfoSync(); // 获取当前运行环境
      config.pixelRate = res.windowWidth / 750;
      config.platform = res.platform;
      config.statusBarHeight = res.statusBarHeight;
      const qyWeChat = res && res.environment || '' // 在企业微信固定返回wxwork，在微信不返回该字段，开发者可此判断当前是否在企业微信运行
      wx.setStorageSync('_qyWeChat', qyWeChat)
      if (res.platform.toLowerCase() == 'devtools') {
        config.capsuleHeight = 44;
      }
      if (res.platform.toLowerCase() == 'android') {
        config.capsuleHeight = 48;
      }
      config.titleHeight = (config.capsuleHeight + config.statusBarHeight) / config.pixelRate;
      if (res.statusBarHeight >= 44) {
        config.isHighHead = true;
      }
      if (res.windowHeight > 750) config.isAllScreen = true;
      config.systemHeight = res.windowHeight;
    } catch (e) {
      console.log(err);
    }
  },
  //检查新版本
  checkForUpdate(){
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    });

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '已有小程序新版本，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
  },
  //判断是不是从企业微信控制台点击进来的
  isFromQiyeConsoleIn(options){
    options = options ? options : {};
    console.log('场景值1 ========', options.scene)
    let scene = wx.getLaunchOptionsSync().scene;
    console.log('场景值2 ========', scene)
    //判断是不是在企业微信中通过工作台打开的
    if (options.scene == 1119 || scene == 1119) {
      wx.redirectTo({
        url: '/shoppingGuid/page/pages/welcomGuider/welcomGuider',
      });
      return;
    }
  },

  onShow: function (options = {}) {
    //检查是不是有更新
    this.checkForUpdate();

    const baseUserInfo = wx.getStorageSync('_baseUserInfo')
    // 获取当前会员是否是体验者
    const { member } = baseUserInfo
    const curMemberTrial = member && member.trial || false
    wx.setStorageSync('isExperiencer', curMemberTrial)

    if (options.referrerInfo && options.referrerInfo.extraData!=null){
      const { activate_ticket, card_id, code, errCode, wx_activate_after_submit_url } = options.referrerInfo.extraData
      let urlData = wx_activate_after_submit_url.split("?");
      let url = urlData[0];
      let parmas = urlData[1];
    
      // encodeURIComponent
      // decodeURIComponent
      wxService.router(`${url}`).search({
        activate_ticket: encodeURIComponent(activate_ticket),
        card_id,
        code,
        errCode,
        wx_activate_after_submit_url: parmas
      });

      // 激活成功 变更 _baseUserInfo
      baseUserInfo.wechatCardId = card_id
      baseUserInfo.wechatCode = code
      wx.setStorageSync('_baseUserInfo',baseUserInfo)
    }
    // 711_授权字体
    // wx.loadFontFace({
    //   family: 'iconfont-711',
    //   source: 'url("https://cdn-alyun.bigaka.com/group1/M00/00/01/Cv6CDl0nE9aAdG45AC7AStq8LfA180.TTF")',
    //   success: function (res) {
    //     console.log(res.status) //  loaded
    //   },
    //   fail: function (res) {
    //     console.log(res.status) //  error
    //   }
    // })
  },
  onHide: function () {
    this.globalData.loginFirst = false
  },
  getUserInfo() {
    return new Promise((resolve, reject) => {
      const _baseUserInfo = wx.getStorageSync('_baseUserInfo')
      if (_baseUserInfo) {
        resolve(_baseUserInfo)
      } else {
        reject('_baseUserInfo is null')
      }
    })
  },
  checkFullSucreen () {
    const self = this
    wxService.getSystemInfo().then(res => {
      if ((res.screenHeight - res.windowHeight - res.statusBarHeight - 32) > 72) {
　　　　　//  处理相关逻辑
        self.globalData.isFullSucreen = true
        // setGlobalData('fullScreen', true)
      }
    })
  },

  globalData: {
    userInfo: null,
    userBaseInfo: null, // openid
    systemInfo: wx.getSystemInfoSync(),
    ctx: envInfo.ctx,
    openCard: false,
    appId: envInfo.appId,
    userNo: null,
    storeId: '',
    storeName: '',
    loginFirst: false,
    imageUrl: envInfo.imgCtx, //图片地址
    isFullSucreen: false, // 当前设备是否为 FullSucreen
    commonFunc: commonFunc,
    contants: contants,
    isPlusVip: isPlusVip,
    cityJson: cityJson,
    brandId: envInfo.brandId,
  }
})
