import { defineStore } from 'pinia' import { computed, ref } from 'vue' import { frontConfigGetByDomain, type FrontConfigPublicItem } from '@/api/frontconfig/frontConfig' import defaultSettings from '@/settings' /** 判定接口业务成功(与全站 okCode 约定一致) */ function isOkCode(code: unknown): boolean { return code === 200 || code === 1 || code === 0 } /** 豁免域名兜底(未配置 VITE_FRONT_CONFIG_EXEMPT_HOSTS 时保持主域名豁免的历史默认行为) */ const DEFAULT_FRONT_BRAND_EXEMPT_HOSTS = 'wms.wms.gztbyc.com' /** * 解析豁免域名集合(主域名/自有默认站):命中后不拉取、不使用 frontConfig.getByDomain 品牌配置。 * 来源 .env 的 VITE_FRONT_CONFIG_EXEMPT_HOSTS(逗号分隔,可分别配置开发/生产环境的豁免域名): * - 显式置空(= 空值)→ 不豁免任何域名; * - 未配置(undefined)→ 回退默认主域名 wms.wms.gztbyc.com。 */ function resolveFrontBrandExemptHosts(): Set { const raw = import.meta.env.VITE_FRONT_CONFIG_EXEMPT_HOSTS const source = raw === undefined || raw === null ? DEFAULT_FRONT_BRAND_EXEMPT_HOSTS : String(raw) return new Set( source .split(',') .map((s) => s.trim().toLowerCase()) .filter(Boolean) ) } /** 豁免域名集合(按 import.meta.env 编译期静态替换) */ const FRONT_BRAND_EXEMPT_HOSTS = resolveFrontBrandExemptHosts() /** 归一化访问域名:去协议/路径/端口、转小写,用于豁免判定与请求域名 */ export function normalizeFrontHost(raw?: string): string { let host = (raw || '').trim().replace(/^https?:\/\//, '') const slashIdx = host.indexOf('/') if (slashIdx >= 0) host = host.slice(0, slashIdx) const colonIdx = host.indexOf(':') if (colonIdx >= 0) host = host.slice(0, colonIdx) return host.toLowerCase() } /** 主域名(豁免域名)清单:与品牌豁免同源,供其它「仅主域名可用」能力复用 */ export function getMainDomainHosts(): string[] { return Array.from(FRONT_BRAND_EXEMPT_HOSTS) } /** * 前端默认品牌 Logo(public/logo/1.png,部署后即 /logo/1.png)。 * 登录页与顶栏(Navbar)共用同一常量,避免出现「相对路径 /public/...」这类解析错误的兜底地址。 */ export const DEFAULT_BRAND_LOGO = '/logo/1.png' /** * 当前访问域名是否为主域名(= 品牌豁免域名,来源 VITE_FRONT_CONFIG_EXEMPT_HOSTS)。 * 用途:微信小程序授权页只能从主域名进入(自持域名下微信授权回调无法回到本系统), * 非主域名时前端禁用「去授权」入口并提示。 */ export function isMainDomainHost(raw?: string): boolean { const host = normalizeFrontHost(raw ?? window.location.hostname) return Boolean(host) && FRONT_BRAND_EXEMPT_HOSTS.has(host) } /** * 前端独立部署品牌(frontConfig.getByDomain 消费端) * * 设计:前端被部署到仓库「自持域名」时,登录前按 location.hostname 拉取该仓库公开品牌 * (title/logo/login_bg/favicon/theme)。未登记域名(404/configured=false)或网络异常时静默回退默认品牌。 * 免鉴权、免权限;main.ts 入口加载一次(loaded 幂等),失败不阻塞应用。 */ export const useFrontBrandStore = defineStore('frontBrand', () => { /** 是否已尝试加载(成功或失败都置 true,避免每次刷新重复请求) */ const loaded = ref(false) /** 品牌配置;null=使用系统默认品牌 */ const brand = ref(null) /** 当前访问域名(归一化) */ const currentHost = normalizeFrontHost(typeof window !== 'undefined' ? window.location.hostname : '') /** * 当前访问域名是否命中品牌豁免(主域名,见 VITE_FRONT_CONFIG_EXEMPT_HOSTS)。 * 命中时不拉取后端品牌,登录页 / 顶栏一律使用前端默认 Logo 与默认标题。 */ const isBrandExemptHost = computed(() => Boolean(currentHost) && FRONT_BRAND_EXEMPT_HOSTS.has(currentHost)) /** 历史 theme 约定键(曾承载 网页名称/主页面logo/登录页logo/登录页文字):现由品牌顶层字段(title/logo_url 等)配置, * 不再从 theme 语义消费;此处仅用于 applyThemeCssVars 排除,避免历史残留污染自定义 CSS 变量 */ const FRONT_THEME_DEFAULT_KEYS = ['siteName', 'mainLogoUrl', 'loginLogoUrl', 'loginText'] as const /** theme 归一化为对象(支持对象或 JSON 字符串) */ const themeObj = computed>(() => { const theme: unknown = brand.value?.theme if (theme && typeof theme === 'object' && !Array.isArray(theme)) return theme as Record if (typeof theme === 'string' && theme.trim()) { try { const parsed = JSON.parse(theme) if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { return parsed as Record } } catch { /* 忽略无法解析的主题字符串 */ } } return {} }) /** 网页名称:品牌顶层 title,缺省回退系统默认标题(settings.title,默认“天豹云仓”)。不再从 theme 约定 siteName */ const siteName = computed(() => brand.value?.title?.trim() || defaultSettings.title || '天豹云仓') /** 登录页文字(slogan):无独立配置字段时为默认文案(登录页用默认标语)。不再从 theme 约定 loginText */ const themeLoginText = computed(() => '') /** 登录页 logo:品牌顶层 logo_url(空→调用方用默认图片)。豁免域名恒为空,强制走前端默认 Logo */ const themeLoginLogoUrl = computed(() => isBrandExemptHost.value ? '' : brand.value?.logo_url?.trim() || '' ) /** 主页面/顶栏 logo:品牌顶层 logo_url(空→调用方用默认图片)。豁免域名恒为空,强制走前端默认 Logo */ const themeMainLogoUrl = computed(() => isBrandExemptHost.value ? '' : brand.value?.logo_url?.trim() || '' ) /** 站点标题/网页名称(theme.siteName 或品牌 title,最后回退系统默认标题 settings.title) */ const siteTitle = computed(() => siteName.value) // 浏览器标题(document.title)由 App.vue 组件统一设置(组件注入 store 可靠),此处不做标题写入 /** 品牌 Logo(空串→调用方回退默认 Logo) */ const logoUrl = computed(() => brand.value?.logo_url?.trim() || '') /** 登录页背景图(空串→调用方用默认背景) */ const loginBgUrl = computed(() => brand.value?.login_bg_url?.trim() || '') /** favicon 图标(空串→调用方用默认) */ const faviconUrl = computed(() => brand.value?.favicon_url?.trim() || '') /** 进行中的加载 Promise:并发调用(main.ts 入口 / 登录页)共享同一次请求,避免重复请求与重复提示 */ let brandLoading: Promise | null = null /** * 按当前访问域名拉取品牌并应用全局(favicon / 登录页标题 / theme CSS 变量)。 * 幂等:已加载直接返回;加载中则复用同一次请求。 */ function loadBrandByDomain(domain?: string): Promise { if (loaded.value) return Promise.resolve() if (brandLoading) return brandLoading brandLoading = doLoadBrandByDomain(domain).finally(() => { brandLoading = null }) return brandLoading } /** 实际加载逻辑(仅由 loadBrandByDomain 调用):失败/未登记域名一律静默回退默认品牌 */ async function doLoadBrandByDomain(domain?: string): Promise { const host = normalizeFrontHost(domain ?? window.location.hostname) // 主域名豁免:不拉取、不应用 getByDomain 品牌配置,直接保持系统默认品牌(默认标题/默认 logo/无主题 CSS 变量) if (!host || FRONT_BRAND_EXEMPT_HOSTS.has(host)) { brand.value = null loaded.value = true applyThemeCssVars(null) applyBrandGlobals() return } try { if (host) { const res: any = await frontConfigGetByDomain({ domain: host }) const data = res?.data && typeof res.data === 'object' ? res.data : res // 未登记域名返回 404 / configured=false → 走默认品牌 const valid = isOkCode(res?.code) && data?.configured !== false brand.value = valid ? (data as FrontConfigPublicItem) : null } } catch (e) { // 未登记/未验证域名(404「域名未配置」)属预期分支:已由接口层静默(silentError)不弹提示, // 这里仅开发环境记一条调试日志,随后回退系统默认品牌 if (import.meta.env.DEV) console.debug('[frontBrand] 未取到域名品牌,使用默认品牌', e) brand.value = null } finally { loaded.value = true // 无论成功/失败都应用主题:无 theme/brand=null 时清除上一次已应用的 CSS 变量,避免换域名后残留旧主题 applyThemeCssVars(brand.value?.theme) applyBrandGlobals() // 浏览器标题由 App.vue 监听 frontBrand.loaded/siteTitle 统一设置:成功→品牌名;失败/豁免→默认“天豹云仓”。 // 追加兜底:品牌加载成功后短时轮询修正标题站点名(应对运行环境存在重复模块/其它写入把标题写成默认的情况), // 保证最终标题稳定为品牌名。 if (brand.value) { let guardTries = 0 const guardTimer = window.setInterval(() => { const site = siteTitle.value || '天豹云仓' const cur = document.title || '' if (cur !== site && !cur.endsWith(` - ${site}`)) { const sep = cur.lastIndexOf(' - ') document.title = sep > 0 ? `${cur.slice(0, sep)} - ${site}` : site } if (++guardTries >= 12 || document.title === site || document.title.endsWith(` - ${site}`)) { window.clearInterval(guardTimer) } }, 200) } } } /** 已应用到 的 CSS 变量列表(用于换品牌/无品牌时清理) */ let appliedCssVars: string[] = [] function isPlainCssValue(v: unknown): v is string | number { return typeof v === 'string' || typeof v === 'number' } function clearAppliedThemeCssVars(): void { if (!document?.documentElement) return const style = document.documentElement.style appliedCssVars.forEach((key) => style.removeProperty(key)) appliedCssVars = [] } /** * 把品牌 theme 映射为 CSS 变量并应用到 (A5)。 * 约定:theme 顶层键 → CSS 变量 `--`,值为标量(字符串/数字)时写入; * 键需符合 [A-Za-z_][A-Za-z0-9_-]*,非法键/嵌套对象忽略。null/undefined 清除已应用变量。 */ function applyThemeCssVars(theme: unknown): void { if (!document?.documentElement) return clearAppliedThemeCssVars() if (!theme || typeof theme !== 'object' || Array.isArray(theme)) return const style = document.documentElement.style Object.entries(theme as Record).forEach(([key, value]) => { if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) return // 文案/资源类约定键不映射 CSS 变量(由页面按语义消费) if (FRONT_THEME_DEFAULT_KEYS.includes(key as (typeof FRONT_THEME_DEFAULT_KEYS)[number])) return if (!isPlainCssValue(value)) return const cssVar = `--${key}` style.setProperty(cssVar, String(value)) appliedCssVars.push(cssVar) }) } /** 应用全局品牌元素:favicon;登录页(未登录首屏)标题 */ function applyBrandGlobals(): void { const b = brand.value if (!b) return if (b.favicon_url?.trim()) { const icon = document.querySelector('link[rel~="icon"]') if (icon) icon.href = b.favicon_url.trim() } // 浏览器标题(document.title)由 App.vue 组件统一设置,此处仅处理 favicon } return { loaded, brand, isBrandExemptHost, themeObj, siteName, siteTitle, themeLoginText, themeLoginLogoUrl, themeMainLogoUrl, logoUrl, loginBgUrl, faviconUrl, loadBrandByDomain, applyThemeCssVars, applyBrandGlobals } })