index.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. const { readTarget } = require('../../utils/web-view-target');
  2. let Parse = getApp().Parse;
  3. let company = getApp().globalData.company
  4. const request = require("../../utils/request");
  5. const qiniuUploader = require("../../utils/qiniuUploader");
  6. //获取应用实例
  7. const app = getApp()
  8. const real = require('../../utils/real')
  9. var timer
  10. /**
  11. * @class NovaAppAuth
  12. * @memberof module:components
  13. * @tutorial userauth
  14. * @desc 通用登录组件
  15. * # 登录组件相关数据表
  16. * - _User
  17. */
  18. Page({
  19. data: {
  20. phoneModal: false, //短信验证码登录弹窗
  21. logo: "https://file-cloud.fmode.cn/MldI5PBNt7/20210928/g0k1jb034826.png",
  22. name: "未来商城",
  23. desc: "江西脑控科技有限公司是国内领先的IT技术企业。专注于互联网+服务,面向政府提供区块链、大数据、物联网、人工智能解决方案",
  24. wxModel: false,
  25. avatarUrl: '',
  26. avatar: '',
  27. nickname: '',
  28. check: false,
  29. mobile: '', //手机号
  30. verilyCode: '', //验证码
  31. s: 0, //获取验证码倒计时 秒/s
  32. countDown: false,
  33. avatarKey: Date.now(), // 用于强制刷新头像显示
  34. isProcessingAuth: false, // 标记是否正在处理授权流程
  35. },
  36. onLoad: async function (options) {
  37. let Company = new Parse.Query('Company')
  38. Company.equalTo("objectId", company)
  39. let currentCompany = await Company.first()
  40. if (currentCompany && currentCompany.id) {
  41. this.setData({
  42. logo: currentCompany.get('logo'),
  43. name: currentCompany.get('name'),
  44. desc: currentCompany.get('desc')
  45. })
  46. }
  47. this.getUptoken()
  48. this.getAgreement() //用户协议
  49. },
  50. async getUptoken() {
  51. let res = await Parse.Cloud.run('qiniu_uptoken', {
  52. company: company
  53. })
  54. this.setData({
  55. uptokenURL: res.uptoken,
  56. domain: res.domain,
  57. uploadURL: res.zoneUrl
  58. })
  59. },
  60. async getAgreement() {
  61. let query = new Parse.Query('ContractAgreement')
  62. query.equalTo('type', 'wxapp')
  63. query.equalTo('company', company)
  64. query.select('title', 'content')
  65. let res = await query.first()
  66. if (res?.id) {
  67. this.setData({
  68. agreement: res.toJSON()
  69. })
  70. }
  71. },
  72. /* 是否同意授权协议 */
  73. getAgreementAuth() {
  74. if (!this.data.check && this.data.agreement) {
  75. wx.showModal({
  76. title: '提示',
  77. content: `请您仔细阅读并充分理解相关条款,点击同意即代表已阅读并同意《${this.data.agreement.title || '用户隐私协议'}》`,
  78. showCancel: true,
  79. cancelText: '取消',
  80. cancelColor: '#000000',
  81. confirmText: '同意',
  82. confirmColor: '#3CC51F',
  83. success: (result) => {
  84. if (result.confirm) {
  85. this.setData({
  86. check: true,
  87. })
  88. // this.getUserProfile()
  89. }
  90. },
  91. fail: () => { },
  92. complete: () => { }
  93. });
  94. return
  95. }
  96. // this.getUserProfile()
  97. return true
  98. },
  99. /* 判断是否绑定手机号 */
  100. async getUserProfile() {
  101. // 检查用户是否已登录
  102. let currentUser = Parse.User.current();
  103. if (!currentUser?.id) {
  104. console.log('⚠️ 用户未登录,需要先登录');
  105. // 不要在这里调用 checkAuth(true),因为它会触发微信官方的强制授权弹窗
  106. // 应该在外层(index.js)处理登录逻辑
  107. return false;
  108. }
  109. /* 如果手机号存在,已注册过判断是否上传过头像昵称信息 */
  110. if (currentUser?.get('mobile')) {
  111. wx.setStorageSync("userLogin", currentUser.id);
  112. // 检查是否需要完善信息(可选)
  113. // 如果用户没有昵称或昵称是默认的,提示完善信息
  114. const needProfile = !currentUser.get('nickname') ||
  115. currentUser.get('nickname') === '微信用户' ||
  116. currentUser.get('nickname') === '';
  117. if (needProfile) {
  118. // 显示自定义的完善信息弹窗(允许跳过)
  119. console.log('ℹ️ 显示自定义头像昵称弹窗');
  120. this.setData({
  121. wxModel: true
  122. });
  123. return false;
  124. }
  125. // 用户信息完整,返回上一页
  126. this.backLoad();
  127. return false;
  128. }
  129. // 用户已登录但没有手机号,允许继续
  130. return true;
  131. },
  132. /* 短信验证码登录弹窗 */
  133. async showDialogBtn() {
  134. let auth = this.getAgreementAuth()
  135. if (!auth) return
  136. let userProfile = await this.getUserProfile()
  137. if (!userProfile) return
  138. // 标记正在处理授权
  139. this.setData({
  140. isProcessingAuth: true,
  141. phoneModal: true
  142. })
  143. },
  144. async getPhoneNumber(e) {
  145. let auth = this.getAgreementAuth()
  146. if (!auth) return
  147. let userProfile = await this.getUserProfile()
  148. if (!userProfile) return
  149. // 标记正在处理授权
  150. this.setData({
  151. isProcessingAuth: true
  152. })
  153. let {
  154. code
  155. } = e.detail
  156. console.log(code);
  157. let phoneNumber = await request.getPhone(code)
  158. if(phoneNumber) this.authMobileUser(phoneNumber)
  159. },
  160. //合并User与绑定手机号逻辑
  161. async authMobileUser(mobile) {
  162. let currentUser = Parse.User.current()
  163. let queryMobUser = new Parse.Query('_User')
  164. queryMobUser.equalTo('mobile', mobile)
  165. queryMobUser.equalTo('company', company)
  166. queryMobUser.notEqualTo('type', 'admin')
  167. queryMobUser.notEqualTo('isDeleted', true)
  168. // queryMobUser.exists(`wxapp.${getApp().globalData.appid}`)
  169. let resMobUser = await queryMobUser.first()
  170. if (resMobUser?.id) {
  171. //请求User合并API,获取token重新登录,再更新昵称头像信息等
  172. let token = await this.getUpdateUserToken(currentUser.id, resMobUser.id)
  173. console.log(token);
  174. if (token) {
  175. Parse.User.become(token).then(async user => {
  176. // let user = Parse.User.current();
  177. wx.setStorageSync("userLogin", user.id);
  178. if (!user.get('avatar') || user.get('nickname') == '微信用户' || !user.get('nickname')) {
  179. this.setData({
  180. phoneModal: false,
  181. wxModel: true
  182. })
  183. return
  184. }
  185. this.backLoad()
  186. return
  187. })
  188. .catch(async err => {
  189. console.log('❌ Parse.User.become 失败:', err);
  190. // 不要直接退出,而是尝试重新登录
  191. wx.showModal({
  192. title: '提示',
  193. content: '登录状态异常,是否重新登录?',
  194. showCancel: true,
  195. cancelText: '取消',
  196. confirmText: '重新登录',
  197. success: async (result) => {
  198. if (result.confirm) {
  199. // 清除登录状态
  200. wx.removeStorageSync("sessionToken");
  201. wx.removeStorageSync("userLogin");
  202. try {
  203. // 尝试重新登录
  204. await Parse.User.logOut();
  205. await getApp().checkAuth(true);
  206. // 重新获取用户信息
  207. const currentUser = Parse.User.current();
  208. if (currentUser && currentUser.get('mobile')) {
  209. wx.setStorageSync("userLogin", currentUser.id);
  210. this.backLoad();
  211. }
  212. } catch (reloginErr) {
  213. console.error('❌ 重新登录失败:', reloginErr);
  214. wx.showToast({
  215. title: '登录失败,请稍后重试',
  216. icon: 'none'
  217. });
  218. }
  219. } else {
  220. // 用户取消,返回上一页
  221. wx.navigateBack();
  222. }
  223. },
  224. });
  225. return
  226. })
  227. return
  228. }
  229. return
  230. }
  231. currentUser.set('mobile', mobile)
  232. await currentUser.save()
  233. if (!currentUser.get('avatar') || currentUser.get('nickname') == '微信用户' || !currentUser.get('nickname')) {
  234. this.setData({
  235. phoneModal: false,
  236. wxModel: true
  237. })
  238. return
  239. }
  240. this.backLoad()
  241. return
  242. },
  243. async getUpdateUserToken(oldUser, newUserId) {
  244. return new Promise((resolve, reject) => {
  245. wx.login({
  246. success: function (res) {
  247. let parms = {
  248. oldUserId: oldUser,
  249. newUserId: newUserId,
  250. appId: getApp().globalData.appid,
  251. code: res.code,
  252. companyId: company,
  253. appType: getApp().globalData.appType || ''
  254. }
  255. if (res.code) {
  256. let url = 'https://server.fmode.cn/api/wxapp/combine/user'
  257. wx.request({
  258. url: url,
  259. data: parms,
  260. header: { 'content-type': 'application/json' },
  261. method: 'POST',
  262. async success(res) {
  263. console.log(res);
  264. let data = res.data
  265. if (data.code == 200) {
  266. wx.setStorageSync("sessionToken", data.data.token);
  267. // 用户合并成功后,更新 ScanRecord 表中的 user 字段
  268. console.log('🔄 [用户合并] 开始更新 ScanRecord 中的用户关联');
  269. console.log(' - 旧用户ID:', oldUser);
  270. console.log(' - 新用户ID:', newUserId);
  271. try {
  272. // 使用 Parse.User.become 切换到新用户
  273. await Parse.User.become(data.data.token);
  274. // 查询所有旧用户的扫码记录
  275. const ScanRecord = Parse.Object.extend('ScanRecord');
  276. const scanQuery = new Parse.Query(ScanRecord);
  277. scanQuery.equalTo('user', {
  278. __type: 'Pointer',
  279. className: '_User',
  280. objectId: oldUser
  281. });
  282. scanQuery.limit(1000); // 设置查询上限
  283. const oldRecords = await scanQuery.find();
  284. console.log(`📋 [查询结果] 找到 ${oldRecords.length} 条旧用户的扫码记录`);
  285. if (oldRecords.length > 0) {
  286. // 批量更新所有记录,将 user 指向新用户
  287. const updatePromises = oldRecords.map(record => {
  288. record.set('user', {
  289. __type: 'Pointer',
  290. className: '_User',
  291. objectId: newUserId
  292. });
  293. return record.save();
  294. });
  295. await Promise.all(updatePromises);
  296. console.log(`✅ [更新成功] 已将 ${oldRecords.length} 条扫码记录的用户更新为新用户`);
  297. } else {
  298. console.log('ℹ️ [无需更新] 旧用户没有扫码记录');
  299. }
  300. } catch (updateError) {
  301. console.error('❌ [更新失败] 更新 ScanRecord 失败:', updateError);
  302. console.error(' - 错误信息:', updateError.message);
  303. // 不影响主流程,继续返回 token
  304. }
  305. resolve(data.data.token)
  306. } else {
  307. console.log(data?.mess);
  308. wx.showModal({
  309. title: '提示',
  310. content: data?.mess,
  311. showCancel: false,
  312. cancelText: '取消',
  313. cancelColor: '#000000',
  314. confirmText: '确定',
  315. confirmColor: '#3CC51F',
  316. success: (result) => {
  317. if (result.confirm) {
  318. }
  319. },
  320. fail: () => { },
  321. complete: () => { }
  322. });
  323. resolve()
  324. }
  325. },
  326. });
  327. }
  328. },
  329. fail: function (err) {
  330. wx.showModal({
  331. title: '提示',
  332. content: '登录超时,请稍后重试',
  333. showCancel: false,
  334. cancelText: '取消',
  335. cancelColor: '#000000',
  336. confirmText: '确定',
  337. confirmColor: '#3CC51F',
  338. success: (result) => {
  339. if (result.confirm) {
  340. }
  341. },
  342. fail: () => { },
  343. complete: () => { }
  344. });
  345. console.warn('小程序wx.login失败');
  346. resolve()
  347. }
  348. });
  349. })
  350. },
  351. //获取验证码
  352. async getPhoneCode() {
  353. let { mobile, s, countDown } = this.data
  354. if (!real.isPoneAvailable(mobile)) {
  355. wx.showToast({
  356. title: '手机号格式有误',
  357. icon: 'error',
  358. duration: 1500,
  359. mask: false,
  360. });
  361. return
  362. }
  363. if(countDown || s > 0) return
  364. this.setData({
  365. countDown:true
  366. })
  367. let parsm = {
  368. company: company,
  369. mobile: mobile
  370. }
  371. let code = await this.getRequest(parsm, 'message')
  372. if(code?.code == 1){
  373. this.setData({
  374. s:60
  375. })
  376. this.decrementTime()
  377. }else{
  378. wx.showToast({
  379. title: '验证码获取失败',
  380. icon: 'error',
  381. image: '',
  382. duration: 1500,
  383. mask: false,
  384. });
  385. this.setData({
  386. countDown:false
  387. })
  388. }
  389. },
  390. //接口请求
  391. getRequest(parsm, apig) {
  392. return new Promise((resolve, rej) => {
  393. let url = 'https://server.fmode.cn/api/apig/'
  394. wx.request({
  395. url: url + apig,
  396. data: parsm,
  397. header: { 'content-type': 'application/json' },
  398. method: 'POST',
  399. dataType: 'json',
  400. responseType: 'text',
  401. success: (result) => {
  402. console.log(result);
  403. resolve(result.data)
  404. },
  405. fail: () => {
  406. resolve(false)
  407. },
  408. complete: () => { }
  409. });
  410. })
  411. },
  412. // 倒计时
  413. decrementTime(){
  414. timer = setTimeout(() => {
  415. let { s } = this.data
  416. if(s == 0){
  417. this.setData({ countDown:false })
  418. timer && clearTimeout(timer)
  419. return
  420. }
  421. s--
  422. this.setData({
  423. s:s
  424. })
  425. this.decrementTime()
  426. }, 1000);
  427. },
  428. //验证码绑定手机号登录
  429. async completePhone() {
  430. let { mobile, verilyCode } = this.data
  431. if(!real.isPoneAvailable(mobile) || !verilyCode.toString().trim()){
  432. wx.showToast({
  433. title: '手机号或验证码不正确',
  434. icon: 'none',
  435. image: '',
  436. duration: 1500,
  437. mask: false,
  438. });
  439. return
  440. }
  441. // 标记正在处理授权
  442. this.setData({
  443. isProcessingAuth: true
  444. })
  445. let parsm = {
  446. mobile: mobile,
  447. code:verilyCode
  448. }
  449. let isVerify = await this.getRequest(parsm, 'verifyCode')
  450. console.log(isVerify);
  451. if(isVerify.code == 200){
  452. this.authMobileUser(mobile.toString())
  453. }else{
  454. // 验证失败,重置标记
  455. this.setData({
  456. isProcessingAuth: false
  457. })
  458. wx.showToast({
  459. title:isVerify?.msg || '验证码错误',
  460. icon: 'none',
  461. image: '',
  462. duration: 1500,
  463. mask: false,
  464. });
  465. return
  466. }
  467. },
  468. //关闭手机号授权弹窗
  469. hideModal: function () {
  470. this.setData({
  471. phoneModal: false,
  472. isProcessingAuth: false // 重置标记
  473. })
  474. },
  475. backLoad() {
  476. console.log('===========================================');
  477. console.log('======= backLoad 方法调用 =======');
  478. let pages = getCurrentPages();
  479. console.log('当前页面栈层数:', pages.length);
  480. console.log('当前页面路由:', pages[pages.length - 1]?.route);
  481. // 检查是否有 returnUrl 参数(从 H5 页面传递过来)
  482. const currentPage = pages[pages.length - 1];
  483. const target = readTarget(currentPage?.options?.returnUrl);
  484. if (target) {
  485. wx.redirectTo({
  486. url: '/common-page/pages/web-view/index?path=' + encodeURIComponent(target),
  487. fail: () => this.normalBackLoad(),
  488. });
  489. return;
  490. }
  491. // 没有 returnUrl,执行正常的返回逻辑
  492. this.normalBackLoad();
  493. },
  494. normalBackLoad() {
  495. let pages = getCurrentPages();
  496. // 如果页面栈只有1层或没有上一页,直接跳转到首页
  497. if (pages.length <= 1) {
  498. console.log('⚠️ 没有上一个页面,直接跳转到首页');
  499. this.goToHome();
  500. return;
  501. }
  502. // 有上一个页面
  503. let beforePage = pages[pages.length - 2];
  504. console.log('上一个页面路由:', beforePage.route);
  505. // 尝试调用上一个页面的 onLoad 方法(如果存在)
  506. if (beforePage && typeof beforePage.onLoad === 'function') {
  507. try {
  508. let options = beforePage.options || { isInit: true };
  509. beforePage.onLoad(options);
  510. console.log('✅ 已调用上一个页面的 onLoad');
  511. } catch (err) {
  512. console.warn('⚠️ 调用上一个页面 onLoad 失败:', err);
  513. }
  514. }
  515. // 返回上一页
  516. console.log('🔙 执行 navigateBack...');
  517. wx.navigateBack({
  518. delta: 1,
  519. success: () => {
  520. console.log('✅ navigateBack 成功');
  521. console.log('===========================================');
  522. },
  523. fail: (err) => {
  524. console.error('❌ navigateBack 失败:', err);
  525. console.log('⚠️ 尝试使用 reLaunch 跳转到首页');
  526. this.goToHome();
  527. }
  528. });
  529. },
  530. // 跳转到首页
  531. goToHome() {
  532. console.log('===========================================');
  533. console.log('======= goToHome 方法调用 =======');
  534. const app = getApp();
  535. console.log('globalData.rootPage:', app.globalData.rootPage);
  536. console.log('globalData.defaultTabBar:', app.globalData.defaultTabBar);
  537. // 尝试多个可能的首页路径
  538. let rootPage = app.globalData.rootPage
  539. || app.globalData.defaultTabBar?.list?.[0]?.pagePath
  540. || '/pages/index/index'
  541. || '/index/index';
  542. // 确保路径以 / 开头
  543. if (!rootPage.startsWith('/')) {
  544. rootPage = '/' + rootPage;
  545. }
  546. console.log('准备跳转到:', rootPage);
  547. wx.reLaunch({
  548. url: rootPage,
  549. success: () => {
  550. console.log('✅ reLaunch 成功');
  551. console.log('===========================================');
  552. },
  553. fail: (err) => {
  554. console.error('❌ reLaunch 失败:', err);
  555. console.log('⚠️ 尝试使用 switchTab');
  556. // 如果是 tabBar 页面,尝试使用 switchTab
  557. wx.switchTab({
  558. url: rootPage,
  559. success: () => {
  560. console.log('✅ switchTab 成功');
  561. console.log('===========================================');
  562. },
  563. fail: (err2) => {
  564. console.error('❌ switchTab 也失败:', err2);
  565. console.log('⚠️ 最后尝试:直接 navigateBack');
  566. // 最后的兜底:直接返回
  567. wx.navigateBack({
  568. delta: 1,
  569. fail: (err3) => {
  570. console.error('❌ 所有跳转方式都失败了:', err3);
  571. console.log('===========================================');
  572. // 显示错误提示
  573. wx.showModal({
  574. title: '提示',
  575. content: '页面跳转失败,请手动返回',
  576. showCancel: false
  577. });
  578. }
  579. });
  580. }
  581. });
  582. }
  583. });
  584. },
  585. goBack: function () {
  586. wx.navigateBack({
  587. delta: 1,
  588. })
  589. },
  590. //手动获取微信头像
  591. onChooseAvatar(e) {
  592. console.log('=== onChooseAvatar 触发 ===');
  593. console.log('事件对象:', e);
  594. const { avatarUrl } = e.detail;
  595. console.log('获取到的头像URL:', avatarUrl);
  596. console.log('头像URL类型:', typeof avatarUrl);
  597. console.log('头像URL长度:', avatarUrl ? avatarUrl.length : 0);
  598. if (avatarUrl) {
  599. // 微信头像URL可能是临时路径,需要先下载
  600. // 临时路径格式:http://tmp/xxx.jpg
  601. // 相机拍照路径格式:wxfile://tmp_xxx.jpg
  602. this.setData({
  603. avatarUrl: avatarUrl,
  604. avatarKey: Date.now() // 更新key强制刷新
  605. }, () => {
  606. console.log('✅ 头像URL已更新到data:', this.data.avatarUrl);
  607. console.log('✅ avatarKey已更新:', this.data.avatarKey);
  608. });
  609. } else {
  610. console.error('❌ 未获取到头像URL');
  611. // 在开发环境下,如果获取失败,提示用户可以跳过
  612. wx.showToast({
  613. title: '开发工具不支持,请真机测试或跳过',
  614. icon: 'none',
  615. duration: 2000
  616. });
  617. }
  618. },
  619. //获取昵称
  620. onChangeName(e) {
  621. console.log('=== 昵称输入事件 ===');
  622. console.log('事件对象:', e);
  623. // 注意:type="nickname" 的 input 会在用户输入时自动更新 model:value
  624. // 这里只是记录日志,实际的值更新由 model:value 自动处理
  625. if (e.detail && e.detail.value !== undefined) {
  626. console.log('昵称值:', e.detail.value);
  627. }
  628. },
  629. //确定头像昵称
  630. async onComplete() {
  631. console.log('=== onComplete 方法被调用 ===');
  632. let {
  633. nickname,
  634. avatarUrl
  635. } = this.data
  636. console.log('昵称:', nickname);
  637. console.log('头像URL:', avatarUrl);
  638. let user = Parse.User.current();
  639. if (!user) {
  640. console.error('❌ 用户未登录,无法保存信息');
  641. wx.showToast({
  642. title: '用户未登录',
  643. icon: 'none'
  644. });
  645. return;
  646. }
  647. console.log('当前用户ID:', user.id);
  648. // 显示加载提示
  649. wx.showLoading({
  650. title: '保存中...',
  651. mask: true
  652. });
  653. try {
  654. // 如果用户填写了信息,则更新
  655. if (nickname || avatarUrl) {
  656. console.log('ℹ️ 用户填写了信息,开始更新');
  657. // 如果有头像,上传头像
  658. if (avatarUrl) {
  659. console.log('📤 开始上传头像...');
  660. let avatar = await this.updataAvatar(avatarUrl);
  661. if (avatar) {
  662. user.set("avatar", avatar);
  663. console.log('✅ 头像上传成功:', avatar);
  664. } else {
  665. console.warn('⚠️ 头像上传失败');
  666. }
  667. }
  668. // 如果有昵称,更新昵称
  669. if (nickname) {
  670. user.set("nickname", nickname);
  671. console.log('✅ 昵称已设置:', nickname);
  672. }
  673. await user.save();
  674. console.log('✅ 用户信息保存成功');
  675. } else {
  676. // 用户没有填写任何信息,使用默认值
  677. console.log('ℹ️ 用户跳过头像昵称设置,使用默认值');
  678. // 如果用户没有昵称,设置默认昵称
  679. if (!user.get('nickname') || user.get('nickname') === '微信用户') {
  680. const defaultNickname = '用户' + user.id.substring(0, 6);
  681. user.set('nickname', defaultNickname);
  682. await user.save();
  683. console.log('✅ 已设置默认昵称:', defaultNickname);
  684. }
  685. }
  686. wx.hideLoading();
  687. // 关闭弹窗
  688. this.onClose();
  689. // 延迟一下再跳转,确保弹窗关闭动画完成
  690. setTimeout(() => {
  691. console.log('🚀 准备跳转...');
  692. this.backLoad();
  693. }, 300);
  694. } catch (err) {
  695. wx.hideLoading();
  696. console.error('❌ 保存用户信息失败:', err);
  697. wx.showModal({
  698. title: '提示',
  699. content: '保存失败,是否继续?',
  700. showCancel: true,
  701. cancelText: '重试',
  702. confirmText: '继续',
  703. success: (result) => {
  704. if (result.confirm) {
  705. // 用户选择继续,直接跳转
  706. this.onClose();
  707. setTimeout(() => {
  708. this.backLoad();
  709. }, 300);
  710. }
  711. // 用户选择重试,留在当前页面
  712. }
  713. });
  714. }
  715. },
  716. //跳过头像昵称设置
  717. async onSkip() {
  718. console.log('=== onSkip 方法被调用 ===');
  719. let user = Parse.User.current();
  720. if (!user) {
  721. console.error('❌ 用户未登录');
  722. wx.showToast({
  723. title: '用户未登录',
  724. icon: 'none'
  725. });
  726. return;
  727. }
  728. console.log('当前用户ID:', user.id);
  729. wx.showLoading({
  730. title: '处理中...',
  731. mask: true
  732. });
  733. try {
  734. // 设置默认昵称(如果没有)
  735. if (!user.get('nickname') || user.get('nickname') === '微信用户') {
  736. const defaultNickname = '用户' + user.id.substring(0, 6);
  737. user.set('nickname', defaultNickname);
  738. await user.save();
  739. console.log('✅ 已设置默认昵称:', defaultNickname);
  740. } else {
  741. console.log('ℹ️ 用户已有昵称:', user.get('nickname'));
  742. }
  743. wx.hideLoading();
  744. // 关闭弹窗
  745. this.onClose();
  746. // 延迟一下再跳转
  747. setTimeout(() => {
  748. console.log('🚀 准备跳转...');
  749. this.backLoad();
  750. }, 300);
  751. } catch (err) {
  752. wx.hideLoading();
  753. console.error('❌ 设置默认昵称失败:', err);
  754. // 即使失败也允许继续
  755. this.onClose();
  756. setTimeout(() => {
  757. this.backLoad();
  758. }, 300);
  759. }
  760. },
  761. //关闭头像昵称填写弹窗
  762. onClose() {
  763. this.setData({
  764. wxModel: false,
  765. isProcessingAuth: false // 重置标记
  766. })
  767. },
  768. //上传头像
  769. updataAvatar(url) {
  770. let that = this;
  771. return new Promise((resolve, rejcet) => {
  772. qiniuUploader.upload(
  773. url,
  774. async (res) => {
  775. let img = res.imageURL;
  776. resolve(img)
  777. },
  778. (error) => {
  779. console.log("error: " + error);
  780. resolve(false)
  781. }, {
  782. region: "SCN",
  783. uploadURL: that.data.uploadURL,
  784. domain: that.data.domain,
  785. uptoken: that.data.uptokenURL,
  786. }
  787. );
  788. })
  789. },
  790. //选择勾选用户协议
  791. onCheckAgreement() {
  792. this.setData({
  793. check: !this.data.check
  794. })
  795. },
  796. //附件下载
  797. openFile() {
  798. let {
  799. agreement
  800. } = this.data
  801. let url = agreement.content,
  802. name = agreement.title
  803. const _this = this;
  804. let rep = this.getFileType(url)
  805. console.log(url, name);
  806. wx.showLoading({
  807. title: '加载中',
  808. })
  809. wx.downloadFile({
  810. url: url, //要预览的PDF的地址
  811. filePath: wx.env.USER_DATA_PATH + `/${name}.${rep}`,
  812. success: function (res) {
  813. console.log(res);
  814. if (res.statusCode === 200) { //成功
  815. var Path = res.filePath //返回的文件临时地址,用于后面打开本地预览所用
  816. console.log(Path)
  817. wx.openDocument({
  818. filePath: Path, //要打开的文件路径
  819. showMenu: true,
  820. success: function (res) {
  821. wx.hideLoading()
  822. console.log(res, '打开PDF成功');
  823. },
  824. fail: function (res) {
  825. console.log(res)
  826. wx.hideLoading()
  827. }
  828. })
  829. }
  830. },
  831. fail: function (res) {
  832. wx.hideLoading()
  833. console.log(res); //失败
  834. },
  835. })
  836. },
  837. //解析文件类型
  838. getFileType(url) {
  839. let pdfReg = /^.+(\.pdf)$/
  840. let txtReg = /^.+(\.txt)$/
  841. let wordReg = /^.+(\.doc|\.docx)$/
  842. let excelReg = /^.+(\.xls|\.xlsx)$/
  843. let jpgPng = /^.+(\.png)$/
  844. let jpgJpg = /^.+(\.jpg)$/
  845. let jpgJpeg = /^.+(\.jpeg)$/
  846. if (pdfReg.test(url)) {
  847. return 'pdf'
  848. }
  849. if (txtReg.test(url)) {
  850. return 'txt'
  851. }
  852. if (wordReg.test(url)) {
  853. return 'docx'
  854. }
  855. if (excelReg.test(url)) {
  856. return 'xls'
  857. }
  858. if (jpgPng.test(url)) {
  859. return 'png'
  860. }
  861. if (jpgJpg.test(url)) {
  862. return 'jpg'
  863. }
  864. if (jpgJpeg.test(url)) {
  865. return 'jpeg'
  866. }
  867. },
  868. onShow: function () {
  869. console.log('=== onShow 方法被调用 ===');
  870. // 如果正在处理授权流程,不要自动返回
  871. if (this.data.isProcessingAuth) {
  872. console.log('ℹ️ 正在处理授权流程,不自动返回');
  873. return;
  874. }
  875. // 如果有弹窗显示(手机号弹窗或头像昵称弹窗),不要自动返回
  876. if (this.data.phoneModal || this.data.wxModel) {
  877. console.log('ℹ️ 有弹窗显示,不自动返回');
  878. return;
  879. }
  880. let userLogin = wx.getStorageSync('userLogin');
  881. let currentUser = Parse.User.current();
  882. console.log('userLogin 存储:', userLogin);
  883. console.log('当前用户:', currentUser ? currentUser.id : '无');
  884. console.log('手机号:', currentUser?.get('mobile') || '无');
  885. // 检查是否是从其他页面跳转过来的(有 returnUrl 参数)
  886. const pages = getCurrentPages();
  887. const currentPage = pages[pages.length - 1];
  888. const hasReturnUrl = currentPage?.options?.returnUrl;
  889. if (hasReturnUrl) {
  890. console.log('ℹ️ 检测到 returnUrl 参数,用户需要完成登录流程');
  891. // 不要自动返回,让用户完成登录
  892. return;
  893. }
  894. // 只有当用户已登录且有手机号,并且不是从其他页面跳转过来时才返回
  895. if (userLogin && currentUser && currentUser.get('mobile')) {
  896. console.log('✅ 用户已完整登录,返回上一页');
  897. wx.navigateBack({
  898. fail: () => {
  899. console.log('⚠️ 返回失败,可能是首页');
  900. }
  901. });
  902. } else {
  903. console.log('ℹ️ 用户未完整登录,显示授权页面');
  904. }
  905. },
  906. onReady: function () {
  907. },
  908. })