App.vue 15 KB

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