App.vue 15 KB

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