App.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. <script setup>
  2. import { ref, onMounted, nextTick, watch, onUnmounted, getCurrentInstance } from 'vue'
  3. import { useI18n } from 'vue-i18n'
  4. import config from '@/config'
  5. import { useMouseTooltip } from '@/utils/useMouseTooltip'
  6. const { t, locale } = useI18n()
  7. // 勿解构 Host80,动态域名下需每次读取 config.Host80
  8. import {
  9. onLoad,
  10. onShow,
  11. onLaunch,
  12. } from '@dcloudio/uni-app'
  13. import {
  14. updateRoute,
  15. } from '@/hooks/useRoute'
  16. import useGlobalStore from '@/stores/use-global-store'
  17. import { userToken } from '@/composables/config'
  18. import { useAppUpdate } from '@/hooks/useAppUpdate'
  19. import {
  20. whenDomainReady,
  21. refreshDynamicDomainIfExpired,
  22. } from '@/utils/dynamicDomain'
  23. const { checkUpdate } = useAppUpdate()
  24. const globalStore = useGlobalStore()
  25. import { useWindowWidth } from '@/composables/useWindowWidth'
  26. const windowWidth = useWindowWidth(300)
  27. onLoad((options) => {
  28. updateRoute()
  29. // checkUpdate()
  30. })
  31. onShow((options) => {
  32. updateRoute()
  33. // checkUpdate()
  34. handleSignupRoute(options)
  35. // #ifdef APP-PLUS
  36. refreshDynamicDomainIfExpired().catch((e) => {
  37. console.warn('[dynamicDomain] 前台刷新失败', e)
  38. })
  39. // #endif
  40. })
  41. // App.vue 或你的初始化文件中
  42. function initTheme() {
  43. // #ifdef H5
  44. // H5 端:使用 matchMedia 主动获取当前系统主题
  45. const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
  46. const theme = isDarkMode ? 'dark' : 'light'
  47. globalStore.setGlobalTheme(theme)
  48. // 监听变化(你的 onThemeChange 已经能工作,但可以再加一层保险)
  49. const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
  50. const handleChange = (e) => {
  51. const newTheme = e.matches ? 'dark' : 'light'
  52. globalStore.setGlobalTheme(newTheme)
  53. }
  54. // 兼容旧版浏览器
  55. if (darkModeQuery.addEventListener) {
  56. darkModeQuery.addEventListener('change', handleChange)
  57. } else {
  58. darkModeQuery.addListener(handleChange)
  59. }
  60. // 设置 data-bs-theme 属性到 html 标签
  61. document.documentElement.setAttribute('data-bs-theme', theme)
  62. document.documentElement.setAttribute('data-color-theme', 'blue')
  63. // 同时设置到 body 标签
  64. document.body.setAttribute('data-bs-theme', theme)
  65. document.body.setAttribute('data-color-theme', 'blue')
  66. // #endif
  67. // #ifdef APP-PLUS
  68. // App 端:使用原生 API
  69. uni.getSystemInfo({
  70. success: (res) => {
  71. let theme = res.osTheme || 'light'
  72. globalStore.setGlobalTheme(theme)
  73. },
  74. })
  75. uni.onThemeChange((res) => {
  76. globalStore.setGlobalTheme(res.theme)
  77. })
  78. // #endif
  79. }
  80. onLaunch((options) => {
  81. // updateRoute();
  82. // checkUpdate()
  83. // 调用初始化
  84. // initTheme()
  85. // #ifdef APP-PLUS
  86. whenDomainReady().then(() => {
  87. uni.getSystemInfo({
  88. success: (res) => {
  89. if (res.platform === 'android') {
  90. const channel = plus.runtime.channel
  91. if (channel !== 'google') {
  92. checkUpdate()
  93. }
  94. }
  95. },
  96. })
  97. })
  98. // #endif
  99. // #ifdef H5
  100. // 处理 signup 路径
  101. document.title = 'CWGMarkets'
  102. // 防止后面又被改掉,再加个定时器兜底
  103. setInterval(() => {
  104. if (!document.title) document.title = 'CWGMarkets'
  105. }, 500)
  106. // #endif
  107. })
  108. // 解析 URL 参数
  109. const parseUrlParams = () => {
  110. const params = {}
  111. // #ifdef H5
  112. // H5 端:直接从浏览器 URL 解析
  113. if (typeof window !== 'undefined' && window.location) {
  114. const href = window.location.href
  115. // 解析 hash 部分
  116. const hashIndex = href.indexOf('#')
  117. if (hashIndex !== -1) {
  118. const hash = href.substring(hashIndex + 1)
  119. // 解析路径
  120. const pathMatch = hash.match(/^\/([^/?]+)/)
  121. if (pathMatch) {
  122. params.path = pathMatch[1]
  123. }
  124. // 解析路径参数 signup/19628/RHOP4WVa/B0
  125. const pathParams = hash.match(/^\/signup\/([^/]+)\/?([^/]+)?\/?([^/]+)?/)
  126. if (pathParams) {
  127. params.path = 'signup'
  128. params.p1 = pathParams[1]
  129. params.p2 = pathParams[2]
  130. params.p3 = pathParams[3]
  131. }
  132. // 解析 query 参数
  133. const queryIndex = hash.indexOf('?')
  134. if (queryIndex !== -1) {
  135. const queryStr = hash.substring(queryIndex + 1)
  136. const pairs = queryStr.split('&')
  137. pairs.forEach(pair => {
  138. const [key, value] = pair.split('=')
  139. if (key && value) {
  140. params[key] = decodeURIComponent(value)
  141. }
  142. })
  143. }
  144. }
  145. }
  146. // #endif
  147. // #ifndef H5
  148. // App 端:从 options 参数获取
  149. if (typeof options === 'object' && options !== null) {
  150. Object.assign(params, options)
  151. }
  152. // #endif
  153. return params
  154. }
  155. // #ifdef H5
  156. /** 当前 hash 路径(不含 query) */
  157. const getHashPath = () => {
  158. if (typeof window === 'undefined' || !window.location?.href) return ''
  159. const hashIndex = window.location.href.indexOf('#')
  160. if (hashIndex === -1) return ''
  161. let hash = window.location.href.substring(hashIndex + 1)
  162. const queryIndex = hash.indexOf('?')
  163. if (queryIndex !== -1) hash = hash.substring(0, queryIndex)
  164. if (!hash) return '/'
  165. return hash.startsWith('/') ? hash : `/${hash}`
  166. }
  167. /** hash 是否在 __uniRoutes 白名单内(匹配 path / alias / meta.route) */
  168. const isInUniRoutes = (hashPath) => {
  169. if (typeof __uniRoutes === 'undefined' || !__uniRoutes?.length) return true
  170. const normalized = (hashPath || '/').replace(/\/$/, '') || '/'
  171. return __uniRoutes.some((route) => {
  172. const candidates = [
  173. route.path,
  174. route.alias,
  175. route.meta?.route ? `/${route.meta.route.replace(/^\//, '')}` : '',
  176. ].filter(Boolean)
  177. return candidates.some((p) => {
  178. const item = (p || '/').replace(/\/$/, '') || '/'
  179. return normalized === item
  180. })
  181. })
  182. }
  183. /** 未登录可访问:登录 / 注册 / 修改密码 */
  184. const AUTH_PUBLIC_PATHS = [
  185. '/pages/login/index',
  186. '/pages/login/regist',
  187. '/pages/login/reset',
  188. ]
  189. const isAuthPublicPath = (hashPath) => {
  190. const normalized = (hashPath || '/').replace(/\/$/, '') || '/'
  191. return AUTH_PUBLIC_PATHS.includes(normalized)
  192. }
  193. // #endif
  194. // 处理 signup 和 signin 路径(仅 H5 端)
  195. const handleSignupRoute = (options) => {
  196. // #ifdef H5
  197. // 解析 URL 参数(从浏览器 URL 解析)
  198. const query = parseUrlParams()
  199. console.log('解析到的参数:', query)
  200. // 处理 signin 路径(自动登录)
  201. if (query.path === 'signin') {
  202. // 跳转到登录页面 有就携带 token 参数
  203. const loginUrl = query?.sysLoginToken ? `/pages/login/index?sysLoginToken=${encodeURIComponent(query.sysLoginToken)}` : '/pages/login/index'
  204. console.log('跳转到登录页面:', loginUrl)
  205. uni.reLaunch({
  206. url: loginUrl,
  207. success: () => {
  208. console.log('跳转成功')
  209. },
  210. fail: (err) => {
  211. console.error('跳转失败:', err)
  212. },
  213. })
  214. return
  215. }
  216. // 判断是否是 signup 路径
  217. const isSignup = query.path === 'signup' || query.s || query.signup || query.activeTab === '2'
  218. if (!isSignup) {
  219. const hashPath = getHashPath()
  220. // 未登录:仅允许登录 / 注册 / 修改密码
  221. if (!userToken.value) {
  222. if (!isAuthPublicPath(hashPath)) {
  223. uni.reLaunch({ url: '/pages/login/index' })
  224. }
  225. return
  226. }
  227. // 已登录:不在 __uniRoutes 内的 hash 路径跳转登录页
  228. if (!isInUniRoutes(hashPath)) {
  229. uni.reLaunch({ url: '/pages/login/index' })
  230. }
  231. return
  232. }
  233. // 已在登录页注册 Tab(含代理参数),无需重复 reLaunch
  234. const hashPath = getHashPath()
  235. if (hashPath === '/pages/login/index' && String(query.activeTab) === '2') {
  236. return
  237. }
  238. // 获取参数
  239. const id = query.id || query.agentId || query.p1 || ''
  240. const subId = query.subId || query.w || query.p2 || ''
  241. const code = query.code || query.oc || query.p3 || ''
  242. // 构建登录页面 URL
  243. let loginUrl = '/pages/login/index?activeTab=2'
  244. // 携带参数
  245. if (id) loginUrl += `&id=${id}`
  246. if (subId) loginUrl += `&subId=${subId}`
  247. if (code) loginUrl += `&code=${code}`
  248. console.log('跳转到:', loginUrl)
  249. // 跳转到注册页面
  250. uni.reLaunch({
  251. url: loginUrl,
  252. success: () => {
  253. console.log('跳转成功')
  254. },
  255. fail: (err) => {
  256. console.error('跳转失败:', err)
  257. },
  258. })
  259. // #endif
  260. }
  261. watch(locale, () => {
  262. // const currentPath = route.path;
  263. // menu.value.forEach((item, index) => {
  264. // if (item.children) {
  265. // const isActive = item.children.some(child => child.path.includes(currentPath));
  266. // menu.value[index].isOpenMenu = isActive;
  267. // if (isActive) {
  268. // nextTick(() => {
  269. // updateSubmenuHeight(index);
  270. // });
  271. // }
  272. // }
  273. // });
  274. }, { immediate: true })
  275. // 检测版本号更新
  276. const checkWgtUpdate = async () => {
  277. await whenDomainReady()
  278. try {
  279. const currentVersion = await getCurrentVersion()
  280. const res = await uni.request({
  281. url: `${config.Host80}/wgt/list.json?_t=${Date.now()}`,
  282. method: 'GET',
  283. timeout: 5000,
  284. })
  285. console.log('up:filedata', res)
  286. console.log(currentVersion, 'currentVersion')
  287. const files = res.data?.files || []
  288. if (!files.length) return
  289. const latestFile = files[files.length - 1]
  290. const latestVersion = latestFile
  291. console.log('last', latestFile, latestVersion)
  292. if (!latestFile) return
  293. const lastInstalled = uni.getStorageSync('lastWgtVersion')
  294. console.log(lastInstalled, 'lastInstalled')
  295. if (latestVersion === lastInstalled) return
  296. console.log('版本对比', compareVersion(latestVersion, currentVersion))
  297. if (compareVersion(latestVersion, currentVersion) > 0) {
  298. downloadAndInstall(latestVersion)
  299. }
  300. } catch (e) {
  301. console.log('[wgt] update check failed', e)
  302. }
  303. }
  304. // 下载并安装
  305. const downloadAndInstall = (version) => {
  306. //TODO: 需要根据版本来确定url
  307. const url = `${config.Host80}/wgt/CwgApp_${version}.wgt`
  308. console.log(url, 'downloadurl')
  309. uni.downloadFile({
  310. url,
  311. success: (res) => {
  312. if (res.statusCode === 200) {
  313. const filePath = res.tempFilePath
  314. plus.runtime.install(
  315. filePath, {
  316. force: true,
  317. },
  318. () => {
  319. uni.setStorageSync('lastWgtVersion', version)
  320. console.log('[wgt] install success:', version)
  321. uni.setStorageSync('wgtNeedRestart', true)
  322. uni.showToast({
  323. title: t('mine.p37'),
  324. icon: 'success',
  325. },
  326. )
  327. plus.runtime.restart()
  328. },
  329. (err) => {
  330. console.error('[wgt] install failed:', err)
  331. },
  332. )
  333. } else {
  334. console.error('[wgt] download status error:', res.statusCode)
  335. }
  336. },
  337. fail: (err) => {
  338. console.error('[wgt] download failed:', err)
  339. },
  340. })
  341. }
  342. // 获取当前版本
  343. const getCurrentVersion = async () => {
  344. return new Promise((resolve, reject) => {
  345. // #ifdef APP-PLUS
  346. try {
  347. plus.runtime.getProperty(plus.runtime.appid, (info) => {
  348. resolve(info.version)
  349. }, (error) => {
  350. reject(error)
  351. })
  352. } catch (error) {
  353. reject(error)
  354. }
  355. // #endif
  356. // #ifndef APP-PLUS
  357. reject(new Error('Not in APP-PLUS environment'))
  358. // #endif
  359. })
  360. }
  361. // 对比版本号
  362. const compareVersion = (v1, v2) => {
  363. const s1 = v1.split('.').map(Number)
  364. const s2 = v2.split('.').map(Number)
  365. const len = Math.max(s1.length, s2.length)
  366. for (let i = 0; i < len; i++) {
  367. const n1 = s1[i] || 0
  368. const n2 = s2[i] || 0
  369. if (n1 > n2) return 1
  370. if (n1 < n2) return -1
  371. }
  372. return 0
  373. }
  374. onMounted(() => {
  375. const sysInfo = uni.getSystemInfoSync()
  376. globalStore.setBarHeight(sysInfo.statusBarHeight || 60)
  377. // ---------- 新增 H5 端专属初始化 ----------
  378. // 仅在 H5 端执行(通过环境判断)
  379. // #ifdef H5
  380. if (typeof window !== 'undefined') {
  381. const instance = getCurrentInstance()
  382. if (instance) {
  383. window.vm = instance.proxy
  384. }
  385. }
  386. window.addEventListener('hashchange', handleSignupRoute)
  387. if (windowWidth.value < 700) return
  388. window._destroyTooltip = useMouseTooltip()
  389. // #endif
  390. })
  391. onUnmounted(() => {
  392. // #ifdef H5
  393. window.removeEventListener('hashchange', handleSignupRoute)
  394. if (windowWidth.value < 700) return
  395. if (window._destroyTooltip) window._destroyTooltip()
  396. // #endif
  397. })
  398. </script>
  399. <style>
  400. /*每个页面公共css */
  401. </style>
  402. <style lang="scss">
  403. /* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
  404. @import "uview-plus/index.scss";
  405. @import "@/static/scss/global/global.scss";
  406. @import "@/static/scss/global/vu.css";
  407. @import "/static/scss/style.scss";
  408. @font-face {
  409. font-family: 'Google Sans';
  410. src: url('/static/Google_Sans/GoogleSans-VariableFont_GRAD,opsz,wght.ttf') format('truetype-variations');
  411. font-weight: 100 900;
  412. font-style: normal;
  413. font-display: swap;
  414. }
  415. /* 全局字体,不破坏 uni-icons 图标 */
  416. view,
  417. text,
  418. button,
  419. input,
  420. textarea,
  421. label {
  422. font-family: 'Google Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  423. font-weight: 400;
  424. }
  425. /* 专门保护 uni-icons 不被覆盖 */
  426. .uni-icon,
  427. [class*="uni-icons-"],
  428. .uni-icons {
  429. font-family: uniicons !important;
  430. }
  431. /* 让整个项目文字都能选中 */
  432. * {
  433. -webkit-user-select: text !important;
  434. user-select: text !important;
  435. }
  436. /* 修复滚动层无法选中 */
  437. view,
  438. text,
  439. div,
  440. span {
  441. -webkit-user-select: text !important;
  442. user-select: text !important;
  443. }
  444. /* 强制修复 uni-datetime-picker 重复渲染双日历 */
  445. // .uni-calendar+.uni-calendar {
  446. // display: none !important;
  447. // }
  448. :deep(.u-toolbar__wrapper__confirm) {
  449. font-size: 20px !important;
  450. }
  451. :deep(.u-toolbar__wrapper__cancel) {
  452. font-size: 20px !important;
  453. }
  454. .page {
  455. /* padding: 31px 31px 110px 31px; */
  456. box-sizing: border-box;
  457. /* background: var(--main-bg); */
  458. }
  459. html {
  460. --bs-bg-opacity: 1;
  461. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  462. font-size: 16px !important;
  463. }
  464. uni-page-body {
  465. height: 100%;
  466. }
  467. page {
  468. --bs-bg-opacity: 1;
  469. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  470. }
  471. </style>