App.vue 15 KB

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