App.vue 12 KB

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