index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. // 2. 解码 URL
  29. let path = decodeURIComponent(options.path || '');
  30. console.log('原始 options.path:', options.path);
  31. console.log('解码后的 path:', path);
  32. // 拼接额外参数(避免重复添加已存在的参数)
  33. let hasQuery = path.indexOf('?') !== -1;
  34. let parsm = hasQuery ? '&' : '?';
  35. let params = [];
  36. // 提取 path 中已有的参数
  37. let existingParams = new Set();
  38. if (hasQuery) {
  39. const queryString = path.split('?')[1];
  40. if (queryString) {
  41. queryString.split('&').forEach(param => {
  42. const key = param.split('=')[0];
  43. existingParams.add(key);
  44. });
  45. }
  46. }
  47. // 只添加 path 中不存在的参数
  48. for (const key in options) {
  49. if(key != 'path' && key != 'url' && !existingParams.has(key)){
  50. params.push(key + '=' + options[key]);
  51. }
  52. }
  53. if(params.length > 0) {
  54. parsm = parsm + params.join('&');
  55. path = path + parsm;
  56. }
  57. console.log('最终 web-view URL:', path);
  58. console.log('URL 长度:', path.length);
  59. console.log('===========================================');
  60. this.setData({
  61. path: path
  62. })
  63. // 立即设置标题
  64. const passedStoreName = options.storeName ? decodeURIComponent(options.storeName) : '';
  65. const passedStoreId = options.storeId || '';
  66. if (passedStoreName) {
  67. this.setNavigationTitle(passedStoreName);
  68. }
  69. // 异步加载完整店铺信息(作为备份)
  70. this.loadAndSetStoreTitle(passedStoreId, passedStoreName);
  71. // 启动标题轮询监听
  72. this.startTitlePolling();
  73. },
  74. /**
  75. * 检查用户登录状态
  76. * @returns {Promise<boolean>} true: 已登录且有手机号,false: 需要登录
  77. */
  78. checkUserLogin: async function(options) {
  79. try {
  80. console.log('===========================================');
  81. console.log('🔍 开始检查用户登录状态...');
  82. // 检查是否有 skipAuth 参数(用于跳过登录检查)
  83. if (options.skipAuth === 'true') {
  84. console.log('ℹ️ 检测到 skipAuth 参数,跳过登录检查');
  85. console.log('===========================================');
  86. return true;
  87. }
  88. // 1. 先调用 checkAuth 初始化用户(不强制授权)
  89. console.log('📱 调用 checkAuth 初始化用户...');
  90. try {
  91. await getApp().checkAuth(false); // false = 不强制授权,只是初始化
  92. console.log('✅ checkAuth 调用成功');
  93. } catch (err) {
  94. console.warn('⚠️ checkAuth 调用失败(可能是游客模式):', err);
  95. }
  96. // 2. 检查用户状态
  97. const currentUser = Parse.User.current();
  98. const hasMobile = currentUser?.get('mobile');
  99. const userLogin = wx.getStorageSync('userLogin');
  100. console.log('📊 用户状态:');
  101. console.log(' - 当前用户:', currentUser ? currentUser.id : '无');
  102. console.log(' - 手机号:', hasMobile || '无');
  103. console.log(' - userLogin 存储:', userLogin || '无');
  104. // 只有同时满足以下条件才认为已完整登录:
  105. // 1. Parse.User.current() 存在
  106. // 2. 用户有手机号
  107. // 3. userLogin 存储存在
  108. if (currentUser && hasMobile && userLogin) {
  109. console.log('✅ 用户已完整登录');
  110. console.log('===========================================');
  111. return true;
  112. }
  113. // 用户未登录或没有手机号,跳转到授权页面
  114. console.log('⚠️ 用户未完整登录,准备跳转到授权页面');
  115. // 构建返回 URL(登录成功后返回当前页面)
  116. const currentPath = options.path || '';
  117. const returnUrl = encodeURIComponent(currentPath);
  118. console.log('🔗 returnUrl:', returnUrl);
  119. console.log('===========================================');
  120. // 跳转到授权页面,并传递 returnUrl
  121. wx.redirectTo({
  122. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  123. success: () => {
  124. console.log('✅ redirectTo 到授权页面成功');
  125. },
  126. fail: (err) => {
  127. console.error('❌ redirectTo 失败:', err);
  128. // 降级:使用 navigateTo
  129. wx.navigateTo({
  130. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  131. success: () => {
  132. console.log('✅ navigateTo 到授权页面成功');
  133. },
  134. fail: (err2) => {
  135. console.error('❌ navigateTo 也失败:', err2);
  136. // 最后降级:使用 reLaunch
  137. wx.reLaunch({
  138. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  139. success: () => {
  140. console.log('✅ reLaunch 到授权页面成功');
  141. },
  142. fail: (err3) => {
  143. console.error('❌ 所有跳转方式都失败:', err3);
  144. }
  145. });
  146. }
  147. });
  148. }
  149. });
  150. return false;
  151. } catch (err) {
  152. console.error('❌ 检查登录状态失败:', err);
  153. console.log('===========================================');
  154. // 出错时也跳转到授权页面
  155. const returnUrl = options.path ? encodeURIComponent(options.path) : '';
  156. wx.redirectTo({
  157. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  158. fail: () => {
  159. wx.navigateTo({
  160. url: `/components/app-auth/index?returnUrl=${returnUrl}`
  161. });
  162. }
  163. });
  164. return false;
  165. }
  166. },
  167. onReady: function () {
  168. },
  169. onShow: function () {
  170. this.startTitlePolling();
  171. },
  172. onHide: function () {
  173. this.stopTitlePolling();
  174. },
  175. onUnload: function () {
  176. this.stopTitlePolling();
  177. },
  178. /**
  179. * 页面相关事件处理函数--监听用户下拉动作
  180. */
  181. onPullDownRefresh: function () {
  182. },
  183. /**
  184. * 页面上拉触底事件的处理函数
  185. */
  186. onReachBottom: function () {
  187. },
  188. /**
  189. * 用户点击右上角分享
  190. */
  191. onShareAppMessage: function () {
  192. },
  193. /**
  194. * 处理来自 H5 页面的消息
  195. */
  196. handleMessage: function (e) {
  197. try {
  198. const messages = e.detail.data || [];
  199. // 找到最后一个标题更新消息
  200. let lastTitleMessage = null;
  201. for (let i = messages.length - 1; i >= 0; i--) {
  202. const msg = messages[i];
  203. if (msg.type === 'updateTitle' && msg.title) {
  204. lastTitleMessage = msg;
  205. break;
  206. }
  207. }
  208. // 更新标题
  209. if (lastTitleMessage) {
  210. this.setNavigationTitle(lastTitleMessage.title);
  211. }
  212. } catch (error) {
  213. console.error('❌ 处理消息失败:', error);
  214. }
  215. },
  216. /**
  217. * 设置导航栏标题(统一方法)
  218. */
  219. setNavigationTitle: function (title) {
  220. if (!title) {
  221. return;
  222. }
  223. // 若与当前标题一致则跳过,避免频繁触发
  224. if (title === this.data.currentTitle) {
  225. return;
  226. }
  227. // 简单节流:500ms 内重复更新跳过
  228. if (!this._lastTitleUpdateTs) {
  229. this._lastTitleUpdateTs = 0;
  230. }
  231. const now = Date.now();
  232. if (now - this._lastTitleUpdateTs < 500) {
  233. return;
  234. }
  235. this._lastTitleUpdateTs = now;
  236. // 更新当前标题记录
  237. this.setData({
  238. currentTitle: title
  239. });
  240. // 延迟调用微信 API 设置标题,确保页面已准备好
  241. setTimeout(() => {
  242. wx.setNavigationBarTitle({
  243. title: title,
  244. success: () => {
  245. console.log('✅ web-view 标题设置成功:', title);
  246. },
  247. fail: (err) => {
  248. console.warn('⚠️ web-view 标题设置失败(可忽略):', err.errMsg);
  249. // 不影响主流程,静默失败
  250. }
  251. });
  252. }, 100);
  253. },
  254. startTitlePolling: function () {
  255. this.stopTitlePolling();
  256. },
  257. stopTitlePolling: function () {
  258. if (this.titlePollingTimer) {
  259. clearInterval(this.titlePollingTimer);
  260. this.titlePollingTimer = null;
  261. }
  262. },
  263. /**
  264. * 加载店铺信息并设置页面标题
  265. */
  266. loadAndSetStoreTitle: async function (storeId = '', storeName = '') {
  267. try {
  268. let finalTitle = storeName;
  269. if (!finalTitle) {
  270. // 如果没有传入名字,按传入的 storeId 精确查询;再不行按 company 兜底
  271. if (storeId) {
  272. const q = new Parse.Query('ShopStore');
  273. const s = await q.get(storeId);
  274. if (s) {
  275. // 优先使用门店地址,如果没有地址则使用门店名称
  276. const address = s.get('address');
  277. const name = s.get('storeName');
  278. finalTitle = address || name || '';
  279. console.log('📍 web-view 门店信息:', {
  280. id: storeId,
  281. name: name,
  282. address: address,
  283. displayTitle: finalTitle
  284. });
  285. }
  286. }
  287. if (!finalTitle) {
  288. const storeQuery = new Parse.Query('ShopStore');
  289. storeQuery.equalTo('company', company);
  290. storeQuery.ascending('score');
  291. storeQuery.limit(1);
  292. const store = await storeQuery.first();
  293. if (store) {
  294. // 优先使用门店地址,如果没有地址则使用门店名称
  295. const address = store.get('address');
  296. const name = store.get('storeName');
  297. finalTitle = address || name || '';
  298. }
  299. }
  300. }
  301. if (!finalTitle) return;
  302. // 使用统一的设置标题方法
  303. this.setNavigationTitle(finalTitle);
  304. } catch (e) {
  305. console.error('设置 web-view 标题失败:', e);
  306. }
  307. }
  308. })