App.vue 12 KB

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