app.js 7.58 KB
//app.js
import { getSystemInfoSync } from "~/utils/systemInfo";
// 解决showLoading 和 showToast显示异常的问题
import fixWxShowToast from "./utils/lib/fixWxShowToast";
fixWxShowToast();
import router from "./router/index.js";
// 判断小程序是否需要更新
import getUpdateManager from "./utils/lib/wxUpdateManager";
import util from "./utils/util.js";
import wxApi from "./utils/utils_wx";
// 实例化对象存储
import { Storage } from "~/utils/cache/storage";
const $Storage = new Storage();
import {
  setSystem_info,
  getNoSignInUuid,
  removeSystemStorage,
  rmNoSignInUuid
} from "~/utils/cache/storageApi";
setSystem_info(); // 存储设备信息
import { checkYqdSuper, checkScene } from "~/store/index";
import eventbus from "./utils/eventbus";
import api from "./api/api";
const { createVersionConfig } = require('./utils/versionConfig.js')
// 预加载:多分包共用,满足主包依赖链(上传质量检测)
require('./utils/vinVaildate.js')
require('./utils/timeFormat/time-utils.js')
// 省市区 CDN 加载:GLForm/GLCustForm 分包共用,满足主包依赖链
require('./utils/areaList.js')
require('@vant/weapp/dialog/dialog')

import globalDataFunction from './mixins/globalDataFunction'
import { hasPermission, createPermissionHelpers, LOGIN_ROLE } from './utils/rolePermission'

/**全埋点 */
import Track from '~/utils/track'
const $Track = new Track()

// 将 api.reNoSignIn() 函数包装为防抖函数
const debouncedReNoSignIn = debounce(function (noSignInUuid, that) {
  console.log("debouncedReNoSignIn2222");
  api
    .reNoSignIn({
      noSignInUuid: noSignInUuid,
    })
    .then((res) => {
      let { code, data } = res;
      if (code == "0" && data) {
        util.setSessionId(data?.sessionId);
        // debugger
        // 还要判断一下他是不是全部登录完,不是直接打到账号选择页面
        if (!data.needSelectAccount) {
          wx.reLaunch({ url: "/pages/loading/loading" });
        } else {
          // debugger
          wx.reLaunch({ url: "/pages/accountItems/accountItems" });
        }
      } else {
        util.removeStorage();
        removeSystemStorage();
        that.login(false);
      }
    })
    .catch((err) => {
      const errMsg = err?.errMsg || String(err || "");
      const isTimeout = /timeout/i.test(errMsg) || err?.errno === 5;
      console.warn("[reNoSignIn fail]", { isTimeout, errMsg }, err);
      // 网络超时等瞬时错误不强制登出,避免初始化阶段反复弹窗
      if (!isTimeout) {
        util.removeStorage();
        removeSystemStorage();
        that.login(false);
      }
    });
}, 300);
// 定义一个防抖函数
function debounce(func, timeout) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}
App({
  onLaunch() {
    /**挂载到wx对象 */
    wx.$storage = $Storage; /** 挂载全局缓存方法 */
    wx.$router = router;
    wx.$modal = this.showModal;
    wx.$util = util;
    // 启动打开会话闸门:sessionId 尚未落地时,首个请求先等一会儿再发(见 util.openSessionGate)
    util.openSessionGate();
    wx.$api = wxApi;
    wx.$eventbus = eventbus;
    wx.$track = $Track
    wx.$hasPermission = hasPermission
    wx.$permission = createPermissionHelpers()
    wx.$LOGIN_ROLE = LOGIN_ROLE
    let userInfo = util.getStorageSync("dj_boutique_user_info");
    // ,this.globalData, userInfo
    userInfo && this.gobalCheckYqdSuper(userInfo);
    wx.$versionConfig = createVersionConfig({
      request: {
        baseUrl: "https://config-center-backend.glsx.com.cn/glsxAdmin/config",
      },
    });
    wx.$globalDataFunction = globalDataFunction
  },
  async getVersionInfo(request) {
    if (request) this.globalData.versionData = null;
    const { versionData } = this.globalData;
    if (versionData) return versionData;
    else {
      const res = await wx.$versionConfig.get({
        moduleUrl: "dj-car-boutique-work-wechat",
        env: "update",
      });
      this.globalData.versionData = res;
      return res;
    }
  },
  showModal(that, options, id = "#modal") {
    // id = id || "#modal";
    that.selectComponent(id).showModal(options);
  },
  gobalCheckYqdSuper(userInfo) {
    checkYqdSuper(userInfo, this.globalData);
  },
  onShow(options) {
    wx.onMemoryWarning(function () {
      console.log("onMemoryWarningReceive");
    });
    // console.log('lifeshow')
    getUpdateManager();
    // options = {
    //   query: {
    //     page: 'playVideo',
    //     type: 1,
    //     title: '内容通知-培训资料-视频',
    //     id: 30,
    //     merchantId: 44211025
    //   }
    // }
    if (options) {
    //   console.log('options', options)

      let res = checkScene(options);
      // console.log(res, 'res')
      // 如果需要重新登录 去掉30天免登录逻辑避免自动登录直接跳回到首页去
      if (res) {
        rmNoSignInUuid()
        this.login(true, res);
      }
      // res &&
    }
  },
  login(relogin, context, RequestMethods) {
    let that = this;
    // 清空多账号信息
    if (relogin) {
      // 判断有没有 30 天免登陆 有直接跳选园区
      let noSignInUuid = getNoSignInUuid();
      console.log("noSignInUuid", noSignInUuid);
      if (noSignInUuid) {
        // 调用防抖函数
        debouncedReNoSignIn(noSignInUuid, that);
      } else {
        let thisPage = wx.$router.getPageInstance()
        // 启动页loading中的埋点接口 在触发登录超时后 ios端wx.showModal会被页面跳转截断,导致无弹窗,将loading页面这个埋点接口的登录超时不做弹窗处理
        // 调用方(请求层 / newRequest)可能不带第三参,这里必须容错:
        // 直接 RequestMethods.includes 会在 undefined 上抛错,弹窗逻辑整段跑不到。
        if (thisPage?.route == 'pages/loading/loading' && RequestMethods?.includes?.('dj.api.smartcarlife.staff.login.record.save')) return
        // 标志位 解决安卓查复弹框问题
        if (wx.__HAS_NOTLOGIN_MODAL) return false;
        wx.__HAS_NOTLOGIN_MODAL = true;
        wx.showModal({
          title: "温馨提示",
          content: context || "登录过期,请重新登录。",
          showCancel: false,
          confirmText: "去登录",
          confirmColor: "#347BFF",
          success(res) {
            if (res.confirm) {
              that.globalData.yqdInfo = {};
              that.globalData.YQorderSetting = "";
              that.globalData.YQList = "";
              that.globalData.businessSchoolScene = "";
              util.removeStorage();
              wx.$relogin = relogin;
              router.reLaunch("pages.wxLogin");
            }
          },
          complete: () => {
            // 这个延迟的目的是为了避免短时间内重复弹出
            // 你要是没有这个需要也可以去掉,直接把标志位改成 false 就行
            setTimeout(() => {
              wx.__HAS_NOTLOGIN_MODAL = false;
            }, 2000);
          },
        });
      }
    } else {
      this.globalData.yqdInfo = {};
      this.globalData.YQorderSetting = "";
      this.globalData.YQList = "";
      this.globalData.businessSchoolScene = "";
      util.removeStorage();
      removeSystemStorage();
      wx.$relogin = relogin;
      router.reLaunch("pages.wxLogin");
    }
  },

  globalData: {
    statusBarHeight: getSystemInfoSync().statusBarHeight, // 头部导航栏的高度
    yqdInfo: {},
    isYqdSuper: true,
    isStaff: false,
    YQorderSetting: "",
    count: "",
    versionData: null,
    businessSchoolScene: "",
    ROUTE_QUERY: {},//路由携带的参数
  },
});