| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741 |
- <script setup lang="ts">
- import { onLaunch, onShow, onHide } from '@dcloudio/uni-app';
- import { watch } from 'vue';
- import { createPinia } from 'pinia';
- import { useUserStore } from './store/user';
- import { useNavigationStore } from './store/navigation';
- import { initDebug } from './utils/debug';
- import { initAnalytics } from './utils/analytics';
- import MiniPlayer from './components/MiniPlayer.vue';
- import CreditInsufficientModal from './components/CreditInsufficientModal.vue';
- // 初始化全局调试工具
- initDebug();
- // ==================== 微信环境检测 ====================
- function isInWechatBrowser(): boolean {
- // #ifdef H5
- const ua = navigator.userAgent.toLowerCase();
- return ua.includes('micromessenger');
- // #endif
- return false;
- }
- // ==================== 微信 OAuth 回调处理 ====================
- async function handleWechatOAuthCallback() {
- // 只在 H5 环境处理
- // #ifdef H5
- const searchParams = new URLSearchParams(window.location.search);
- const code = searchParams.get('code');
- const state = searchParams.get('state');
- console.log('[App] handleWechatOAuthCallback 触发', { code: !!code, fullUrl: window.location.href });
- if (!code) {
- console.log('[App] 无 code 参数,跳过 OAuth 处理');
- return; // 不是 OAuth 回调,跳过
- }
- console.log('[App] 检测到微信 OAuth 回调,处理 code...');
- uni.showLoading({ title: '授权中...' });
- try {
- const { post } = await import('./utils/request');
- const result = await post<{ openid: string }>('/payment/wechat/openid', { code });
- if (result.openid) {
- console.log('[App] OpenID 获取成功');
- // 先尝试根据 openid 自动登录
- try {
- const userStore = useUserStore();
- await userStore.loginByOpenid(result.openid);
- console.log('[App] OpenID 已绑定,自动登录成功');
- // 清除 URL 参数,停留在当前页
- searchParams.delete('code');
- searchParams.delete('state');
- const newSearch = searchParams.toString();
- const newUrl = window.location.origin + window.location.pathname
- + (newSearch ? '?' + newSearch : '') + window.location.hash;
- window.history.replaceState({}, '', newUrl);
- uni.hideLoading();
- uni.showToast({ title: '自动登录成功', icon: 'success' });
- return;
- } catch (e: any) {
- if (e?.message?.includes('未绑定') || e?.code === -1) {
- // 自动登录失败(未绑定账号),继续正常流程
- console.log('[App] OpenID 未绑定账号,将存储待登录');
- } else {
- console.error('[App] 自动登录异常:', e);
- }
- }
- // 未绑定账号或自动登录失败,存储 openid 等待手机号登录绑定
- localStorage.setItem('wx_openid', result.openid);
- // 🔧 标记刚从 OAuth 回来,页面组件可据此自动触发支付
- try { sessionStorage.setItem('wx_oauth_just_done', '1'); } catch (_) {}
- // 恢复之前保存的页面上下文
- let returnUrl: string | null = null;
- try {
- returnUrl = sessionStorage.getItem('wx_oauth_return');
- sessionStorage.removeItem('wx_oauth_return');
- } catch (_) {}
- if (returnUrl) {
- // 跳回原始页面(保留完整 hash 路由)
- // 用 location.replace 避免产生多余的历史记录
- window.location.replace(returnUrl);
- } else {
- // 没有上下文,清除 URL 参数后停留在当前页
- searchParams.delete('code');
- searchParams.delete('state');
- const newSearch = searchParams.toString();
- const newUrl = window.location.origin + window.location.pathname
- + (newSearch ? '?' + newSearch : '') + window.location.hash;
- window.history.replaceState({}, '', newUrl);
- }
- }
- } catch (e) {
- console.error('[App] OAuth 回调处理失败:', e);
- // 清除 URL 参数
- searchParams.delete('code');
- searchParams.delete('state');
- const newSearch = searchParams.toString();
- const newUrl = window.location.origin + window.location.pathname
- + (newSearch ? '?' + newSearch : '');
- window.history.replaceState({}, '', newUrl);
- } finally {
- uni.hideLoading();
- }
- // #endif
- }
- onLaunch(async () => {
- console.log('App Launch');
- // ============ 第一件事:加载导航配置 ============
- // 业务方要求:首次打开必须先获取底部 tab 导航接口,
- // 否则不允许加载任何业务内容。
- const navStore = useNavigationStore();
- try {
- await navStore.loadConfig({ throwOnError: true, timeout: 8000 });
- console.log('[App] 导航配置加载成功,tabs:', navStore.tabList.length);
- } catch (err: any) {
- console.error('[App] 导航配置加载失败,阻塞启动:', err?.message || err);
- // 不再继续后续初始化,等用户在重试 UI 上点击重试
- return;
- }
- const userStore = useUserStore();
- userStore.initUser();
- // 应用夜间模式
- applyDarkMode();
- // 初始化统计
- initAnalytics();
- // 处理微信 OAuth 回调(必须在 initUser 之后)
- // #ifdef H5
- handleWechatOAuthCallback().then(() => {
- // OAuth 回调处理完成后,再执行自动登录检查
- checkAutoLogin();
- });
- // #endif
- });
- // ==================== 全局自动登录检查 ====================
- async function checkAutoLogin() {
- // 只在微信环境下处理
- if (!isInWechatBrowser()) {
- console.log('[App] 非微信环境,跳过自动登录检查');
- return;
- }
- const userStore = useUserStore();
- // 如果已经登录,跳过
- if (userStore.isLoggedIn) {
- console.log('[App] 已登录,跳过自动登录检查');
- return;
- }
- // 检查 localStorage 是否有 openid
- const wxOpenid = localStorage.getItem('wx_openid');
- if (!wxOpenid) {
- console.log('[App] 微信环境无 openid,触发 OAuth 授权');
- // 触发 OAuth 授权
- await triggerWechatOAuth();
- return;
- }
- console.log('[App] 检测到 openid,尝试自动登录:', wxOpenid.substring(0, 8) + '...');
- try {
- await userStore.loginByOpenid(wxOpenid);
- console.log('[App] 自动登录成功!');
- uni.showToast({ title: '自动登录成功', icon: 'success' });
- } catch (e: any) {
- console.log('[App] 自动登录失败(openid 未绑定账号):', e?.message);
- // 不做处理,让用户手动登录
- }
- }
- // ==================== 触发微信 OAuth 授权 ====================
- async function triggerWechatOAuth() {
- // #ifdef H5
- uni.showLoading({ title: '正在跳转微信授权...' });
- try {
- const { get } = await import('./utils/request');
- // 直接使用当前完整 URL 作为回调地址
- const redirectUrl = window.location.href;
- console.log('[App] 授权回调地址:', redirectUrl);
- // 调用后端获取微信授权链接
- const result = await get<{ oauthUrl: string }>(`/payment/wechat/oauth-url?redirect=${encodeURIComponent(redirectUrl)}`);
- console.log('[App] 微信授权链接:', result.oauthUrl);
- // 跳转到微信授权页
- window.location.href = result.oauthUrl;
- } catch (e) {
- console.error('[App] 获取授权链接失败:', e);
- uni.hideLoading();
- uni.showToast({ title: '授权失败,请重试', icon: 'none' });
- }
- // #endif
- }
- onShow(() => {
- console.log('App Show');
- // 同步当前 tab 高亮(处理热更新/外部跳转等场景)
- syncCurrentTabFromPageStack();
- });
- onHide(() => {
- console.log('App Hide');
- });
- // 从页面栈同步当前 tab 高亮
- function syncCurrentTabFromPageStack() {
- try {
- const navStore = useNavigationStore();
- if (!navStore.isReady) return;
- const pages = getCurrentPages();
- const last = pages[pages.length - 1] as any;
- const route = (last && last.route) ? String(last.route) : '';
- if (route) navStore.syncCurrentTabByPagePath(route);
- } catch (_) {
- // 非 H5 环境 getCurrentPages 可能不可用
- }
- }
- // 应用夜间模式
- function applyDarkMode() {
- try {
- const isDark = uni.getStorageSync('dark_mode');
- if (isDark) {
- uni.setStorageSync('is_dark_mode', true);
- }
- } catch (error) {
- console.error('应用夜间模式失败:', error);
- }
- }
- // ==================== 启动态:导航配置重试 ====================
- const navStore = useNavigationStore();
- /**
- * 控制启动浮层 (#boot-splash) 的显示与内容。
- *
- * 该 DOM 元素由 main.ts 在 #app 之外创建,目的是绕过 uni-app H5 的 page HOC
- * (HOC 会吞掉 App.vue 模板里 router-view 之外的子节点,导致 v-if 不生效)。
- * 我们 watch navStore.isReady / loading / loadError 来同步浮层状态。
- */
- function renderBootSplash() {
- if (typeof document === 'undefined') return;
- const splash = document.getElementById('boot-splash');
- if (!splash) return;
- if (navStore.isReady) {
- splash.classList.add('is-hidden');
- return;
- }
- // 显示 splash
- splash.classList.remove('is-hidden');
- const showError = !navStore.loading && !!navStore.loadError;
- const loadingHtml = `
- <div class="boot-spinner"></div>
- <div class="boot-loading-text">正在加载导航…</div>
- <div class="boot-loading-hint">${navStore.loading ? '请稍候' : '准备中'}</div>
- `;
- const errorHtml = `
- <div class="boot-error-icon">⚠️</div>
- <div class="boot-error-title">导航服务连接失败</div>
- <div class="boot-error-message"></div>
- <button class="boot-retry-btn" id="boot-retry-btn">重新连接</button>
- <div class="boot-error-hint">网络异常时,请检查后端服务后重试</div>
- `;
- splash.innerHTML = `
- <div class="boot-logo"><span class="boot-logo-icon">📚</span></div>
- <div class="boot-app-name">AI 有声书</div>
- <div class="boot-state">${showError ? errorHtml : loadingHtml}</div>
- `;
- if (showError) {
- const msgEl = splash.querySelector('.boot-error-message');
- if (msgEl) msgEl.textContent = String(navStore.loadError || '');
- const btn = splash.querySelector('#boot-retry-btn');
- if (btn) {
- btn.addEventListener('click', () => {
- handleNavRetry();
- });
- }
- }
- }
- if (typeof window !== 'undefined') {
- watch(
- () => [navStore.isReady, navStore.loading, navStore.loadError],
- () => {
- renderBootSplash();
- },
- { immediate: true, deep: true }
- );
- }
- async function handleNavRetry() {
- try {
- await navStore.loadConfig({ throwOnError: true, timeout: 8000 });
- // 加载成功后,补充执行原本被阻塞的初始化
- const userStore = useUserStore();
- if (!userStore.token) {
- userStore.initUser();
- }
- applyDarkMode();
- initAnalytics();
- // #ifdef H5
- handleWechatOAuthCallback().then(() => checkAutoLogin());
- // #endif
- } catch (err: any) {
- // 留 store 内的 loadError 给 UI 显示
- console.error('[App] 导航配置重试失败:', err?.message || err);
- }
- }
- </script>
- <template>
- <view id="app">
- <router-view />
- <MiniPlayer />
- <CreditInsufficientModal />
- </view>
- </template>
- <style>
- /* ============================================================
- 全局设计系统 - Global Design System
- ============================================================ */
- /* --- CSS 设计令牌 (Design Tokens) --- */
- :root {
- /* 主色调 - Indigo */
- --color-primary: #4f46e5;
- --color-primary-400: #818cf8;
- --color-primary-500: #6366f1;
- --color-primary-600: #4f46e5;
- --color-primary-700: #4338ca;
- --color-primary-800: #3730a3;
- /* 强调色 - Amber/Orange */
- --color-accent: #f97316;
- --color-accent-400: #fb923c;
- --color-accent-500: #f97316;
- /* 语义色 */
- --color-success: #10b981;
- --color-success-bg: #ecfdf5;
- --color-warning: #f59e0b;
- --color-warning-bg: #fffbeb;
- --color-error: #ef4444;
- --color-error-bg: #fef2f2;
- --color-info: #3b82f6;
- --color-info-bg: #eff6ff;
- /* 中性色 */
- --color-text-primary: #111827;
- --color-text-secondary: #4b5563;
- --color-text-tertiary: #9ca3af;
- --color-text-placeholder: #d1d5db;
- --color-text-inverse: #ffffff;
- /* 背景色 */
- --color-bg-page: #f3f4f6;
- --color-bg-card: #ffffff;
- --color-bg-surface: #f9fafb;
- --color-bg-hover: #f3f4f6;
- --color-bg-divider: #e5e7eb;
- /* 阴影系统 */
- --shadow-xs: 0 1rpx 2rpx rgba(0, 0, 0, 0.04);
- --shadow-sm: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
- --shadow-md: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
- --shadow-lg: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
- --shadow-xl: 0 16rpx 48rpx rgba(0, 0, 0, 0.16);
- --shadow-primary: 0 4rpx 20rpx rgba(79, 70, 229, 0.25);
- /* 圆角系统 */
- --radius-xs: 6rpx;
- --radius-sm: 10rpx;
- --radius-md: 16rpx;
- --radius-lg: 24rpx;
- --radius-xl: 32rpx;
- --radius-full: 9999rpx;
- /* 间距系统 */
- --space-1: 4rpx;
- --space-2: 8rpx;
- --space-3: 12rpx;
- --space-4: 16rpx;
- --space-5: 20rpx;
- --space-6: 24rpx;
- --space-8: 32rpx;
- --space-10: 40rpx;
- --space-12: 48rpx;
- /* 字体 */
- --font-sans: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
- --font-mono: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace;
- /* 字体大小 */
- --text-xs: 20rpx;
- --text-sm: 24rpx;
- --text-base: 28rpx;
- --text-lg: 32rpx;
- --text-xl: 36rpx;
- --text-2xl: 44rpx;
- --text-3xl: 56rpx;
- /* 过渡 */
- --transition-fast: 0.15s cubic-bezier(0.4, 0, 0.2, 1);
- --transition-base: 0.25s cubic-bezier(0.4, 0, 0.2, 1);
- --transition-slow: 0.35s cubic-bezier(0.4, 0, 0.2, 1);
- /* 兼容旧变量名 */
- --primary-color: var(--color-primary);
- --primary-light: var(--color-primary-500);
- --primary-lighter: var(--color-primary-400);
- --accent-color: var(--color-accent);
- --success-color: var(--color-success);
- --error-color: var(--color-error);
- --text-primary: var(--color-text-primary);
- --text-secondary: var(--color-text-secondary);
- --bg-primary: var(--color-bg-page);
- --bg-card: var(--color-bg-card);
- }
- /* --- 页面基础 --- */
- page {
- background-color: var(--color-bg-page);
- font-family: var(--font-sans);
- font-size: 14px;
- color: var(--color-text-primary);
- min-height: 100vh;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- transition: background-color var(--transition-base), color var(--transition-base);
- }
- /* --- 页面过渡动画 --- */
- page {
- animation: pageIn 0.28s cubic-bezier(0.22, 0.61, 0.36, 1);
- }
- @keyframes pageIn {
- from {
- opacity: 0;
- transform: translateX(16px);
- }
- to {
- opacity: 1;
- transform: translateX(0);
- }
- }
- /* --- 通用入场动画 --- */
- @keyframes fadeInUp {
- from { opacity: 0; transform: translateY(24px); }
- to { opacity: 1; transform: translateY(0); }
- }
- @keyframes fadeIn {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- @keyframes scaleIn {
- from { opacity: 0; transform: scale(0.92); }
- to { opacity: 1; transform: scale(1); }
- }
- @keyframes shimmer {
- 0% { background-position: -200% 0; }
- 100% { background-position: 200% 0; }
- }
- @keyframes pulse-ring {
- 0% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.4); }
- 70% { box-shadow: 0 0 0 12rpx rgba(79, 70, 229, 0); }
- 100% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0); }
- }
- .list-item-enter {
- animation: fadeInUp 0.4s cubic-bezier(0.22, 0.61, 0.36, 1) forwards;
- }
- /* --- 交互反馈 --- */
- button:active,
- .btn:active {
- transform: scale(0.97);
- transition: transform 0.12s cubic-bezier(0.4, 0, 0.2, 1);
- }
- .touch-feedback:active {
- transform: scale(0.97);
- transition: transform 0.12s cubic-bezier(0.4, 0, 0.2, 1);
- opacity: 0.85;
- }
- /* 通用点击态 */
- .tappable {
- transition: transform var(--transition-fast), opacity var(--transition-fast);
- }
- .tappable:active {
- transform: scale(0.97);
- opacity: 0.8;
- }
- /* --- 渐变工具类 --- */
- .gradient-primary {
- background: linear-gradient(135deg, var(--color-primary-600), var(--color-primary-700));
- }
- .gradient-accent {
- background: linear-gradient(135deg, var(--color-accent), var(--color-accent-400));
- }
- .gradient-success {
- background: linear-gradient(135deg, #059669, var(--color-success));
- }
- /* --- 毛玻璃效果 --- */
- .glass {
- background: rgba(255, 255, 255, 0.85);
- backdrop-filter: blur(20px);
- -webkit-backdrop-filter: blur(20px);
- }
- .glass-dark {
- background: rgba(17, 24, 39, 0.85);
- backdrop-filter: blur(20px);
- -webkit-backdrop-filter: blur(20px);
- }
- /* --- 夜间模式 --- */
- page.dark-mode {
- --color-bg-page: #0f172a;
- --color-bg-card: #1e293b;
- --color-bg-surface: #1a2332;
- --color-bg-hover: #334155;
- --color-bg-divider: #334155;
- --color-text-primary: #f1f5f9;
- --color-text-secondary: #94a3b8;
- --color-text-tertiary: #64748b;
- background-color: #0f172a;
- color: #f1f5f9;
- }
- /* --- 工具类 --- */
- .text-ellipsis {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .text-clamp-2 {
- display: -webkit-box;
- -webkit-line-clamp: 2;
- -webkit-box-orient: vertical;
- overflow: hidden;
- }
- text {
- user-select: none;
- }
- .safe-area-bottom {
- padding-bottom: constant(safe-area-inset-bottom);
- padding-bottom: env(safe-area-inset-bottom);
- }
- /* ============================================================
- 隐藏 uni-app 内置 tab bar(由 CustomTabBar 替代)
- ============================================================ */
- uni-app .uni-tabbar,
- uni-app uni-tabbar,
- .uni-app--showtabbar .uni-tabbar {
- display: none !important;
- }
- /* ============================================================
- 启动阻塞 UI(导航未就绪时显示)
- 使用 div 选择器确保生效
- ============================================================ */
- .boot-splash.is-hidden {
- display: none !important;
- }
- .boot-splash {
- position: fixed !important;
- top: 0 !important;
- left: 0 !important;
- right: 0 !important;
- bottom: 0 !important;
- display: flex !important;
- flex-direction: column !important;
- align-items: center !important;
- justify-content: center !important;
- background: linear-gradient(160deg, #4f46e5 0%, #7c3aed 60%, #a855f7 100%) !important;
- color: #ffffff !important;
- padding: 60rpx 80rpx !important;
- z-index: 99999 !important;
- box-sizing: border-box !important;
- }
- .boot-logo {
- width: 160rpx;
- height: 160rpx;
- border-radius: 40rpx;
- background: rgba(255, 255, 255, 0.18);
- display: flex;
- align-items: center;
- justify-content: center;
- margin-bottom: 28rpx;
- box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.18);
- }
- .boot-logo-icon {
- font-size: 96rpx;
- line-height: 1;
- }
- .boot-app-name {
- font-size: 44rpx;
- font-weight: 700;
- letter-spacing: 2rpx;
- margin-bottom: 80rpx;
- text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
- }
- .boot-state {
- display: flex;
- flex-direction: column;
- align-items: center;
- width: 100%;
- }
- .boot-loading {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 24rpx;
- }
- .boot-spinner {
- width: 56rpx;
- height: 56rpx;
- border-radius: 50%;
- border: 4rpx solid rgba(255, 255, 255, 0.25);
- border-top-color: #ffffff;
- animation: bootSpin 0.9s linear infinite;
- }
- @keyframes bootSpin {
- to { transform: rotate(360deg); }
- }
- .boot-loading-text {
- font-size: 28rpx;
- font-weight: 600;
- color: #ffffff;
- }
- .boot-loading-hint {
- font-size: 22rpx;
- color: rgba(255, 255, 255, 0.7);
- }
- .boot-error {
- width: 100%;
- max-width: 560rpx;
- background: rgba(255, 255, 255, 0.95);
- border-radius: 28rpx;
- padding: 48rpx 40rpx;
- display: flex;
- flex-direction: column;
- align-items: center;
- color: #111827;
- box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.18);
- }
- .boot-error-icon {
- font-size: 80rpx;
- line-height: 1;
- margin-bottom: 20rpx;
- }
- .boot-error-title {
- font-size: 32rpx;
- font-weight: 700;
- color: #111827;
- margin-bottom: 16rpx;
- }
- .boot-error-message {
- font-size: 24rpx;
- color: #6b7280;
- text-align: center;
- line-height: 1.5;
- margin-bottom: 32rpx;
- word-break: break-all;
- }
- .boot-retry-btn {
- width: 100%;
- height: 88rpx;
- line-height: 88rpx;
- background: linear-gradient(135deg, #4f46e5, #7c3aed);
- color: #ffffff;
- font-size: 28rpx;
- font-weight: 600;
- border-radius: 44rpx;
- border: none;
- margin-bottom: 20rpx;
- box-shadow: 0 4rpx 16rpx rgba(79, 70, 229, 0.4);
- }
- .boot-retry-btn::after {
- border: none;
- }
- .boot-error-hint {
- font-size: 20rpx;
- color: #9ca3af;
- text-align: center;
- }
- </style>
|