index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // common-page/pages/web-view/index.js
  2. const Parse = getApp().Parse;
  3. const company = getApp().globalData.company;
  4. Page({
  5. /**
  6. * 页面的初始数据
  7. */
  8. data: {
  9. path: "",
  10. currentTitle: "", // 当前标题
  11. },
  12. // 标题轮询定时器
  13. titlePollingTimer: null,
  14. /**
  15. * 生命周期函数--监听页面加载
  16. */
  17. onLoad: async function (options) {
  18. console.log('===========================================');
  19. console.log('======= web-view 页面加载 =======');
  20. // 1. 先检查用户登录状态
  21. const loginCheck = await this.checkUserLogin(options);
  22. if (!loginCheck) {
  23. console.log('⚠️ 用户未登录或没有手机号,已跳转到授权页面');
  24. console.log('===========================================');
  25. return; // 停止后续加载
  26. }
  27. console.log('✅ 用户已登录且有手机号,继续加载 web-view');
  28. const postAuthModal = wx.getStorageSync('post_auth_modal');
  29. if (postAuthModal && (postAuthModal.title || postAuthModal.content)) {
  30. wx.removeStorageSync('post_auth_modal');
  31. await new Promise((resolve) => {
  32. wx.showModal({
  33. title: postAuthModal.title || '温馨提示',
  34. content: postAuthModal.content || '',
  35. showCancel: false,
  36. success: () => resolve(),
  37. fail: () => resolve(),
  38. complete: () => resolve(),
  39. });
  40. });
  41. }
  42. const upsertQueryParam = (url, key, value) => {
  43. if (!url || !key) return url;
  44. const safeValue = value === undefined || value === null ? '' : String(value);
  45. const [base, hash] = url.split('#');
  46. const [pathPart, queryString] = base.split('?');
  47. const pairs = (queryString || '')
  48. .split('&')
  49. .filter(Boolean)
  50. .map((p) => {
  51. const idx = p.indexOf('=');
  52. if (idx === -1) return [p, ''];
  53. return [p.slice(0, idx), p.slice(idx + 1)];
  54. });
  55. let found = false;
  56. const nextPairs = pairs.map(([k, v]) => {
  57. if (k === key) {
  58. found = true;
  59. return [k, encodeURIComponent(safeValue)];
  60. }
  61. return [k, v];
  62. });
  63. if (!found) nextPairs.push([key, encodeURIComponent(safeValue)]);
  64. const nextQuery = nextPairs.length ? nextPairs.map(([k, v]) => `${k}=${v}`).join('&') : '';
  65. const nextBase = nextQuery ? `${pathPart}?${nextQuery}` : pathPart;
  66. return hash !== undefined ? `${nextBase}#${hash}` : nextBase;
  67. };
  68. const removeQueryParam = (url, key) => {
  69. if (!url || !key) return url;
  70. const [base, hash] = url.split('#');
  71. const [pathPart, queryString] = base.split('?');
  72. if (!queryString) return url;
  73. const nextPairs = queryString
  74. .split('&')
  75. .filter(Boolean)
  76. .map((p) => {
  77. const idx = p.indexOf('=');
  78. if (idx === -1) return [p, ''];
  79. return [p.slice(0, idx), p.slice(idx + 1)];
  80. })
  81. .filter(([k]) => k !== key);
  82. const nextQuery = nextPairs.length ? nextPairs.map(([k, v]) => `${k}=${v}`).join('&') : '';
  83. const nextBase = nextQuery ? `${pathPart}?${nextQuery}` : pathPart;
  84. return hash !== undefined ? `${nextBase}#${hash}` : nextBase;
  85. };
  86. // 2. 解码 URL
  87. let path = decodeURIComponent(options.path || '');
  88. console.log('原始 options.path:', options.path);
  89. console.log('解码后的 path:', path);
  90. const currentUser = Parse.User.current();
  91. const sessionToken = currentUser?.getSessionToken ? currentUser.getSessionToken() : null;
  92. if (sessionToken) {
  93. path = upsertQueryParam(path, 'token', sessionToken);
  94. path = removeQueryParam(path, 'guestMode');
  95. } else {
  96. const hasToken = path.includes('token=');
  97. const hasGuestMode = path.includes('guestMode=');
  98. if (!hasToken && !hasGuestMode) {
  99. path = upsertQueryParam(path, 'guestMode', 'true');
  100. }
  101. }
  102. // 拼接额外参数(避免重复添加已存在的参数)
  103. let hasQuery = path.indexOf('?') !== -1;
  104. let parsm = hasQuery ? '&' : '?';
  105. let params = [];
  106. // 提取 path 中已有的参数
  107. let existingParams = new Set();
  108. if (hasQuery) {
  109. const queryString = path.split('?')[1];
  110. if (queryString) {
  111. queryString.split('&').forEach(param => {
  112. const key = param.split('=')[0];
  113. existingParams.add(key);
  114. });
  115. }
  116. }
  117. // 只添加 path 中不存在的参数
  118. for (const key in options) {
  119. if(key != 'path' && key != 'url' && !existingParams.has(key)){
  120. params.push(key + '=' + options[key]);
  121. }
  122. }
  123. if(params.length > 0) {
  124. parsm = parsm + params.join('&');
  125. path = path + parsm;
  126. }
  127. console.log('最终 web-view URL:', path);
  128. console.log('URL 长度:', path.length);
  129. console.log('===========================================');
  130. this.setData({
  131. path: path
  132. })
  133. // 立即设置标题
  134. const passedStoreName = options.storeName ? decodeURIComponent(options.storeName) : '';
  135. const passedStoreId = options.storeId || '';
  136. if (passedStoreName) {
  137. this.setNavigationTitle(passedStoreName);
  138. }
  139. // 异步加载完整店铺信息(作为备份)
  140. this.loadAndSetStoreTitle(passedStoreId, passedStoreName);
  141. // 启动标题轮询监听
  142. this.startTitlePolling();
  143. },
  144. /**
  145. * 检查用户登录状态
  146. * @returns {Promise<boolean>} true: 已登录且有手机号,false: 需要登录
  147. */
  148. checkUserLogin: async function(options) {
  149. try {
  150. console.log('===========================================');
  151. console.log('🔍 开始检查用户登录状态...');
  152. // 检查是否有 skipAuth 参数(用于跳过登录检查)
  153. if (options.skipAuth === 'true') {
  154. console.log('ℹ️ 检测到 skipAuth 参数,跳过登录检查');
  155. console.log('===========================================');
  156. return true;
  157. }
  158. // 1. 先调用 checkAuth 初始化用户(不强制授权)
  159. console.log('📱 调用 checkAuth 初始化用户...');
  160. try {
  161. await getApp().checkAuth(false); // false = 不强制授权,只是初始化
  162. console.log('✅ checkAuth 调用成功');
  163. } catch (err) {
  164. console.warn('⚠️ checkAuth 调用失败(可能是游客模式):', err);
  165. }
  166. // 2. 检查用户状态
  167. const currentUser = Parse.User.current();
  168. const hasMobile = currentUser?.get('mobile');
  169. const userLogin = wx.getStorageSync('userLogin');
  170. console.log('📊 用户状态:');
  171. console.log(' - 当前用户:', currentUser ? currentUser.id : '无');
  172. console.log(' - 手机号:', hasMobile || '无');
  173. console.log(' - userLogin 存储:', userLogin || '无');
  174. // 只有同时满足以下条件才认为已完整登录:
  175. // 1. Parse.User.current() 存在
  176. // 2. 用户有手机号
  177. // 3. userLogin 存储存在
  178. if (currentUser && hasMobile && userLogin) {
  179. console.log('✅ 用户已完整登录');
  180. console.log('===========================================');
  181. return true;
  182. }
  183. // 用户未登录或没有手机号,跳转到授权页面
  184. console.log('⚠️ 用户未完整登录,准备跳转到授权页面');
  185. // 构建返回 URL(登录成功后返回当前页面)
  186. const currentPath = options.path || '';
  187. const returnUrl = currentPath;
  188. const storeId = options.storeId ? String(options.storeId) : '';
  189. const storeName = options.storeName ? String(options.storeName) : '';
  190. console.log('🔗 returnUrl:', returnUrl);
  191. console.log('===========================================');
  192. wx.setStorageSync('post_auth_modal', {
  193. title: '授权成功',
  194. content: '已完成授权,正在为你打开分享内容。'
  195. });
  196. // 跳转到授权页面,并传递 returnUrl
  197. let authPageUrl = `/components/app-auth/index?returnUrl=${returnUrl}`;
  198. if (storeId) {
  199. authPageUrl += `&storeId=${storeId}`;
  200. }
  201. if (storeName) {
  202. authPageUrl += `&storeName=${storeName}`;
  203. }
  204. wx.redirectTo({
  205. url: authPageUrl,
  206. success: () => {
  207. console.log('✅ redirectTo 到授权页面成功');
  208. },
  209. fail: (err) => {
  210. console.error('❌ redirectTo 失败:', err);
  211. // 降级:使用 navigateTo
  212. wx.navigateTo({
  213. url: authPageUrl,
  214. success: () => {
  215. console.log('✅ navigateTo 到授权页面成功');
  216. },
  217. fail: (err2) => {
  218. console.error('❌ navigateTo 也失败:', err2);
  219. // 最后降级:使用 reLaunch
  220. wx.reLaunch({
  221. url: authPageUrl,
  222. success: () => {
  223. console.log('✅ reLaunch 到授权页面成功');
  224. },
  225. fail: (err3) => {
  226. console.error('❌ 所有跳转方式都失败:', err3);
  227. }
  228. });
  229. }
  230. });
  231. }
  232. });
  233. return false;
  234. } catch (err) {
  235. console.error('❌ 检查登录状态失败:', err);
  236. console.log('===========================================');
  237. // 出错时也跳转到授权页面
  238. const returnUrl = options.path || '';
  239. wx.setStorageSync('post_auth_modal', {
  240. title: '授权成功',
  241. content: '已完成授权,正在为你打开分享内容。'
  242. });
  243. wx.redirectTo({
  244. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  245. fail: () => {
  246. wx.navigateTo({
  247. url: `/components/app-auth/index?returnUrl=${returnUrl}`
  248. });
  249. }
  250. });
  251. return false;
  252. }
  253. },
  254. onReady: function () {
  255. },
  256. onShow: function () {
  257. this.startTitlePolling();
  258. },
  259. onHide: function () {
  260. this.stopTitlePolling();
  261. },
  262. onUnload: function () {
  263. this.stopTitlePolling();
  264. },
  265. /**
  266. * 页面相关事件处理函数--监听用户下拉动作
  267. */
  268. onPullDownRefresh: function () {
  269. },
  270. /**
  271. * 页面上拉触底事件的处理函数
  272. */
  273. onReachBottom: function () {
  274. },
  275. /**
  276. * 用户点击右上角分享
  277. */
  278. onShareAppMessage: function () {
  279. },
  280. /**
  281. * 处理来自 H5 页面的消息
  282. */
  283. handleMessage: function (e) {
  284. try {
  285. const messages = e.detail.data || [];
  286. // 找到最后一个标题更新消息
  287. let lastTitleMessage = null;
  288. for (let i = messages.length - 1; i >= 0; i--) {
  289. const msg = messages[i];
  290. if (msg.type === 'updateTitle' && msg.title) {
  291. lastTitleMessage = msg;
  292. break;
  293. }
  294. }
  295. // 更新标题
  296. if (lastTitleMessage) {
  297. this.setNavigationTitle(lastTitleMessage.title);
  298. }
  299. } catch (error) {
  300. console.error('❌ 处理消息失败:', error);
  301. }
  302. },
  303. /**
  304. * 设置导航栏标题(统一方法)
  305. */
  306. setNavigationTitle: function (title) {
  307. if (!title) {
  308. return;
  309. }
  310. // 若与当前标题一致则跳过,避免频繁触发
  311. if (title === this.data.currentTitle) {
  312. return;
  313. }
  314. // 简单节流:500ms 内重复更新跳过
  315. if (!this._lastTitleUpdateTs) {
  316. this._lastTitleUpdateTs = 0;
  317. }
  318. const now = Date.now();
  319. if (now - this._lastTitleUpdateTs < 500) {
  320. return;
  321. }
  322. this._lastTitleUpdateTs = now;
  323. // 更新当前标题记录
  324. this.setData({
  325. currentTitle: title
  326. });
  327. // 延迟调用微信 API 设置标题,确保页面已准备好
  328. setTimeout(() => {
  329. wx.setNavigationBarTitle({
  330. title: title,
  331. success: () => {
  332. console.log('✅ web-view 标题设置成功:', title);
  333. },
  334. fail: (err) => {
  335. console.warn('⚠️ web-view 标题设置失败(可忽略):', err.errMsg);
  336. // 不影响主流程,静默失败
  337. }
  338. });
  339. }, 100);
  340. },
  341. startTitlePolling: function () {
  342. this.stopTitlePolling();
  343. },
  344. stopTitlePolling: function () {
  345. if (this.titlePollingTimer) {
  346. clearInterval(this.titlePollingTimer);
  347. this.titlePollingTimer = null;
  348. }
  349. },
  350. /**
  351. * 加载店铺信息并设置页面标题
  352. */
  353. loadAndSetStoreTitle: async function (storeId = '', storeName = '') {
  354. try {
  355. let finalTitle = storeName;
  356. if (!finalTitle) {
  357. // 如果没有传入名字,按传入的 storeId 精确查询;再不行按 company 兜底
  358. if (storeId) {
  359. const q = new Parse.Query('ShopStore');
  360. const s = await q.get(storeId);
  361. if (s) {
  362. // 优先使用门店地址,如果没有地址则使用门店名称
  363. const address = s.get('address');
  364. const name = s.get('storeName');
  365. finalTitle = address || name || '';
  366. console.log('📍 web-view 门店信息:', {
  367. id: storeId,
  368. name: name,
  369. address: address,
  370. displayTitle: finalTitle
  371. });
  372. }
  373. }
  374. if (!finalTitle) {
  375. const storeQuery = new Parse.Query('ShopStore');
  376. storeQuery.equalTo('company', company);
  377. storeQuery.ascending('score');
  378. storeQuery.limit(1);
  379. const store = await storeQuery.first();
  380. if (store) {
  381. // 优先使用门店地址,如果没有地址则使用门店名称
  382. const address = store.get('address');
  383. const name = store.get('storeName');
  384. finalTitle = address || name || '';
  385. }
  386. }
  387. }
  388. if (!finalTitle) return;
  389. // 使用统一的设置标题方法
  390. this.setNavigationTitle(finalTitle);
  391. } catch (e) {
  392. console.error('设置 web-view 标题失败:', e);
  393. }
  394. }
  395. })