| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511 |
- <script setup>
- import { ref, onMounted, nextTick, watch, onUnmounted, getCurrentInstance } from 'vue'
- import { useI18n } from 'vue-i18n'
- import config from '@/config'
- const { t, locale } = useI18n()
- const { Host80 } = config
- import {
- onLoad,
- onShow,
- onLaunch,
- } from '@dcloudio/uni-app'
- import {
- updateRoute,
- } from '@/hooks/useRoute'
- import useGlobalStore from '@/stores/use-global-store'
- import { userToken } from '@/composables/config'
- import { useAppUpdate } from '@/hooks/useAppUpdate'
- const { checkUpdate } = useAppUpdate()
- const globalStore = useGlobalStore()
- onLoad((options) => {
- updateRoute()
- // checkUpdate()
- })
- onShow((options) => {
- updateRoute()
- // checkUpdate()
- handleSignupRoute(options)
- })
- // App.vue 或你的初始化文件中
- function initTheme() {
- // #ifdef H5
- // H5 端:使用 matchMedia 主动获取当前系统主题
- const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
- const theme = isDarkMode ? 'dark' : 'light'
- globalStore.setGlobalTheme(theme)
- // 监听变化(你的 onThemeChange 已经能工作,但可以再加一层保险)
- const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
- const handleChange = (e) => {
- const newTheme = e.matches ? 'dark' : 'light'
- globalStore.setGlobalTheme(newTheme)
- }
- // 兼容旧版浏览器
- if (darkModeQuery.addEventListener) {
- darkModeQuery.addEventListener('change', handleChange)
- } else {
- darkModeQuery.addListener(handleChange)
- }
- // 设置 data-bs-theme 属性到 html 标签
- document.documentElement.setAttribute('data-bs-theme', theme)
- document.documentElement.setAttribute('data-color-theme', 'blue')
- // 同时设置到 body 标签
- document.body.setAttribute('data-bs-theme', theme)
- document.body.setAttribute('data-color-theme', 'blue')
- // #endif
- // #ifdef APP-PLUS
- // App 端:使用原生 API
- uni.getSystemInfo({
- success: (res) => {
- let theme = res.osTheme || 'light'
- globalStore.setGlobalTheme(theme)
- },
- })
- uni.onThemeChange((res) => {
- globalStore.setGlobalTheme(res.theme)
- })
- // #endif
- }
- onLaunch((options) => {
- // updateRoute();
- // checkUpdate()
- // 调用初始化
- // initTheme()
- // #ifdef APP-PLUS
- uni.getSystemInfo({
- success: res => { // android且非谷歌渠道才执行
- if(res.platform=="android"){
- // 区分是否谷歌打包:用渠道名/manifest自定义参数
- let channel = plus.runtime.channel;
- if(channel != "google"){
- // 仅国内APK执行代码
- checkUpdate()
- // console.log('普通APK专属逻辑')
- }
- } }
- })
- // checkWgtUpdate()
- // #endif
- // #ifdef H5
- // 处理 signup 路径
- document.title = 'CWGMarkets'
- // 防止后面又被改掉,再加个定时器兜底
- setInterval(() => {
- if (!document.title) document.title = 'CWGMarkets'
- }, 500)
- // #endif
- })
- // 解析 URL 参数
- const parseUrlParams = () => {
- const params = {}
- // #ifdef H5
- // H5 端:直接从浏览器 URL 解析
- if (typeof window !== 'undefined' && window.location) {
- const href = window.location.href
- // 解析 hash 部分
- const hashIndex = href.indexOf('#')
- if (hashIndex !== -1) {
- const hash = href.substring(hashIndex + 1)
- // 解析路径
- const pathMatch = hash.match(/^\/([^/?]+)/)
- if (pathMatch) {
- params.path = pathMatch[1]
- }
- // 解析路径参数 signup/19628/RHOP4WVa/B0
- const pathParams = hash.match(/^\/signup\/([^/]+)\/?([^/]+)?\/?([^/]+)?/)
- if (pathParams) {
- params.path = 'signup'
- params.p1 = pathParams[1]
- params.p2 = pathParams[2]
- params.p3 = pathParams[3]
- }
- // 解析 query 参数
- const queryIndex = hash.indexOf('?')
- if (queryIndex !== -1) {
- const queryStr = hash.substring(queryIndex + 1)
- const pairs = queryStr.split('&')
- pairs.forEach(pair => {
- const [key, value] = pair.split('=')
- if (key && value) {
- params[key] = decodeURIComponent(value)
- }
- })
- }
- }
- }
- // #endif
- // #ifndef H5
- // App 端:从 options 参数获取
- if (typeof options === 'object' && options !== null) {
- Object.assign(params, options)
- }
- // #endif
- return params
- }
- // #ifdef H5
- /** 当前 hash 路径(不含 query) */
- const getHashPath = () => {
- if (typeof window === 'undefined' || !window.location?.href) return ''
- const hashIndex = window.location.href.indexOf('#')
- if (hashIndex === -1) return ''
- let hash = window.location.href.substring(hashIndex + 1)
- const queryIndex = hash.indexOf('?')
- if (queryIndex !== -1) hash = hash.substring(0, queryIndex)
- if (!hash) return '/'
- return hash.startsWith('/') ? hash : `/${hash}`
- }
- /** hash 是否在 __uniRoutes 白名单内(匹配 path / alias / meta.route) */
- const isInUniRoutes = (hashPath) => {
- if (typeof __uniRoutes === 'undefined' || !__uniRoutes?.length) return true
- const normalized = (hashPath || '/').replace(/\/$/, '') || '/'
- return __uniRoutes.some((route) => {
- const candidates = [
- route.path,
- route.alias,
- route.meta?.route ? `/${route.meta.route.replace(/^\//, '')}` : '',
- ].filter(Boolean)
- return candidates.some((p) => {
- const item = (p || '/').replace(/\/$/, '') || '/'
- return normalized === item
- })
- })
- }
- /** 未登录可访问:登录 / 注册 / 修改密码 */
- const AUTH_PUBLIC_PATHS = [
- '/pages/login/index',
- '/pages/login/regist',
- '/pages/login/reset',
- ]
- const isAuthPublicPath = (hashPath) => {
- const normalized = (hashPath || '/').replace(/\/$/, '') || '/'
- return AUTH_PUBLIC_PATHS.includes(normalized)
- }
- // #endif
- // 处理 signup 和 signin 路径(仅 H5 端)
- const handleSignupRoute = (options) => {
- // #ifdef H5
- // 解析 URL 参数(从浏览器 URL 解析)
- const query = parseUrlParams()
- console.log('解析到的参数:', query)
- // 处理 signin 路径(自动登录)
- if (query.path === 'signin') {
- // 跳转到登录页面 有就携带 token 参数
- const loginUrl = query?.sysLoginToken ? `/pages/login/index?sysLoginToken=${encodeURIComponent(query.sysLoginToken)}` : '/pages/login/index'
- console.log('跳转到登录页面:', loginUrl)
- uni.reLaunch({
- url: loginUrl,
- success: () => {
- console.log('跳转成功')
- },
- fail: (err) => {
- console.error('跳转失败:', err)
- },
- })
- return
- }
- // 判断是否是 signup 路径
- const isSignup = query.path === 'signup' || query.s || query.signup || query.activeTab === '2'
- if (!isSignup) {
- const hashPath = getHashPath()
- // 未登录:仅允许登录 / 注册 / 修改密码
- if (!userToken.value) {
- if (!isAuthPublicPath(hashPath)) {
- uni.reLaunch({ url: '/pages/login/index' })
- }
- return
- }
- // 已登录:不在 __uniRoutes 内的 hash 路径跳转登录页
- if (!isInUniRoutes(hashPath)) {
- uni.reLaunch({ url: '/pages/login/index' })
- }
- return
- }
- // 已在登录页注册 Tab(含代理参数),无需重复 reLaunch
- const hashPath = getHashPath()
- if (hashPath === '/pages/login/index' && String(query.activeTab) === '2') {
- return
- }
- // 获取参数
- const id = query.id || query.agentId || query.p1 || ''
- const subId = query.subId || query.w || query.p2 || ''
- const code = query.code || query.oc || query.p3 || ''
- // 构建登录页面 URL
- let loginUrl = '/pages/login/index?activeTab=2'
- // 携带参数
- if (id) loginUrl += `&id=${id}`
- if (subId) loginUrl += `&subId=${subId}`
- if (code) loginUrl += `&code=${code}`
- console.log('跳转到:', loginUrl)
- // 跳转到注册页面
- uni.reLaunch({
- url: loginUrl,
- success: () => {
- console.log('跳转成功')
- },
- fail: (err) => {
- console.error('跳转失败:', err)
- },
- })
- // #endif
- }
- watch(locale, () => {
- // const currentPath = route.path;
- // menu.value.forEach((item, index) => {
- // if (item.children) {
- // const isActive = item.children.some(child => child.path.includes(currentPath));
- // menu.value[index].isOpenMenu = isActive;
- // if (isActive) {
- // nextTick(() => {
- // updateSubmenuHeight(index);
- // });
- // }
- // }
- // });
- }, { immediate: true })
- // 检测版本号更新
- const checkWgtUpdate = async () => {
- console.log(Host80)
- try {
- console.log(Host80)
- const currentVersion = await getCurrentVersion()
- const res = await uni.request({
- url: `${Host80}/wgt/list.json?_t=${Date.now()}`,
- method: 'GET',
- timeout: 5000,
- })
- console.log('up:filedata', res)
- console.log(currentVersion, 'currentVersion')
- const files = res.data?.files || []
- if (!files.length) return
- const latestFile = files[files.length - 1]
- const latestVersion = latestFile
- console.log('last', latestFile, latestVersion)
- if (!latestFile) return
- const lastInstalled = uni.getStorageSync('lastWgtVersion')
- console.log(lastInstalled, 'lastInstalled')
- if (latestVersion === lastInstalled) return
- console.log('版本对比', compareVersion(latestVersion, currentVersion))
- if (compareVersion(latestVersion, currentVersion) > 0) {
- downloadAndInstall(latestVersion)
- }
- } catch (e) {
- console.log('[wgt] update check failed', e)
- }
- }
- // 下载并安装
- const downloadAndInstall = (version) => {
- //TODO: 需要根据版本来确定url
- const url = `${Host80}/wgt/CwgApp_${version}.wgt`
- console.log(url, 'downloadurl')
- uni.downloadFile({
- url,
- success: (res) => {
- if (res.statusCode === 200) {
- const filePath = res.tempFilePath
- plus.runtime.install(
- filePath, {
- force: true,
- },
- () => {
- uni.setStorageSync('lastWgtVersion', version)
- console.log('[wgt] install success:', version)
- uni.setStorageSync('wgtNeedRestart', true)
- uni.showToast({
- title: t('mine.p37'),
- icon: 'success',
- },
- )
- plus.runtime.restart()
- },
- (err) => {
- console.error('[wgt] install failed:', err)
- },
- )
- } else {
- console.error('[wgt] download status error:', res.statusCode)
- }
- },
- fail: (err) => {
- console.error('[wgt] download failed:', err)
- },
- })
- }
- // 获取当前版本
- const getCurrentVersion = async () => {
- return new Promise((resolve, reject) => {
- // #ifdef APP-PLUS
- try {
- plus.runtime.getProperty(plus.runtime.appid, (info) => {
- resolve(info.version)
- }, (error) => {
- reject(error)
- })
- } catch (error) {
- reject(error)
- }
- // #endif
- // #ifndef APP-PLUS
- reject(new Error('Not in APP-PLUS environment'))
- // #endif
- })
- }
- // 对比版本号
- const compareVersion = (v1, v2) => {
- const s1 = v1.split('.').map(Number)
- const s2 = v2.split('.').map(Number)
- const len = Math.max(s1.length, s2.length)
- for (let i = 0; i < len; i++) {
- const n1 = s1[i] || 0
- const n2 = s2[i] || 0
- if (n1 > n2) return 1
- if (n1 < n2) return -1
- }
- return 0
- }
- onMounted(() => {
- const sysInfo = uni.getSystemInfoSync()
- globalStore.setBarHeight(sysInfo.statusBarHeight || 60)
- // ---------- 新增 H5 端专属初始化 ----------
- // 仅在 H5 端执行(通过环境判断)
- // #ifdef H5
- if (typeof window !== 'undefined') {
- const instance = getCurrentInstance()
- if (instance) {
- window.vm = instance.proxy
- }
- }
- window.addEventListener('hashchange', handleSignupRoute)
- // #endif
- })
- onUnmounted(() => {
- // #ifdef H5
- window.removeEventListener('hashchange', handleSignupRoute)
- // #endif
- })
- </script>
- <style>
- /*每个页面公共css */
- </style>
- <style lang="scss">
- /* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
- @import "uview-plus/index.scss";
- @import "@/static/scss/global/global.scss";
- @import "@/static/scss/global/vu.css";
- @import "/static/scss/style.scss";
- @font-face {
- font-family: 'Google Sans';
- src: url('/static/Google_Sans/GoogleSans-VariableFont_GRAD,opsz,wght.ttf') format('truetype-variations');
- font-weight: 100 900;
- font-style: normal;
- font-display: swap;
- }
- /* 全局字体,不破坏 uni-icons 图标 */
- view,
- text,
- button,
- input,
- textarea,
- label {
- font-family: 'Google Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- font-weight: 400;
- }
- /* 专门保护 uni-icons 不被覆盖 */
- .uni-icon,
- [class*="uni-icons-"],
- .uni-icons {
- font-family: uniicons !important;
- }
- /* 让整个项目文字都能选中 */
- * {
- -webkit-user-select: text !important;
- user-select: text !important;
- }
- /* 修复滚动层无法选中 */
- view,
- text,
- div,
- span {
- -webkit-user-select: text !important;
- user-select: text !important;
- }
- /* 强制修复 uni-datetime-picker 重复渲染双日历 */
- // .uni-calendar+.uni-calendar {
- // display: none !important;
- // }
- :deep(.u-toolbar__wrapper__confirm) {
- font-size: 20px !important;
- }
- :deep(.u-toolbar__wrapper__cancel) {
- font-size: 20px !important;
- }
- .page {
- /* padding: 31px 31px 110px 31px; */
- box-sizing: border-box;
- /* background: var(--main-bg); */
- }
- html {
- --bs-bg-opacity: 1;
- background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
- font-size: 16px !important;
- }
- uni-page-body {
- height: 100%;
- }
- page {
- --bs-bg-opacity: 1;
- background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
- }
- </style>
|