index.js 14 KB

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