FloatLogConfig.js 2.31 KB
import { index as envIndex } from '@/env'

const listeners = new Set()
let configLoaded = false
let serverAllows = false

function isNonProduction() {
  return envIndex !== 3
}

/**
 * app-tape 配置 isShowLogBall:仅显式 true 时展示,未配置/false 均隐藏
 */
export function parseIsShowLogBall(mockData) {
  if (!mockData || mockData.isShowLogBall == null) return false
  const v = mockData.isShowLogBall
  if (v === true || v === 1) return true
  if (typeof v === 'string') return v.toLowerCase() === 'true'
  return false
}

function computeVisible() {
  return isNonProduction() && serverAllows
}

function notify() {
  const visible = computeVisible()
  listeners.forEach(fn => {
    try {
      fn(visible)
    } catch (e) {
      /* ignore */
    }
  })
  return visible
}

const FloatLogConfig = {
  isNonProduction,
  isLogBallVisible() {
    return computeVisible()
  },
  isConfigLoaded() {
    return configLoaded
  },

  applyFromMockData(mockData) {
    if (!isNonProduction()) {
      serverAllows = false
    } else {
      serverAllows = parseIsShowLogBall(mockData)
    }
    configLoaded = true
    const visible = notify()
    if (visible) {
      const FloatLogBus = require('./FloatLogBus.js').default
      FloatLogBus.install()
    }
    return visible
  },

  /**
   * 拉取配置中心 app-tape 并更新悬浮球(uni.$api.systemApi.getMockData)
   * 例: https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=app-tape&env=test
   * 字段 isShowLogBall;生产环境不展示
   */
  async refreshFromServer(immediate = false) {
    if (!isNonProduction()) {
      serverAllows = false
      configLoaded = true
      return notify()
    }

    const cached = uni.$storage?.get?.('mock_data')
    if (cached) {
      this.applyFromMockData(cached)
    }

    try {
      if (uni.$api?.systemApi?.getMockData) {
        const data = await uni.$api.systemApi.getMockData(immediate)
        return this.applyFromMockData(data)
      }
      serverAllows = false
    } catch (e) {
      uni.$logger?.local?.warn?.(`[FloatLogConfig] 读取 app-tape 配置失败: ${e?.message || e}`)
      serverAllows = false
    }

    configLoaded = true
    return notify()
  },

  subscribe(fn) {
    listeners.add(fn)
    fn(computeVisible())
    return () => listeners.delete(fn)
  }
}

export default FloatLogConfig