index.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. const Parse = getApp().Parse;
  2. const company = getApp().globalData.company;
  3. const login = require("../../../utils/login");
  4. const clearLogin = require("../../../utils/clearLogin");
  5. Component({
  6. /**
  7. * 组件的属性列表
  8. */
  9. properties: {
  10. },
  11. data: {
  12. // 轮播图相关数据
  13. currentSwiperIndex: 0,
  14. // 是否显示 AI 相关内容(根据 Company.isPublishing 字段)
  15. showAI: false,
  16. },
  17. lifetimes: {
  18. created() {},
  19. attached: async function () {
  20. // 页面加载时检查是否首次访问
  21. this.checkFirstVisit();
  22. // 检查并清理异常的登录状态
  23. await this.checkAndCleanInvalidLoginState();
  24. // 在控制台显示当前登录用户信息
  25. this.showCurrentUser();
  26. // 检查 isPublishing 状态
  27. await this.checkPublishingStatus();
  28. },
  29. },
  30. pageLifetimes: {
  31. show: async function() {
  32. console.log('===========================================');
  33. console.log('======= 页面显示 (pageLifetimes.show) =======');
  34. // 重新检查 isPublishing 状态
  35. await this.checkPublishingStatus();
  36. // 延迟检查登录状态,等待 Parse 更新
  37. setTimeout(() => {
  38. const currentUser = Parse.User.current();
  39. console.log('当前用户:', currentUser ? currentUser.id : '无');
  40. console.log('手机号:', currentUser?.get('mobile') || '无');
  41. if (currentUser && currentUser.get('mobile')) {
  42. const userLogin = wx.getStorageSync('userLogin');
  43. console.log('userLogin 存储:', userLogin || '无');
  44. if (!userLogin || userLogin !== currentUser.id) {
  45. wx.setStorageSync("userLogin", currentUser.id);
  46. console.log('✅ 页面显示时更新 userLogin:', currentUser.id);
  47. // 清除游客模式标记
  48. wx.removeStorageSync('isGuestMode');
  49. console.log('✅ 已清除游客模式标记');
  50. }
  51. }
  52. console.log('===========================================');
  53. // 更新显示的用户信息
  54. this.showCurrentUser();
  55. }, 500); // 延迟 500ms,等待 Parse 更新
  56. }
  57. },
  58. /**
  59. * 组件的方法列表
  60. */
  61. methods: {
  62. /**
  63. * 检查并清理异常的登录状态
  64. * 在页面加载时自动执行,避免点击登录时白屏
  65. */
  66. async checkAndCleanInvalidLoginState() {
  67. try {
  68. const currentUser = Parse.User.current();
  69. const userLogin = wx.getStorageSync('userLogin');
  70. // 如果有 Parse 用户但没有 userLogin,说明状态不一致
  71. if (currentUser && !userLogin) {
  72. console.log('⚠️ 检测到异常登录状态:有 Parse 用户但没有 userLogin');
  73. console.log(' 用户 ID:', currentUser.id);
  74. console.log(' 手机号:', currentUser.get('mobile') || '无');
  75. // 如果用户有手机号,补充设置 userLogin
  76. if (currentUser.get('mobile')) {
  77. wx.setStorageSync('userLogin', currentUser.id);
  78. console.log('✅ 已补充设置 userLogin');
  79. } else {
  80. // 如果用户没有手机号,清除这个无效的用户
  81. console.log('🧹 用户没有手机号,清除无效状态');
  82. await clearLogin.clearAllLoginState();
  83. }
  84. }
  85. // 如果有 userLogin 但没有 Parse 用户,说明状态不一致
  86. if (!currentUser && userLogin) {
  87. console.log('⚠️ 检测到异常登录状态:有 userLogin 但没有 Parse 用户');
  88. console.log(' userLogin:', userLogin);
  89. console.log('🧹 清除无效的 userLogin');
  90. wx.removeStorageSync('userLogin');
  91. }
  92. } catch (error) {
  93. console.error('❌ 检查登录状态失败:', error);
  94. }
  95. },
  96. /**
  97. * 检查 Company 的 isPublishing 状态
  98. * 只有 isPublishing == true 时才显示 AI 相关内容
  99. */
  100. async checkPublishingStatus() {
  101. try {
  102. // 先尝试从全局或缓存读取
  103. let isPublishing = getApp().globalData.isPublishing;
  104. if (isPublishing === undefined) {
  105. isPublishing = wx.getStorageSync('isPublishing');
  106. }
  107. // 如果缓存中没有,查询数据库
  108. if (isPublishing === undefined || isPublishing === '') {
  109. const companyQuery = new Parse.Query('Company');
  110. companyQuery.equalTo('objectId', getApp().globalData.company);
  111. companyQuery.select('isPublishing');
  112. const companyObj = await companyQuery.first();
  113. if (companyObj) {
  114. isPublishing = companyObj.get('isPublishing') === true;
  115. } else {
  116. isPublishing = false;
  117. }
  118. // 保存到全局和缓存
  119. getApp().globalData.isPublishing = isPublishing;
  120. wx.setStorageSync('isPublishing', isPublishing);
  121. }
  122. console.log('📋 isPublishing 状态:', isPublishing);
  123. console.log('🤖 是否显示 AI:', isPublishing);
  124. // 更新组件数据
  125. this.setData({
  126. showAI: isPublishing === true
  127. });
  128. } catch (error) {
  129. console.error('❌ 检查 isPublishing 状态失败:', error);
  130. // 出错时默认不显示 AI
  131. this.setData({
  132. showAI: false
  133. });
  134. }
  135. },
  136. /**
  137. * 在控制台显示当前登录用户信息
  138. */
  139. showCurrentUser() {
  140. const currentUser = Parse.User.current();
  141. console.log('===========================================');
  142. console.log('======= 当前登录用户信息 =======');
  143. console.log('===========================================');
  144. if (currentUser) {
  145. console.log('✅ 用户已登录');
  146. console.log('📱 用户ID:', currentUser.id);
  147. console.log('📞 手机号:', currentUser.get('mobile') || '未设置');
  148. console.log('👤 用户名:', currentUser.get('username') || '未设置');
  149. console.log('🔑 Session Token:', currentUser.getSessionToken());
  150. console.log('📧 邮箱:', currentUser.get('email') || '未设置');
  151. console.log('📦 完整用户对象:', currentUser);
  152. console.log('📋 所有属性:', currentUser.attributes);
  153. } else {
  154. console.log('❌ 当前没有登录用户');
  155. }
  156. console.log('===========================================');
  157. },
  158. /**
  159. * 检查是否首次访问
  160. */
  161. checkFirstVisit() {
  162. try {
  163. const hasVisited = wx.getStorageSync('hasVisitedWelcome');
  164. if (!hasVisited) {
  165. console.log('首次访问,显示引导页');
  166. } else {
  167. console.log('已访问过,可选择是否直接跳转');
  168. // 如果需要自动跳转到主页,可以在这里调用 this.navigateToHome()
  169. }
  170. } catch (e) {
  171. console.error('检查访问状态失败:', e);
  172. }
  173. },
  174. /**
  175. * 检查 Company 的 isPublishing 状态
  176. * 用于控制是否显示 AI 相关内容
  177. */
  178. async checkPublishingStatus() {
  179. try {
  180. console.log('🔍 开始检查 isPublishing 状态...');
  181. // 先尝试从缓存读取
  182. let isPublishing = wx.getStorageSync('isPublishing');
  183. if (isPublishing === '' || isPublishing === null || isPublishing === undefined) {
  184. // 缓存中没有,查询 Company 表
  185. const companyQuery = new Parse.Query('Company');
  186. companyQuery.equalTo('objectId', getApp().globalData.company);
  187. companyQuery.select('isPublishing');
  188. const companyObj = await companyQuery.first();
  189. if (companyObj) {
  190. isPublishing = companyObj.get('isPublishing') === true;
  191. console.log('📋 从数据库查询 isPublishing:', isPublishing);
  192. // 保存到缓存
  193. wx.setStorageSync('isPublishing', isPublishing);
  194. getApp().globalData.isPublishing = isPublishing;
  195. } else {
  196. console.warn('⚠️ 未找到 Company 记录');
  197. isPublishing = false;
  198. }
  199. } else {
  200. console.log('📦 从缓存读取 isPublishing:', isPublishing);
  201. }
  202. // 更新组件状态
  203. this.setData({
  204. showAI: isPublishing === true
  205. });
  206. console.log('✅ isPublishing 状态检查完成');
  207. console.log(' - isPublishing:', isPublishing);
  208. console.log(' - showAI:', isPublishing === true);
  209. console.log('===========================================');
  210. } catch (error) {
  211. console.error('❌ 检查 isPublishing 状态失败:', error);
  212. // 出错时默认不显示 AI
  213. this.setData({
  214. showAI: false
  215. });
  216. }
  217. },
  218. /**
  219. * 点击"立即开始探索"按钮
  220. */
  221. onStart() {
  222. console.log('===========================================');
  223. console.log('🚀 调用了 onStart 方法(立即开始探索)');
  224. console.log('===========================================');
  225. // 标记已访问
  226. wx.setStorageSync('hasVisitedWelcome', true);
  227. // 跳转到 H5 主页
  228. this.navigateToHome();
  229. },
  230. /**
  231. * 点击"跳过引导"按钮
  232. */
  233. onSkip() {
  234. // 标记已访问
  235. wx.setStorageSync('hasVisitedWelcome', true);
  236. // 跳转到 H5 主页
  237. this.navigateToHome();
  238. },
  239. /**
  240. * 点击"查看新手指南"
  241. */
  242. onGuide() {
  243. wx.showToast({
  244. title: '新手指南开发中',
  245. icon: 'none',
  246. duration: 2000
  247. });
  248. // TODO: 后续可以跳转到新手指南页面
  249. // wx.navigateTo({
  250. // url: '/pages/guide/index'
  251. // });
  252. },
  253. /**
  254. * 验证 token 是否有效
  255. */
  256. async validateToken(token) {
  257. try {
  258. console.log('🔍 开始验证 token 有效性...');
  259. // 使用 Parse.User.become() 验证 token
  260. const user = await Parse.User.become(token);
  261. if (user) {
  262. console.log('✅ Token 有效!用户:', user.id);
  263. return true;
  264. }
  265. console.log('⚠️ Token 验证返回空用户');
  266. return false;
  267. } catch (error) {
  268. console.error('❌ Token 验证失败:', error.message);
  269. return false;
  270. }
  271. },
  272. /**
  273. * 刷新用户 session token
  274. */
  275. async refreshToken() {
  276. try {
  277. console.log('🔄 开始刷新 token...');
  278. const currentUser = Parse.User.current();
  279. if (!currentUser) {
  280. console.error('❌ 当前没有登录用户,无法刷新 token');
  281. return null;
  282. }
  283. // 保存用户信息以触发 session token 刷新
  284. await currentUser.fetch();
  285. const newToken = currentUser.getSessionToken();
  286. console.log('✅ Token 刷新成功');
  287. console.log('🔑 新 Token (前20字符):', newToken.substring(0, 20));
  288. return newToken;
  289. } catch (error) {
  290. console.error('❌ Token 刷新失败:', error.message);
  291. return null;
  292. }
  293. },
  294. /**
  295. * 获取店铺 ID
  296. * 优先级:
  297. * 1. 扫码进入的 storeId(最高优先级)
  298. * 2. 用户历史访问的 storeId
  299. * 3. 超级门店 ID(默认值)
  300. *
  301. * 注意:如果需要切换店铺(非扫码),请先调用:
  302. * wx.removeStorageSync('storeId_from_scan')
  303. */
  304. async getStoreId() {
  305. try {
  306. console.log('🏪 开始获取店铺 ID...');
  307. const defaultStoreId = 'pkPdAnLAUZ'; // 超级门店ID
  308. // 检查是否是扫码进入
  309. const isFromScan = wx.getStorageSync('storeId_from_scan');
  310. const storedStoreId = wx.getStorageSync('storeId');
  311. const globalStoreId = getApp().globalData.storeId;
  312. let configuredStoreId;
  313. if (isFromScan && storedStoreId) {
  314. // 优先级1:扫码进入的店铺(最高优先级)
  315. configuredStoreId = storedStoreId;
  316. console.log('🎯 使用扫码进入的店铺 ID:', configuredStoreId);
  317. } else if (storedStoreId) {
  318. // 优先级2:用户历史访问的店铺
  319. configuredStoreId = storedStoreId;
  320. console.log('📍 使用历史访问的店铺 ID:', configuredStoreId);
  321. } else if (globalStoreId) {
  322. // 优先级3:全局设置的店铺
  323. configuredStoreId = globalStoreId;
  324. console.log('🌐 使用全局店铺 ID:', configuredStoreId);
  325. } else {
  326. // 优先级4:默认超级门店
  327. configuredStoreId = defaultStoreId;
  328. console.log('⭐ 使用默认超级门店 ID:', configuredStoreId);
  329. }
  330. console.log('✅ 最终使用店铺 ID:', configuredStoreId);
  331. return configuredStoreId;
  332. } catch (error) {
  333. console.error('❌ 获取店铺 ID 失败:', error);
  334. return 'pkPdAnLAUZ';
  335. }
  336. },
  337. /**
  338. * 获取店铺信息(id 与 名称)
  339. * 优先级:
  340. * 1. 扫码进入的 storeId(最高优先级)
  341. * 2. 用户历史访问的 storeId
  342. * 3. 超级门店 ID(默认值)
  343. */
  344. async getStoreInfo() {
  345. try {
  346. const defaultStoreId = 'pkPdAnLAUZ'; // 超级门店ID
  347. // 检查是否是扫码进入
  348. const isFromScan = wx.getStorageSync('storeId_from_scan');
  349. const storedStoreId = wx.getStorageSync('storeId');
  350. const globalStoreId = getApp().globalData.storeId;
  351. let effectiveStoreId;
  352. if (isFromScan && storedStoreId) {
  353. // 优先级1:扫码进入的店铺(最高优先级)
  354. effectiveStoreId = storedStoreId;
  355. console.log('🎯 使用扫码进入的店铺 ID:', effectiveStoreId);
  356. } else if (storedStoreId) {
  357. // 优先级2:用户历史访问的店铺
  358. effectiveStoreId = storedStoreId;
  359. console.log('📍 使用历史访问的店铺 ID:', effectiveStoreId);
  360. } else if (globalStoreId) {
  361. // 优先级3:全局设置的店铺
  362. effectiveStoreId = globalStoreId;
  363. console.log('🌐 使用全局店铺 ID:', effectiveStoreId);
  364. } else {
  365. // 优先级4:默认超级门店
  366. effectiveStoreId = defaultStoreId;
  367. console.log('⭐ 使用默认超级门店 ID:', effectiveStoreId);
  368. }
  369. const query = new Parse.Query('ShopStore');
  370. query.equalTo('objectId', effectiveStoreId);
  371. const store = await query.first();
  372. if (store) {
  373. const name = store.get('storeName') || '';
  374. console.log('✅ 获取店铺信息:', { id: effectiveStoreId, name });
  375. return { id: effectiveStoreId, name };
  376. } else {
  377. console.log('⚠️ 未找到店铺,仅返回 ID');
  378. return { id: effectiveStoreId, name: '' };
  379. }
  380. } catch (e) {
  381. console.error('获取店铺信息失败:', e);
  382. const fallbackId = wx.getStorageSync('storeId') || 'pkPdAnLAUZ';
  383. return { id: fallbackId, name: '' };
  384. }
  385. },
  386. /**
  387. * 跳转到 H5 主页
  388. */
  389. async navigateToHome() {
  390. console.log('===========================================');
  391. console.log('======= navigateToHome 被调用 =======');
  392. console.log('===========================================');
  393. let currentUser = Parse.User.current();
  394. let userInfo = wx.getStorageSync("userLogin");
  395. console.log('当前用户:', currentUser ? currentUser.id : '无');
  396. console.log('用户手机号:', currentUser?.get('mobile') || '无');
  397. console.log('userInfo:', userInfo || '无');
  398. // 如果有 Parse 用户但没有 userInfo,可能是刚登录,等待同步
  399. if (currentUser && currentUser.get('mobile') && !userInfo) {
  400. console.log('⏳ 检测到刚登录,等待状态同步...');
  401. // 等待 500ms
  402. await new Promise(resolve => setTimeout(resolve, 500));
  403. // 重新获取
  404. currentUser = Parse.User.current();
  405. userInfo = wx.getStorageSync("userLogin");
  406. // 如果还是没有,手动设置
  407. if (currentUser && currentUser.get('mobile') && !userInfo) {
  408. wx.setStorageSync("userLogin", currentUser.id);
  409. userInfo = currentUser.id;
  410. console.log('✅ 手动设置 userLogin:', userInfo);
  411. }
  412. }
  413. // 重新检查登录状态
  414. const isLoggedIn = currentUser && currentUser.get('mobile') && userInfo;
  415. console.log('最终登录状态:', isLoggedIn ? '已登录' : '未登录');
  416. // 如果用户未登录,进入游客模式
  417. if (!isLoggedIn) {
  418. console.log('⚠️ 用户未登录,进入游客模式');
  419. this.navigateToHomeAsGuest();
  420. return;
  421. }
  422. let token = currentUser.getSessionToken();
  423. if (!token) {
  424. console.error('❌ 无法获取 Session Token!');
  425. wx.showToast({
  426. title: '获取登录信息失败',
  427. icon: 'none'
  428. });
  429. return;
  430. }
  431. // 验证 token 是否有效
  432. const isValid = await this.validateToken(token);
  433. if (!isValid) {
  434. wx.showLoading({
  435. title: '正在刷新登录...'
  436. });
  437. // 尝试刷新 token
  438. const newToken = await this.refreshToken();
  439. wx.hideLoading();
  440. if (newToken) {
  441. token = newToken;
  442. } else {
  443. console.error('❌ Token 刷新失败,需要重新登录');
  444. wx.showModal({
  445. title: '提示',
  446. content: '登录已过期,请重新登录',
  447. showCancel: false,
  448. success: () => {
  449. wx.navigateTo({
  450. url: 'plugin://fm-plugin/fm-auth'
  451. });
  452. }
  453. });
  454. return;
  455. }
  456. } else {
  457. // token 验证通过
  458. }
  459. // 获取店铺信息
  460. const store = await this.getStoreInfo();
  461. const storeId = store && store.id ? store.id : null;
  462. const storeName = store && store.name ? store.name : '';
  463. // 构建 H5 URL(重要:storeId 和 token 作为查询参数)
  464. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?`;
  465. // 如果有 storeId,添加到 URL 中
  466. if (storeId) {
  467. h5Url += `storeId=${storeId}&`;
  468. }
  469. h5Url += `token=${token}`;
  470. console.log('🌐 H5 URL:', h5Url);
  471. console.log(' - URL 长度:', h5Url.length);
  472. if (storeId) {
  473. console.log(' - 店铺 ID:', storeId);
  474. }
  475. // 编码后的 URL
  476. const encodedUrl = encodeURIComponent(h5Url);
  477. console.log('📦 编码后的 URL:', encodedUrl.substring(0, 100) + '...');
  478. // 最终的小程序页面路径
  479. // 传递店铺信息给 web-view 页面,优先用于设置标题
  480. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
  481. if (storeId) {
  482. webViewPath += `&storeId=${storeId}`;
  483. }
  484. if (storeName) {
  485. webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
  486. }
  487. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  488. console.log('===========================================');
  489. wx.navigateTo({
  490. url: webViewPath,
  491. success: () => {
  492. console.log('✅ 跳转成功');
  493. },
  494. fail: (err) => {
  495. console.error('❌ 跳转失败:', err);
  496. wx.showToast({
  497. title: '跳转失败,请重试',
  498. icon: 'none'
  499. });
  500. }
  501. });
  502. },
  503. /**
  504. * 游客模式跳转到主页
  505. */
  506. async navigateToHomeAsGuest() {
  507. try {
  508. console.log('===========================================');
  509. console.log('======= 游客模式访问 =======');
  510. console.log('===========================================');
  511. // 标记为游客模式
  512. wx.setStorageSync('isGuestMode', true);
  513. // ✅ 游客默认使用超级门店ID,确保有数据
  514. const superStoreId = 'pkPdAnLAUZ'; // 超级门店ID
  515. // 设置超级门店ID到存储
  516. wx.setStorageSync('storeId', superStoreId);
  517. getApp().globalData.storeId = superStoreId;
  518. console.log('✅ 游客使用超级门店ID:', superStoreId);
  519. // 获取店铺信息
  520. const store = await this.getStoreInfo();
  521. const storeId = store && store.id ? store.id : superStoreId;
  522. const storeName = store && store.name ? store.name : '超级门店';
  523. console.log('✅ 店铺信息:', { id: storeId, name: storeName });
  524. // 构建 H5 URL(游客模式,不传 token)
  525. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?`;
  526. h5Url += `storeId=${storeId}&`;
  527. // 添加游客模式标识
  528. h5Url += `guestMode=true`;
  529. console.log('🌐 游客模式 H5 URL:', h5Url);
  530. console.log('');
  531. console.log('⚠️⚠️⚠️ 重要提示 ⚠️⚠️⚠️');
  532. console.log('如果H5页面显示的不是超级门店,说明H5端没有正确使用URL中的storeId参数!');
  533. console.log('H5端需要确保:');
  534. console.log('1. 从URL中读取 storeId 参数');
  535. console.log('2. 优先使用URL传递的 storeId,不要被其他逻辑覆盖');
  536. console.log('3. 不要使用localStorage缓存的旧门店ID');
  537. console.log('');
  538. console.log('请复制以下URL在浏览器中测试:');
  539. console.log(h5Url);
  540. console.log('===========================================');
  541. // 编码后的 URL
  542. const encodedUrl = encodeURIComponent(h5Url);
  543. // 跳转
  544. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
  545. webViewPath += `&storeId=${storeId}`;
  546. if (storeName) {
  547. webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
  548. }
  549. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  550. console.log('===========================================');
  551. wx.navigateTo({
  552. url: webViewPath,
  553. success: () => {
  554. console.log('✅ 游客模式跳转成功');
  555. },
  556. fail: (err) => {
  557. console.error('❌ 跳转失败:', err);
  558. wx.showToast({
  559. title: '跳转失败,请重试',
  560. icon: 'none'
  561. });
  562. }
  563. });
  564. } catch (error) {
  565. console.error('❌ 游客模式跳转失败:', error);
  566. wx.showToast({
  567. title: '加载失败,请重试',
  568. icon: 'none'
  569. });
  570. }
  571. },
  572. /**
  573. * 轮播图变化事件
  574. */
  575. onSwiperChange(e) {
  576. this.setData({
  577. currentSwiperIndex: e.detail.current
  578. });
  579. },
  580. /**
  581. * 跳转到案例展示页面
  582. */
  583. async navigateToCases() {
  584. console.log('===========================================');
  585. console.log('🏠 调用了 navigateToCases 方法(案例展示)');
  586. console.log('===========================================');
  587. // 案例展示允许游客访问,直接跳转
  588. const currentUser = Parse.User.current();
  589. if (!currentUser) {
  590. console.log('游客访问案例展示');
  591. wx.setStorageSync('isGuestMode', true);
  592. await this.navigateToH5PageAsGuest('owner/nav/cases');
  593. } else {
  594. await this.navigateToH5Page('owner/nav/cases');
  595. }
  596. },
  597. /**
  598. * 跳转到产品中心页面
  599. * @param {string} productId - 可选的产品ID,用于直接跳转到特定产品详情
  600. */
  601. async navigateToProducts(productId = null) {
  602. console.log('===========================================');
  603. console.log('📦 调用了 navigateToProducts 方法(产品中心)');
  604. console.log('===========================================');
  605. // 产品中心允许游客访问,直接跳转
  606. const currentUser = Parse.User.current();
  607. const params = productId ? { productId } : {};
  608. if (!currentUser) {
  609. console.log('游客访问产品中心');
  610. wx.setStorageSync('isGuestMode', true);
  611. await this.navigateToH5PageAsGuest('owner/nav/products', params);
  612. } else {
  613. await this.navigateToH5Page('owner/nav/products', params);
  614. }
  615. },
  616. /**
  617. * 跳转到方案定制/AI推荐页面
  618. */
  619. async navigateToConsultation() {
  620. console.log('===========================================');
  621. console.log('======= 点击咨询/方案定制 =======');
  622. console.log('===========================================');
  623. // 方案定制需要登录
  624. let currentUser = Parse.User.current();
  625. const isGuestMode = wx.getStorageSync('isGuestMode');
  626. let userLogin = wx.getStorageSync('userLogin');
  627. console.log('当前用户:', currentUser ? currentUser.id : '无');
  628. console.log('用户手机号:', currentUser?.get('mobile') || '无');
  629. console.log('游客模式:', isGuestMode);
  630. console.log('userLogin 存储:', userLogin || '无');
  631. // 如果有 Parse 用户但没有 userLogin,可能是刚授权完成,等待一下
  632. if (currentUser && currentUser.get('mobile') && !userLogin) {
  633. console.log('⏳ 检测到刚授权完成,等待状态同步...');
  634. // 等待 500ms 后重新检查
  635. await new Promise(resolve => setTimeout(resolve, 500));
  636. // 重新获取状态
  637. currentUser = Parse.User.current();
  638. userLogin = wx.getStorageSync('userLogin');
  639. // 如果还是没有 userLogin,手动设置
  640. if (currentUser && currentUser.get('mobile') && !userLogin) {
  641. wx.setStorageSync("userLogin", currentUser.id);
  642. userLogin = currentUser.id;
  643. console.log('✅ 手动设置 userLogin:', userLogin);
  644. }
  645. }
  646. // 检查用户是否真正登录(有手机号且有 userLogin 存储)
  647. const isReallyLoggedIn = currentUser && currentUser.get('mobile') && userLogin;
  648. console.log('最终登录状态:', isReallyLoggedIn ? '已登录' : '未登录');
  649. // 如果用户已经真正登录,清除游客模式标记
  650. if (isReallyLoggedIn && isGuestMode) {
  651. console.log('✅ 用户已登录,清除游客模式标记');
  652. wx.removeStorageSync('isGuestMode');
  653. }
  654. // 只有在真正未登录时才提示
  655. if (!isReallyLoggedIn) {
  656. console.log('⚠️ 用户未完成登录,显示登录提示');
  657. wx.showModal({
  658. title: '需要登录',
  659. content: '方案定制和咨询功能需要登录后使用,是否立即登录?',
  660. confirmText: '立即登录',
  661. cancelText: '取消',
  662. success: async (res) => {
  663. if (res.confirm) {
  664. console.log('用户选择:立即登录');
  665. // 不要清除登录状态,因为可能用户刚登录成功只是状态没同步
  666. // 直接跳转到登录页面
  667. console.log('准备调用 login.loginNow()');
  668. // 直接调用登录方法
  669. const loginResult = login.loginNow();
  670. console.log('login.loginNow() 返回值:', loginResult);
  671. // 如果返回 false,说明已经跳转到登录页面
  672. if (!loginResult) {
  673. console.log('✅ 已跳转到登录页面');
  674. // 设置待处理的跳转,登录成功后自动跳转到咨询页面
  675. wx.setStorageSync('pendingNavigation', 'consultation');
  676. console.log('📌 已设置待处理跳转: consultation');
  677. }
  678. } else {
  679. console.log('用户选择:取消');
  680. }
  681. }
  682. });
  683. return;
  684. }
  685. console.log('✅ 用户已登录,跳转到咨询页面');
  686. console.log('===========================================');
  687. await this.navigateToH5Page('owner/nav/consultation');
  688. },
  689. /**
  690. * 通用 H5 页面跳转方法
  691. * @param {string} pagePath - H5 页面路径(例如: 'owner/nav/cases')
  692. * @param {object} extraParams - 额外的URL参数对象(例如: { productId: 'xxx' })
  693. */
  694. async navigateToH5Page(pagePath, extraParams = {}) {
  695. console.log('===========================================');
  696. console.log(`======= 小程序跳转 H5: ${pagePath} =======`);
  697. console.log('===========================================');
  698. const currentUser = Parse.User.current();
  699. let userInfo = wx.getStorageSync("userLogin");
  700. console.log('📱 当前登录状态检查:');
  701. console.log(' Parse.User.current():', currentUser ? currentUser.id : '无');
  702. console.log(' 用户手机号:', currentUser?.get('mobile') || '无');
  703. console.log(' userLogin 存储:', userInfo || '无');
  704. console.log(' Session Token (前20字符):', currentUser?.getSessionToken()?.substring(0, 20) || '无');
  705. // 检查是否是游客模式
  706. const isGuestMode = wx.getStorageSync('isGuestMode');
  707. console.log(' 游客模式:', isGuestMode);
  708. // 定义允许游客访问的页面
  709. const guestAllowedPages = [
  710. 'owner/nav/home', // 首页
  711. 'owner/nav/products', // 产品中心
  712. 'owner/nav/cases' // 案例展示
  713. ];
  714. // 检查当前页面是否允许游客访问
  715. const isGuestAllowed = guestAllowedPages.some(page => pagePath.includes(page));
  716. if ((!currentUser || userInfo == '') && !isGuestMode) {
  717. // 未登录且不是游客模式,提示用户
  718. wx.showModal({
  719. title: '温馨提示',
  720. content: '登录后可以体验更多功能,是否立即登录?',
  721. confirmText: '立即登录',
  722. cancelText: '先随便看看',
  723. success: (res) => {
  724. if (res.confirm) {
  725. // 用户选择登录
  726. login.loginNow();
  727. } else {
  728. // 用户选择游客模式
  729. if (isGuestAllowed) {
  730. // 如果是允许游客访问的页面,继续访问
  731. wx.setStorageSync('isGuestMode', true);
  732. this.navigateToH5PageAsGuest(pagePath, extraParams);
  733. } else {
  734. // 如果不允许游客访问,提示需要登录
  735. wx.showToast({
  736. title: '此功能需要登录',
  737. icon: 'none'
  738. });
  739. }
  740. }
  741. }
  742. });
  743. return;
  744. }
  745. // 如果是游客模式,检查是否允许访问
  746. if (isGuestMode || !currentUser) {
  747. if (!isGuestAllowed) {
  748. // 游客不允许访问此页面
  749. wx.showModal({
  750. title: '需要登录',
  751. content: '此功能需要登录后使用,是否立即登录?',
  752. confirmText: '立即登录',
  753. cancelText: '取消',
  754. success: (res) => {
  755. if (res.confirm) {
  756. login.loginNow();
  757. }
  758. }
  759. });
  760. return;
  761. }
  762. // 游客访问允许的页面
  763. this.navigateToH5PageAsGuest(pagePath, extraParams);
  764. return;
  765. }
  766. let token = currentUser.getSessionToken();
  767. console.log('🔑 准备传递的 Token:');
  768. console.log(' 完整 Token:', token);
  769. console.log(' Token 长度:', token ? token.length : 0);
  770. console.log(' Token 前20个字符:', token ? token.substring(0, 20) : 'null');
  771. if (!token) {
  772. console.error('❌ 无法获取 Session Token!');
  773. wx.showToast({
  774. title: '获取登录信息失败',
  775. icon: 'none'
  776. });
  777. return;
  778. }
  779. // 验证 token 是否有效
  780. console.log('🔍 验证 token 有效性...');
  781. const isValid = await this.validateToken(token);
  782. if (!isValid) {
  783. console.log('⚠️ Token 已失效,尝试刷新...');
  784. wx.showLoading({
  785. title: '正在刷新登录...'
  786. });
  787. // 尝试刷新 token
  788. const newToken = await this.refreshToken();
  789. wx.hideLoading();
  790. if (newToken) {
  791. token = newToken;
  792. console.log('✅ 使用新的 token:', token.substring(0, 20));
  793. } else {
  794. console.error('❌ Token 刷新失败,需要重新登录');
  795. wx.showModal({
  796. title: '提示',
  797. content: '登录已过期,请重新登录',
  798. showCancel: false,
  799. success: () => {
  800. wx.navigateTo({
  801. url: 'plugin://fm-plugin/fm-auth'
  802. });
  803. }
  804. });
  805. return;
  806. }
  807. } else {
  808. console.log('✅ Token 验证通过');
  809. }
  810. // 获取店铺信息
  811. const store = await this.getStoreInfo();
  812. const storeId = store && store.id ? store.id : null;
  813. const storeName = store && store.name ? store.name : '';
  814. // 构建 H5 URL(重要:storeId 和 token 作为查询参数)
  815. let h5Url = `https://app.fmode.cn/dev/pobingfeng/${pagePath}?`;
  816. // 如果有 storeId,添加到 URL 中
  817. if (storeId) {
  818. h5Url += `storeId=${storeId}&`;
  819. }
  820. h5Url += `token=${token}`;
  821. console.log('🌐 构建的 H5 URL:');
  822. console.log(' 完整 URL:', h5Url);
  823. console.log(' URL 中的 token (前20字符):', token.substring(0, 20));
  824. // 添加额外的参数(如 productId)
  825. if (extraParams && Object.keys(extraParams).length > 0) {
  826. for (const [key, value] of Object.entries(extraParams)) {
  827. if (value) {
  828. h5Url += `&${key}=${encodeURIComponent(value)}`;
  829. console.log(` - 添加参数 ${key}:`, value);
  830. }
  831. }
  832. }
  833. // 编码后的 URL
  834. const encodedUrl = encodeURIComponent(h5Url);
  835. // 最终的小程序页面路径
  836. // 传递店铺信息给 web-view 页面,优先用于设置标题
  837. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
  838. if (storeId) {
  839. webViewPath += `&storeId=${storeId}`;
  840. }
  841. if (storeName) {
  842. webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
  843. }
  844. console.log('📄 最终跳转路径:', webViewPath.substring(0, 150) + '...');
  845. console.log('===========================================');
  846. wx.navigateTo({
  847. url: webViewPath,
  848. success: () => {
  849. console.log('✅ 跳转成功');
  850. },
  851. fail: (err) => {
  852. console.error('❌ 跳转失败:', err);
  853. wx.showToast({
  854. title: '跳转失败,请重试',
  855. icon: 'none'
  856. });
  857. }
  858. });
  859. },
  860. /**
  861. * 游客模式跳转 H5 页面
  862. * @param {string} pagePath - H5 页面路径
  863. * @param {object} extraParams - 额外参数
  864. */
  865. async navigateToH5PageAsGuest(pagePath, extraParams = {}) {
  866. try {
  867. console.log('===========================================');
  868. console.log(`======= 游客模式跳转 H5: ${pagePath} =======`);
  869. console.log('===========================================');
  870. // ✅ 游客默认使用超级门店ID,确保有数据
  871. const superStoreId = 'pkPdAnLAUZ'; // 超级门店ID
  872. // 确保使用超级门店ID
  873. wx.setStorageSync('storeId', superStoreId);
  874. getApp().globalData.storeId = superStoreId;
  875. console.log('✅ 游客使用超级门店ID:', superStoreId);
  876. // 获取店铺信息
  877. const store = await this.getStoreInfo();
  878. const storeId = store && store.id ? store.id : superStoreId;
  879. const storeName = store && store.name ? store.name : '超级门店';
  880. console.log('✅ 店铺信息:', { id: storeId, name: storeName });
  881. // 构建 H5 URL(游客模式,不传 token)
  882. let h5Url = `https://app.fmode.cn/dev/pobingfeng/${pagePath}?`;
  883. h5Url += `storeId=${storeId}&`;
  884. // 添加游客模式标识
  885. h5Url += `guestMode=true`;
  886. // 添加额外的参数
  887. if (extraParams && Object.keys(extraParams).length > 0) {
  888. for (const [key, value] of Object.entries(extraParams)) {
  889. if (value) {
  890. h5Url += `&${key}=${encodeURIComponent(value)}`;
  891. console.log(` - 添加参数 ${key}:`, value);
  892. }
  893. }
  894. }
  895. console.log('🌐 游客模式 H5 URL:', h5Url);
  896. console.log('');
  897. console.log('⚠️ 如果H5显示的不是超级门店,请检查H5端是否正确读取了URL中的storeId参数');
  898. console.log('');
  899. // 编码后的 URL
  900. const encodedUrl = encodeURIComponent(h5Url);
  901. // 最终的小程序页面路径
  902. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}`;
  903. webViewPath += `&storeId=${storeId}`;
  904. if (storeName) {
  905. webViewPath += `&storeName=${encodeURIComponent(storeName)}`;
  906. }
  907. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  908. console.log('===========================================');
  909. wx.navigateTo({
  910. url: webViewPath,
  911. success: () => {
  912. console.log('✅ 游客模式跳转成功');
  913. },
  914. fail: (err) => {
  915. console.error('❌ 跳转失败:', err);
  916. wx.showToast({
  917. title: '跳转失败,请重试',
  918. icon: 'none'
  919. });
  920. }
  921. });
  922. } catch (error) {
  923. console.error('❌ 游客模式跳转失败:', error);
  924. wx.showToast({
  925. title: '加载失败,请重试',
  926. icon: 'none'
  927. });
  928. }
  929. }
  930. }
  931. })