| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235 |
- const Parse = getApp().Parse;
- const company = getApp().globalData.company;
- const login = require("../../../utils/login");
- const clearLogin = require("../../../utils/clearLogin");
- Component({
- /**
- * 组件的属性列表
- */
- properties: {
- },
- data: {
- // 轮播图相关数据
- currentSwiperIndex: 0,
- // 是否显示 AI 相关内容(根据 Company.isPublishing 字段)
- showAI: false,
- },
- lifetimes: {
- created() {},
- attached: async function () {
- // 页面加载时检查是否首次访问
- this.checkFirstVisit();
-
- // 检查并清理异常的登录状态
- await this.checkAndCleanInvalidLoginState();
-
- // 在控制台显示当前登录用户信息
- this.showCurrentUser();
-
- // 检查 isPublishing 状态
- await this.checkPublishingStatus();
- },
- },
- pageLifetimes: {
- show: async function() {
- console.log('===========================================');
- console.log('======= 页面显示 (pageLifetimes.show) =======');
-
- // 重新检查 isPublishing 状态
- await this.checkPublishingStatus();
-
- // 延迟检查登录状态,等待 Parse 更新
- setTimeout(() => {
- const currentUser = Parse.User.current();
- console.log('当前用户:', currentUser ? currentUser.id : '无');
- console.log('手机号:', currentUser?.get('mobile') || '无');
-
- if (currentUser && currentUser.get('mobile')) {
- const userLogin = wx.getStorageSync('userLogin');
- console.log('userLogin 存储:', userLogin || '无');
-
- if (!userLogin || userLogin !== currentUser.id) {
- wx.setStorageSync("userLogin", currentUser.id);
- console.log('✅ 页面显示时更新 userLogin:', currentUser.id);
-
- // 清除游客模式标记
- wx.removeStorageSync('isGuestMode');
- console.log('✅ 已清除游客模式标记');
- }
- }
-
- console.log('===========================================');
-
- // 更新显示的用户信息
- this.showCurrentUser();
- }, 500); // 延迟 500ms,等待 Parse 更新
- }
- },
- /**
- * 组件的方法列表
- */
- methods: {
- /**
- * 检查并清理异常的登录状态
- * 在页面加载时自动执行,避免点击登录时白屏
- */
- async checkAndCleanInvalidLoginState() {
- try {
- const currentUser = Parse.User.current();
- const userLogin = wx.getStorageSync('userLogin');
-
- // 如果有 Parse 用户但没有 userLogin,说明状态不一致
- if (currentUser && !userLogin) {
- console.log('⚠️ 检测到异常登录状态:有 Parse 用户但没有 userLogin');
- console.log(' 用户 ID:', currentUser.id);
- console.log(' 手机号:', currentUser.get('mobile') || '无');
-
- // 如果用户有手机号,补充设置 userLogin
- if (currentUser.get('mobile')) {
- wx.setStorageSync('userLogin', currentUser.id);
- console.log('✅ 已补充设置 userLogin');
- } else {
- // 如果用户没有手机号,清除这个无效的用户
- // console.log('🧹 用户没有手机号,清除无效状态');
- // await clearLogin.clearAllLoginState();
- }
- }
-
- // 如果有 userLogin 但没有 Parse 用户,说明状态不一致
- if (!currentUser && userLogin) {
- console.log('⚠️ 检测到异常登录状态:有 userLogin 但没有 Parse 用户');
- console.log(' userLogin:', userLogin);
- console.log('🧹 清除无效的 userLogin');
- wx.removeStorageSync('userLogin');
- }
- } catch (error) {
- console.error('❌ 检查登录状态失败:', error);
- }
- },
- /**
- * 在控制台显示当前登录用户信息
- */
- showCurrentUser() {
- const currentUser = Parse.User.current();
-
- console.log('===========================================');
- console.log('======= 当前登录用户信息 =======');
- console.log('===========================================');
-
- if (currentUser) {
- console.log('✅ 用户已登录');
- console.log('📱 用户ID:', currentUser.id);
- console.log('📞 手机号:', currentUser.get('mobile') || '未设置');
- console.log('👤 用户名:', currentUser.get('username') || '未设置');
- console.log('🔑 Session Token:', currentUser.getSessionToken());
- console.log('📧 邮箱:', currentUser.get('email') || '未设置');
- console.log('📦 完整用户对象:', currentUser);
- console.log('📋 所有属性:', currentUser.attributes);
- } else {
- console.log('❌ 当前没有登录用户');
- }
-
- console.log('===========================================');
- },
- /**
- * 检查是否首次访问
- */
- checkFirstVisit() {
- try {
- const hasVisited = wx.getStorageSync('hasVisitedWelcome');
- if (!hasVisited) {
- console.log('首次访问,显示引导页');
- } else {
- console.log('已访问过,可选择是否直接跳转');
- // 如果需要自动跳转到主页,可以在这里调用 this.navigateToHome()
- }
- } catch (e) {
- console.error('检查访问状态失败:', e);
- }
- },
- /**
- * 检查登录状态(强制登录模式)
- * 当 isPublishing != true 时,必须登录才能访问
- * @returns {Promise<boolean>} 是否已登录或允许访问
- */
- async checkLoginRequired() {
- // 获取 isPublishing 状态
- const isPublishing = wx.getStorageSync('isPublishing');
-
- console.log('🔐 检查登录要求...');
- console.log(' isPublishing:', isPublishing);
-
- // 如果 isPublishing == true,不需要强制登录,允许游客访问
- if (isPublishing === true) {
- console.log('✅ isPublishing == true,允许游客访问');
- return true;
- }
-
- console.log('⚠️ isPublishing != true,需要强制登录');
-
- // 检查用户是否已登录
- const currentUser = Parse.User.current();
- const userLogin = wx.getStorageSync('userLogin');
- const isLoggedIn = currentUser && currentUser.get('mobile') && userLogin;
-
- console.log(' 当前用户:', currentUser ? currentUser.id : '无');
- console.log(' 手机号:', currentUser?.get('mobile') || '无');
- console.log(' userLogin:', userLogin || '无');
- console.log(' 登录状态:', isLoggedIn ? '已登录' : '未登录');
-
- if (!isLoggedIn) {
- console.log('❌ 用户未登录,显示登录提示');
-
- wx.showModal({
- title: '需要登录',
- content: '请先登录后再使用此功能',
- showCancel: false,
- confirmText: '立即登录',
- success: () => {
- // 跳转到登录页面
- console.log('🔄 跳转到登录页面');
- login.loginNow();
- }
- });
-
- return false;
- }
-
- console.log('✅ 用户已登录,允许访问');
- return true;
- },
- /**
- * 检查 Company 的 isPublishing 状态
- * 用于控制是否显示 AI 相关内容
- */
- async checkPublishingStatus() {
- try {
- console.log('🔍 开始检查 isPublishing 状态...');
-
- // 先尝试从缓存读取
- let isPublishing = wx.getStorageSync('isPublishing');
-
- if (isPublishing === '' || isPublishing === null || isPublishing === undefined) {
- console.log('📦 缓存中没有 isPublishing,尝试查询数据库...');
-
- try {
- // 缓存中没有,查询 Company 表(使用 master key,不需要登录)
- const companyQuery = new Parse.Query('Company');
- companyQuery.equalTo('objectId', getApp().globalData.company);
- companyQuery.select('isPublishing');
-
- // 使用 find 而不是 first,避免 session token 问题
- const results = await companyQuery.find();
-
- if (results && results.length > 0) {
- const companyObj = results[0];
- isPublishing = companyObj.get('isPublishing') === true;
- console.log('📋 从数据库查询 isPublishing:', isPublishing);
-
- // 保存到缓存
- wx.setStorageSync('isPublishing', isPublishing);
- getApp().globalData.isPublishing = isPublishing;
- } else {
- console.warn('⚠️ 未找到 Company 记录,默认为 false');
- isPublishing = false;
- // 也保存到缓存,避免重复查询
- wx.setStorageSync('isPublishing', false);
- getApp().globalData.isPublishing = false;
- }
- } catch (queryError) {
- console.error('❌ 查询 Company 失败:', queryError);
- // 查询失败时,默认为 false(需要登录)
- isPublishing = false;
- wx.setStorageSync('isPublishing', false);
- getApp().globalData.isPublishing = false;
- }
- } else {
- console.log('📦 从缓存读取 isPublishing:', isPublishing);
- }
-
- // 更新组件状态
- this.setData({
- showAI: isPublishing === true
- });
-
- console.log('✅ isPublishing 状态检查完成');
- console.log(' - isPublishing:', isPublishing);
- console.log(' - showAI:', isPublishing === true);
- console.log('===========================================');
- } catch (error) {
- console.error('❌ 检查 isPublishing 状态失败:', error);
- // 出错时默认不显示 AI(需要登录)
- this.setData({
- showAI: false
- });
- wx.setStorageSync('isPublishing', false);
- }
- },
- /**
- * 点击"立即开始探索"按钮
- */
- async onStart() {
- console.log('===========================================');
- console.log('🚀 调用了 onStart 方法(立即开始探索)');
- console.log('===========================================');
-
- // 检查 isPublishing 状态,如果不是 true,需要强制登录
- const isPublishing = this.data.showAI; // showAI 就是 isPublishing 的状态
-
- console.log('📋 isPublishing 状态:', isPublishing);
-
- // 如果 isPublishing != true,必须登录才能访问
- if (!isPublishing) {
- console.log('⚠️ isPublishing != true,需要强制登录');
-
- // 检查用户是否已登录
- const currentUser = Parse.User.current();
- const userLogin = wx.getStorageSync('userLogin');
- const isLoggedIn = currentUser && currentUser.get('mobile') && userLogin;
-
- console.log(' 当前用户:', currentUser ? currentUser.id : '无');
- console.log(' 手机号:', currentUser?.get('mobile') || '无');
- console.log(' userLogin:', userLogin || '无');
- console.log(' 登录状态:', isLoggedIn ? '已登录' : '未登录');
-
- if (!isLoggedIn) {
- console.log('❌ 用户未登录,直接跳转到登录页面');
- login.loginNow();
- return;
- }
-
- console.log('✅ 用户已登录,允许访问');
- } else {
- console.log('✅ isPublishing == true,允许游客访问');
- }
-
- // 标记已访问
- wx.setStorageSync('hasVisitedWelcome', true);
-
- // 跳转到 H5 主页
- this.navigateToHome();
- },
- /**
- * 点击"跳过引导"按钮
- */
- async onSkip() {
- // 检查是否需要强制登录
- const canAccess = await this.checkLoginRequired();
- if (!canAccess) {
- return;
- }
-
- // 标记已访问
- wx.setStorageSync('hasVisitedWelcome', true);
-
- // 跳转到 H5 主页
- this.navigateToHome();
- },
- /**
- * 点击"查看新手指南"
- */
- onGuide() {
- wx.showToast({
- title: '新手指南开发中',
- icon: 'none',
- duration: 2000
- });
-
- // TODO: 后续可以跳转到新手指南页面
- // wx.navigateTo({
- // url: '/pages/guide/index'
- // });
- },
- /**
- * 验证 token 是否有效
- */
- async validateToken(token) {
- try {
- console.log('🔍 开始验证 token 有效性...');
-
- // 使用 Parse.User.become() 验证 token
- const user = await Parse.User.become(token);
-
- if (user) {
- console.log('✅ Token 有效!用户:', user.id);
- return true;
- }
-
- console.log('⚠️ Token 验证返回空用户');
- return false;
- } catch (error) {
- console.error('❌ Token 验证失败:', error.message);
- return false;
- }
- },
- /**
- * 刷新用户 session token
- */
- async refreshToken() {
- try {
- console.log('🔄 开始刷新 token...');
-
- const currentUser = Parse.User.current();
- if (!currentUser) {
- console.error('❌ 当前没有登录用户,无法刷新 token');
- return null;
- }
-
- // 保存用户信息以触发 session token 刷新
- await currentUser.fetch();
- const newToken = currentUser.getSessionToken();
-
- console.log('✅ Token 刷新成功');
- console.log('🔑 新 Token (前20字符):', newToken.substring(0, 20));
-
- return newToken;
- } catch (error) {
- console.error('❌ Token 刷新失败:', error.message);
- return null;
- }
- },
- /**
- * 获取店铺 ID
- * 优先级:
- * 1. 扫码进入的 storeId(最高优先级)
- * 2. 用户历史访问的 storeId
- * 3. 超级门店 ID(默认值)
- *
- * 注意:如果需要切换店铺(非扫码),请先调用:
- * wx.removeStorageSync('storeId_from_scan')
- */
- async getStoreId() {
- try {
- console.log('🏪 开始获取店铺 ID...');
- const defaultStoreId = 'pkPdAnLAUZ'; // 超级门店ID
-
- // 检查是否是扫码进入
- const isFromScan = wx.getStorageSync('storeId_from_scan');
- const storedStoreId = wx.getStorageSync('storeId');
- const globalStoreId = getApp().globalData.storeId;
-
- let configuredStoreId;
-
- if (isFromScan && storedStoreId) {
- // 优先级1:扫码进入的店铺(最高优先级)
- configuredStoreId = storedStoreId;
- console.log('🎯 使用扫码进入的店铺 ID:', configuredStoreId);
- } else if (storedStoreId) {
- // 优先级2:用户历史访问的店铺
- configuredStoreId = storedStoreId;
- console.log('📍 使用历史访问的店铺 ID:', configuredStoreId);
- } else if (globalStoreId) {
- // 优先级3:全局设置的店铺
- configuredStoreId = globalStoreId;
- console.log('🌐 使用全局店铺 ID:', configuredStoreId);
- } else {
- // 优先级4:默认超级门店
- configuredStoreId = defaultStoreId;
- console.log('⭐ 使用默认超级门店 ID:', configuredStoreId);
- }
-
- console.log('✅ 最终使用店铺 ID:', configuredStoreId);
- return configuredStoreId;
- } catch (error) {
- console.error('❌ 获取店铺 ID 失败:', error);
- return 'pkPdAnLAUZ';
- }
- },
- /**
- * 获取店铺信息(id 与 名称)
- * 优先级:
- * 1. 扫码进入的 storeId(最高优先级)
- * 2. 用户历史访问的 storeId
- * 3. 超级门店 ID(默认值)
- */
- async getStoreInfo() {
- try {
- const defaultStoreId = 'pkPdAnLAUZ'; // 超级门店ID
-
- // 检查是否是扫码进入
- const isFromScan = wx.getStorageSync('storeId_from_scan');
- const storedStoreId = wx.getStorageSync('storeId');
- const globalStoreId = getApp().globalData.storeId;
-
- let effectiveStoreId;
-
- if (isFromScan && storedStoreId) {
- // 优先级1:扫码进入的店铺(最高优先级)
- effectiveStoreId = storedStoreId;
- console.log('🎯 使用扫码进入的店铺 ID:', effectiveStoreId);
- } else if (storedStoreId) {
- // 优先级2:用户历史访问的店铺
- effectiveStoreId = storedStoreId;
- console.log('📍 使用历史访问的店铺 ID:', effectiveStoreId);
- } else if (globalStoreId) {
- // 优先级3:全局设置的店铺
- effectiveStoreId = globalStoreId;
- console.log('🌐 使用全局店铺 ID:', effectiveStoreId);
- } else {
- // 优先级4:默认超级门店
- effectiveStoreId = defaultStoreId;
- console.log('⭐ 使用默认超级门店 ID:', effectiveStoreId);
- }
- const query = new Parse.Query('ShopStore');
- query.equalTo('objectId', effectiveStoreId);
- const store = await query.first();
- if (store) {
- const name = store.get('storeName') || '';
- console.log('✅ 获取店铺信息:', { id: effectiveStoreId, name });
- return { id: effectiveStoreId, name };
- } else {
- console.log('⚠️ 未找到店铺,仅返回 ID');
- return { id: effectiveStoreId, name: '' };
- }
- } catch (e) {
- console.error('获取店铺信息失败:', e);
- const fallbackId = wx.getStorageSync('storeId') || 'pkPdAnLAUZ';
- return { id: fallbackId, name: '' };
- }
- },
- /**
- * 跳转到 H5 主页
- */
- async navigateToHome() {
- console.log('===========================================');
- console.log('======= navigateToHome 被调用 =======');
- console.log('===========================================');
-
- let currentUser = Parse.User.current();
- let userInfo = wx.getStorageSync("userLogin");
-
- console.log('当前用户:', currentUser ? currentUser.id : '无');
- console.log('用户手机号:', currentUser?.get('mobile') || '无');
- console.log('userInfo:', userInfo || '无');
-
- // 如果有 Parse 用户但没有 userInfo,可能是刚登录,等待同步
- if (currentUser && currentUser.get('mobile') && !userInfo) {
- console.log('⏳ 检测到刚登录,等待状态同步...');
-
- // 等待 500ms
- await new Promise(resolve => setTimeout(resolve, 500));
-
- // 重新获取
- currentUser = Parse.User.current();
- userInfo = wx.getStorageSync("userLogin");
-
- // 如果还是没有,手动设置
- if (currentUser && currentUser.get('mobile') && !userInfo) {
- wx.setStorageSync("userLogin", currentUser.id);
- userInfo = currentUser.id;
- console.log('✅ 手动设置 userLogin:', userInfo);
- }
- }
-
- // 重新检查登录状态
- const isLoggedIn = currentUser && currentUser.get('mobile') && userInfo;
-
- console.log('最终登录状态:', isLoggedIn ? '已登录' : '未登录');
-
- // 检查 isPublishing 状态
- const isPublishing = wx.getStorageSync('isPublishing');
-
- // 如果用户未登录
- if (!isLoggedIn) {
- // 只有当 isPublishing == true 时才允许游客模式
- if (isPublishing === true) {
- console.log('⚠️ 用户未登录,但 isPublishing == true,进入游客模式');
- this.navigateToHomeAsGuest();
- return;
- } else {
- console.log('❌ 用户未登录且 isPublishing != true,直接跳转登录页面');
- login.loginNow();
- return;
- }
- }
-
- let token = currentUser.getSessionToken();
-
- if (!token) {
- console.error('❌ 无法获取 Session Token!');
- wx.showToast({
- title: '获取登录信息失败',
- icon: 'none'
- });
- return;
- }
-
- // 验证 token 是否有效
- const isValid = await this.validateToken(token);
-
- if (!isValid) {
- wx.showLoading({
- title: '正在刷新登录...'
- });
-
- // 尝试刷新 token
- const newToken = await this.refreshToken();
-
- wx.hideLoading();
-
- if (newToken) {
- token = newToken;
- } else {
- console.error('❌ Token 刷新失败,需要重新登录');
- wx.showModal({
- title: '提示',
- content: '登录已过期,请重新登录',
- showCancel: false,
- success: () => {
- wx.navigateTo({
- url: 'plugin://fm-plugin/fm-auth'
- });
- }
- });
- return;
- }
- } else {
- // token 验证通过
- }
-
- // 获取店铺信息
- const store = await this.getStoreInfo();
- const storeId = store && store.id ? store.id : null;
- const storeName = store && store.name ? store.name : '';
-
- // 构建 H5 URL(重要:storeId 和 token 作为查询参数)
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?`;
-
- // 如果有 storeId,添加到 URL 中
- if (storeId) {
- h5Url += `storeId=${storeId}&`;
- }
-
- h5Url += `token=${token}`;
-
- console.log('🌐 H5 URL:', h5Url);
- console.log(' - URL 长度:', h5Url.length);
- if (storeId) {
- console.log(' - 店铺 ID:', storeId);
- }
-
- // 编码后的 URL
- const encodedUrl = encodeURIComponent(h5Url);
- console.log('📦 编码后的 URL:', encodedUrl.substring(0, 100) + '...');
-
- // 最终的小程序页面路径
- // 传递店铺信息给 web-view 页面,优先用于设置标题
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
- if (storeId) {
- webViewPath += `&storeId=${storeId}`;
- }
- if (storeName) {
- webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
- }
- console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
- console.log('===========================================');
-
- wx.navigateTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 跳转成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- wx.showToast({
- title: '跳转失败,请重试',
- icon: 'none'
- });
- }
- });
- },
-
- /**
- * 游客模式跳转到主页
- */
- async navigateToHomeAsGuest() {
- try {
- console.log('===========================================');
- console.log('======= 游客模式访问 =======');
- console.log('===========================================');
-
- // 标记为游客模式
- wx.setStorageSync('isGuestMode', true);
-
- // ✅ 游客默认使用超级门店ID,确保有数据
- const superStoreId = 'pkPdAnLAUZ'; // 超级门店ID
-
- // 设置超级门店ID到存储
- wx.setStorageSync('storeId', superStoreId);
- getApp().globalData.storeId = superStoreId;
-
- console.log('✅ 游客使用超级门店ID:', superStoreId);
-
- // 获取店铺信息
- const store = await this.getStoreInfo();
- const storeId = store && store.id ? store.id : superStoreId;
- const storeName = store && store.name ? store.name : '超级门店';
-
- console.log('✅ 店铺信息:', { id: storeId, name: storeName });
-
- // 构建 H5 URL(游客模式,不传 token)
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?`;
-
- h5Url += `storeId=${storeId}&`;
-
- // 添加游客模式标识
- h5Url += `guestMode=true`;
-
- console.log('🌐 游客模式 H5 URL:', h5Url);
- console.log('');
- console.log('⚠️⚠️⚠️ 重要提示 ⚠️⚠️⚠️');
- console.log('如果H5页面显示的不是超级门店,说明H5端没有正确使用URL中的storeId参数!');
- console.log('H5端需要确保:');
- console.log('1. 从URL中读取 storeId 参数');
- console.log('2. 优先使用URL传递的 storeId,不要被其他逻辑覆盖');
- console.log('3. 不要使用localStorage缓存的旧门店ID');
- console.log('');
- console.log('请复制以下URL在浏览器中测试:');
- console.log(h5Url);
- console.log('===========================================');
-
- // 编码后的 URL
- const encodedUrl = encodeURIComponent(h5Url);
-
- // 跳转
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
- webViewPath += `&storeId=${storeId}`;
- if (storeName) {
- webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
- }
-
- console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
- console.log('===========================================');
-
- wx.navigateTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 游客模式跳转成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- wx.showToast({
- title: '跳转失败,请重试',
- icon: 'none'
- });
- }
- });
- } catch (error) {
- console.error('❌ 游客模式跳转失败:', error);
- wx.showToast({
- title: '加载失败,请重试',
- icon: 'none'
- });
- }
- },
- /**
- * 轮播图变化事件
- */
- onSwiperChange(e) {
- this.setData({
- currentSwiperIndex: e.detail.current
- });
- },
- /**
- * 跳转到案例展示页面
- */
- async navigateToCases() {
- console.log('===========================================');
- console.log('🏠 调用了 navigateToCases 方法(案例展示)');
- console.log('===========================================');
-
- // 检查 isPublishing 状态,如果不是 true,需要强制登录
- const isPublishing = this.data.showAI;
-
- // 检查是否需要强制登录
- const canAccess = await this.checkLoginRequired();
- if (!canAccess) {
- return;
- }
-
- // 案例展示允许游客访问(当 isPublishing == true 时)
- const currentUser = Parse.User.current();
-
- if (!currentUser) {
- console.log('游客访问案例展示');
- wx.setStorageSync('isGuestMode', true);
- await this.navigateToH5PageAsGuest('owner/nav/cases');
- } else {
- await this.navigateToH5Page('owner/nav/cases');
- }
- },
-
- /**
- * 跳转到产品中心页面
- * @param {string} productId - 可选的产品ID,用于直接跳转到特定产品详情
- */
- async navigateToProducts(productId = null) {
- console.log('===========================================');
- console.log('📦 调用了 navigateToProducts 方法(产品中心)');
- console.log('===========================================');
-
- // 检查是否需要强制登录
- const canAccess = await this.checkLoginRequired();
- if (!canAccess) {
- return;
- }
-
- // 产品中心允许游客访问(当 isPublishing == true 时)
- const currentUser = Parse.User.current();
- const params = productId ? { productId } : {};
-
- if (!currentUser) {
- console.log('游客访问产品中心');
- wx.setStorageSync('isGuestMode', true);
- await this.navigateToH5PageAsGuest('owner/nav/products', params);
- } else {
- await this.navigateToH5Page('owner/nav/products', params);
- }
- },
- /**
- * 跳转到方案定制/AI推荐页面
- */
- async navigateToConsultation() {
- console.log('===========================================');
- console.log('======= 点击咨询/方案定制 =======');
- console.log('===========================================');
-
- // 检查 isPublishing 状态,如果不是 true,需要强制登录
- const isPublishing = this.data.showAI;
-
- // 检查是否需要强制登录
- const canAccess = await this.checkLoginRequired();
- if (!canAccess) {
- return;
- }
-
- // 方案定制需要登录
- let currentUser = Parse.User.current();
- const isGuestMode = wx.getStorageSync('isGuestMode');
- let userLogin = wx.getStorageSync('userLogin');
-
- console.log('当前用户:', currentUser ? currentUser.id : '无');
- console.log('用户手机号:', currentUser?.get('mobile') || '无');
- console.log('游客模式:', isGuestMode);
- console.log('userLogin 存储:', userLogin || '无');
-
- // 如果有 Parse 用户但没有 userLogin,可能是刚授权完成,等待一下
- if (currentUser && currentUser.get('mobile') && !userLogin) {
- console.log('⏳ 检测到刚授权完成,等待状态同步...');
-
- // 等待 500ms 后重新检查
- await new Promise(resolve => setTimeout(resolve, 500));
-
- // 重新获取状态
- currentUser = Parse.User.current();
- userLogin = wx.getStorageSync('userLogin');
-
- // 如果还是没有 userLogin,手动设置
- if (currentUser && currentUser.get('mobile') && !userLogin) {
- wx.setStorageSync("userLogin", currentUser.id);
- userLogin = currentUser.id;
- console.log('✅ 手动设置 userLogin:', userLogin);
- }
- }
-
- // 检查用户是否真正登录(有手机号且有 userLogin 存储)
- const isReallyLoggedIn = currentUser && currentUser.get('mobile') && userLogin;
-
- console.log('最终登录状态:', isReallyLoggedIn ? '已登录' : '未登录');
-
- // 如果用户已经真正登录,清除游客模式标记
- if (isReallyLoggedIn && isGuestMode) {
- console.log('✅ 用户已登录,清除游客模式标记');
- wx.removeStorageSync('isGuestMode');
- }
-
- // 只有在真正未登录时才提示
- if (!isReallyLoggedIn) {
- console.log('⚠️ 用户未完成登录,显示登录提示');
-
- wx.showModal({
- title: '需要登录',
- content: '方案定制和咨询功能需要登录后使用,是否立即登录?',
- confirmText: '立即登录',
- cancelText: '取消',
- success: async (res) => {
- if (res.confirm) {
- console.log('用户选择:立即登录');
-
- // 不要清除登录状态,因为可能用户刚登录成功只是状态没同步
- // 直接跳转到登录页面
- console.log('准备调用 login.loginNow()');
-
- // 直接调用登录方法
- const loginResult = login.loginNow();
- console.log('login.loginNow() 返回值:', loginResult);
-
- // 如果返回 false,说明已经跳转到登录页面
- if (!loginResult) {
- console.log('✅ 已跳转到登录页面');
- // 设置待处理的跳转,登录成功后自动跳转到咨询页面
- wx.setStorageSync('pendingNavigation', 'consultation');
- console.log('📌 已设置待处理跳转: consultation');
- }
- } else {
- console.log('用户选择:取消');
- }
- }
- });
- return;
- }
-
- console.log('✅ 用户已登录,跳转到咨询页面');
- console.log('===========================================');
- await this.navigateToH5Page('owner/nav/consultation');
- },
- /**
- * 通用 H5 页面跳转方法
- * @param {string} pagePath - H5 页面路径(例如: 'owner/nav/cases')
- * @param {object} extraParams - 额外的URL参数对象(例如: { productId: 'xxx' })
- */
- async navigateToH5Page(pagePath, extraParams = {}) {
- console.log('===========================================');
- console.log(`======= 小程序跳转 H5: ${pagePath} =======`);
- console.log('===========================================');
-
- const currentUser = Parse.User.current();
- let userInfo = wx.getStorageSync("userLogin");
-
- console.log('📱 当前登录状态检查:');
- console.log(' Parse.User.current():', currentUser ? currentUser.id : '无');
- console.log(' 用户手机号:', currentUser?.get('mobile') || '无');
- console.log(' userLogin 存储:', userInfo || '无');
- console.log(' Session Token (前20字符):', currentUser?.getSessionToken()?.substring(0, 20) || '无');
-
- // 检查是否是游客模式
- const isGuestMode = wx.getStorageSync('isGuestMode');
- console.log(' 游客模式:', isGuestMode);
-
- // 定义允许游客访问的页面
- const guestAllowedPages = [
- 'owner/nav/home', // 首页
- 'owner/nav/products', // 产品中心
- 'owner/nav/cases' // 案例展示
- ];
-
- // 检查当前页面是否允许游客访问
- const isGuestAllowed = guestAllowedPages.some(page => pagePath.includes(page));
-
- if ((!currentUser || userInfo == '') && !isGuestMode) {
- // 未登录且不是游客模式,提示用户
- wx.showModal({
- title: '温馨提示',
- content: '登录后可以体验更多功能,是否立即登录?',
- confirmText: '立即登录',
- cancelText: '先随便看看',
- success: (res) => {
- if (res.confirm) {
- // 用户选择登录
- login.loginNow();
- } else {
- // 用户选择游客模式
- if (isGuestAllowed) {
- // 如果是允许游客访问的页面,继续访问
- wx.setStorageSync('isGuestMode', true);
- this.navigateToH5PageAsGuest(pagePath, extraParams);
- } else {
- // 如果不允许游客访问,提示需要登录
- wx.showToast({
- title: '此功能需要登录',
- icon: 'none'
- });
- }
- }
- }
- });
- return;
- }
-
- // 如果是游客模式,检查是否允许访问
- if (isGuestMode || !currentUser) {
- if (!isGuestAllowed) {
- // 游客不允许访问此页面
- wx.showModal({
- title: '需要登录',
- content: '此功能需要登录后使用,是否立即登录?',
- confirmText: '立即登录',
- cancelText: '取消',
- success: (res) => {
- if (res.confirm) {
- login.loginNow();
- }
- }
- });
- return;
- }
-
- // 游客访问允许的页面
- this.navigateToH5PageAsGuest(pagePath, extraParams);
- return;
- }
-
- let token = currentUser.getSessionToken();
- console.log('🔑 准备传递的 Token:');
- console.log(' 完整 Token:', token);
- console.log(' Token 长度:', token ? token.length : 0);
- console.log(' Token 前20个字符:', token ? token.substring(0, 20) : 'null');
-
- if (!token) {
- console.error('❌ 无法获取 Session Token!');
- wx.showToast({
- title: '获取登录信息失败',
- icon: 'none'
- });
- return;
- }
-
- // 验证 token 是否有效
- console.log('🔍 验证 token 有效性...');
- const isValid = await this.validateToken(token);
-
- if (!isValid) {
- console.log('⚠️ Token 已失效,尝试刷新...');
- wx.showLoading({
- title: '正在刷新登录...'
- });
-
- // 尝试刷新 token
- const newToken = await this.refreshToken();
-
- wx.hideLoading();
-
- if (newToken) {
- token = newToken;
- console.log('✅ 使用新的 token:', token.substring(0, 20));
- } else {
- console.error('❌ Token 刷新失败,需要重新登录');
- wx.showModal({
- title: '提示',
- content: '登录已过期,请重新登录',
- showCancel: false,
- success: () => {
- wx.navigateTo({
- url: 'plugin://fm-plugin/fm-auth'
- });
- }
- });
- return;
- }
- } else {
- console.log('✅ Token 验证通过');
- }
-
- // 获取店铺信息
- const store = await this.getStoreInfo();
- const storeId = store && store.id ? store.id : null;
- const storeName = store && store.name ? store.name : '';
-
- // 构建 H5 URL(重要:storeId 和 token 作为查询参数)
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/${pagePath}?`;
-
- // 如果有 storeId,添加到 URL 中
- if (storeId) {
- h5Url += `storeId=${storeId}&`;
- }
-
- h5Url += `token=${token}`;
-
- console.log('🌐 构建的 H5 URL:');
- console.log(' 完整 URL:', h5Url);
- console.log(' URL 中的 token (前20字符):', token.substring(0, 20));
-
- // 添加额外的参数(如 productId)
- if (extraParams && Object.keys(extraParams).length > 0) {
- for (const [key, value] of Object.entries(extraParams)) {
- if (value) {
- h5Url += `&${key}=${encodeURIComponent(value)}`;
- console.log(` - 添加参数 ${key}:`, value);
- }
- }
- }
-
- // 编码后的 URL
- const encodedUrl = encodeURIComponent(h5Url);
-
- // 最终的小程序页面路径
- // 传递店铺信息给 web-view 页面,优先用于设置标题
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
- if (storeId) {
- webViewPath += `&storeId=${storeId}`;
- }
- if (storeName) {
- webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
- }
-
- console.log('📄 最终跳转路径:', webViewPath.substring(0, 150) + '...');
- console.log('===========================================');
-
- wx.navigateTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 跳转成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- wx.showToast({
- title: '跳转失败,请重试',
- icon: 'none'
- });
- }
- });
- },
-
- /**
- * 检查登录状态
- * @returns {boolean} 是否已登录
- */
- async checkLoginStatus() {
- let currentUser = Parse.User.current();
- let userLogin = wx.getStorageSync('userLogin');
-
- // 如果有 Parse 用户但没有 userLogin,等待同步
- if (currentUser && currentUser.get('mobile') && !userLogin) {
- console.log('⏳ 等待登录状态同步...');
- await new Promise(resolve => setTimeout(resolve, 500));
-
- currentUser = Parse.User.current();
- userLogin = wx.getStorageSync('userLogin');
-
- if (currentUser && currentUser.get('mobile') && !userLogin) {
- wx.setStorageSync("userLogin", currentUser.id);
- userLogin = currentUser.id;
- }
- }
-
- return currentUser && currentUser.get('mobile') && userLogin;
- },
-
- /**
- * 显示需要登录的提示
- */
- showLoginRequired() {
- wx.showModal({
- title: '需要登录',
- content: '此功能需要登录后使用,请先完成登录',
- confirmText: '立即登录',
- cancelText: '取消',
- success: (res) => {
- if (res.confirm) {
- console.log('用户选择:立即登录');
- login.loginNow();
- }
- }
- });
- },
-
- /**
- * 游客模式跳转 H5 页面
- * @param {string} pagePath - H5 页面路径
- * @param {object} extraParams - 额外参数
- */
- async navigateToH5PageAsGuest(pagePath, extraParams = {}) {
- try {
- console.log('===========================================');
- console.log(`======= 游客模式跳转 H5: ${pagePath} =======`);
- console.log('===========================================');
-
- // ✅ 游客默认使用超级门店ID,确保有数据
- const superStoreId = 'pkPdAnLAUZ'; // 超级门店ID
-
- // 确保使用超级门店ID
- wx.setStorageSync('storeId', superStoreId);
- getApp().globalData.storeId = superStoreId;
-
- console.log('✅ 游客使用超级门店ID:', superStoreId);
-
- // 获取店铺信息
- const store = await this.getStoreInfo();
- const storeId = store && store.id ? store.id : superStoreId;
- const storeName = store && store.name ? store.name : '超级门店';
-
- console.log('✅ 店铺信息:', { id: storeId, name: storeName });
-
- // 构建 H5 URL(游客模式,不传 token)
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/${pagePath}?`;
-
- h5Url += `storeId=${storeId}&`;
-
- // 添加游客模式标识
- h5Url += `guestMode=true`;
-
- // 添加额外的参数
- if (extraParams && Object.keys(extraParams).length > 0) {
- for (const [key, value] of Object.entries(extraParams)) {
- if (value) {
- h5Url += `&${key}=${encodeURIComponent(value)}`;
- console.log(` - 添加参数 ${key}:`, value);
- }
- }
- }
-
- console.log('🌐 游客模式 H5 URL:', h5Url);
- console.log('');
- console.log('⚠️ 如果H5显示的不是超级门店,请检查H5端是否正确读取了URL中的storeId参数');
- console.log('');
-
- // 编码后的 URL
- const encodedUrl = encodeURIComponent(h5Url);
-
- // 最终的小程序页面路径
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
- webViewPath += `&storeId=${storeId}`;
- if (storeName) {
- webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
- }
-
- console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
- console.log('===========================================');
-
- wx.navigateTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 游客模式跳转成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- wx.showToast({
- title: '跳转失败,请重试',
- icon: 'none'
- });
- }
- });
- } catch (error) {
- console.error('❌ 游客模式跳转失败:', error);
- wx.showToast({
- title: '加载失败,请重试',
- icon: 'none'
- });
- }
- }
- }
- })
|