App.vue 15 KB

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