| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006 |
- let Parse = getApp().Parse;
- let company = getApp().globalData.company
- const request = require("../../utils/request");
- const qiniuUploader = require("../../utils/qiniuUploader");
- //获取应用实例
- const app = getApp()
- const real = require('../../utils/real')
- var timer
- /**
- * @class NovaAppAuth
- * @memberof module:components
- * @tutorial userauth
- * @desc 通用登录组件
- * # 登录组件相关数据表
- * - _User
- */
- Page({
- data: {
- phoneModal: false, //短信验证码登录弹窗
- logo: "https://file-cloud.fmode.cn/MldI5PBNt7/20210928/g0k1jb034826.png",
- name: "未来商城",
- desc: "江西脑控科技有限公司是国内领先的IT技术企业。专注于互联网+服务,面向政府提供区块链、大数据、物联网、人工智能解决方案",
- wxModel: false,
- avatarUrl: '',
- avatar: '',
- nickname: '',
- check: false,
- mobile: '', //手机号
- verilyCode: '', //验证码
- s: 0, //获取验证码倒计时 秒/s
- countDown: false,
- avatarKey: Date.now(), // 用于强制刷新头像显示
- isProcessingAuth: false, // 标记是否正在处理授权流程
- },
- onLoad: async function (options) {
- let Company = new Parse.Query('Company')
- Company.equalTo("objectId", company)
- let currentCompany = await Company.first()
- if (currentCompany && currentCompany.id) {
- this.setData({
- logo: currentCompany.get('logo'),
- name: currentCompany.get('name'),
- desc: currentCompany.get('desc')
- })
- }
- this.getUptoken()
- this.getAgreement() //用户协议
- },
- async getUptoken() {
- let res = await Parse.Cloud.run('qiniu_uptoken', {
- company: company
- })
- this.setData({
- uptokenURL: res.uptoken,
- domain: res.domain,
- uploadURL: res.zoneUrl
- })
- },
- async getAgreement() {
- let query = new Parse.Query('ContractAgreement')
- query.equalTo('type', 'wxapp')
- query.equalTo('company', company)
- query.select('title', 'content')
- let res = await query.first()
- if (res?.id) {
- this.setData({
- agreement: res.toJSON()
- })
- }
- },
- /* 是否同意授权协议 */
- getAgreementAuth() {
- if (!this.data.check && this.data.agreement) {
- wx.showModal({
- title: '提示',
- content: `请您仔细阅读并充分理解相关条款,点击同意即代表已阅读并同意《${this.data.agreement.title || '用户隐私协议'}》`,
- showCancel: true,
- cancelText: '取消',
- cancelColor: '#000000',
- confirmText: '同意',
- confirmColor: '#3CC51F',
- success: (result) => {
- if (result.confirm) {
- this.setData({
- check: true,
- })
- // this.getUserProfile()
- }
- },
- fail: () => { },
- complete: () => { }
- });
- return
- }
- // this.getUserProfile()
- return true
- },
- /* 判断是否绑定手机号 */
- async getUserProfile() {
- // 检查用户是否已登录
- let currentUser = Parse.User.current();
-
- if (!currentUser?.id) {
- console.log('⚠️ 用户未登录,需要先登录');
- // 不要在这里调用 checkAuth(true),因为它会触发微信官方的强制授权弹窗
- // 应该在外层(index.js)处理登录逻辑
- return false;
- }
-
- /* 如果手机号存在,已注册过判断是否上传过头像昵称信息 */
- if (currentUser?.get('mobile')) {
- wx.setStorageSync("userLogin", currentUser.id);
-
- // 检查是否需要完善信息(可选)
- // 如果用户没有昵称或昵称是默认的,提示完善信息
- const needProfile = !currentUser.get('nickname') ||
- currentUser.get('nickname') === '微信用户' ||
- currentUser.get('nickname') === '';
-
- if (needProfile) {
- // 显示自定义的完善信息弹窗(允许跳过)
- console.log('ℹ️ 显示自定义头像昵称弹窗');
- this.setData({
- wxModel: true
- });
- return false;
- }
-
- // 用户信息完整,返回上一页
- this.backLoad();
- return false;
- }
-
- // 用户已登录但没有手机号,允许继续
- return true;
- },
- /* 短信验证码登录弹窗 */
- async showDialogBtn() {
- let auth = this.getAgreementAuth()
- if (!auth) return
- let userProfile = await this.getUserProfile()
- if (!userProfile) return
-
- // 标记正在处理授权
- this.setData({
- isProcessingAuth: true,
- phoneModal: true
- })
- },
- async getPhoneNumber(e) {
- let auth = this.getAgreementAuth()
- if (!auth) return
- let userProfile = await this.getUserProfile()
- if (!userProfile) return
-
- // 标记正在处理授权
- this.setData({
- isProcessingAuth: true
- })
-
- let {
- code
- } = e.detail
- console.log(code);
- let phoneNumber = await request.getPhone(code)
- if(phoneNumber) this.authMobileUser(phoneNumber)
- },
- //合并User与绑定手机号逻辑
- async authMobileUser(mobile) {
- let currentUser = Parse.User.current()
- let queryMobUser = new Parse.Query('_User')
- queryMobUser.equalTo('mobile', mobile)
- queryMobUser.equalTo('company', company)
- queryMobUser.notEqualTo('type', 'admin')
- queryMobUser.notEqualTo('isDeleted', true)
- // queryMobUser.exists(`wxapp.${getApp().globalData.appid}`)
- let resMobUser = await queryMobUser.first()
- if (resMobUser?.id) {
- //请求User合并API,获取token重新登录,再更新昵称头像信息等
- let token = await this.getUpdateUserToken(currentUser.id, resMobUser.id)
- console.log(token);
- if (token) {
- Parse.User.become(token).then(async user => {
- // let user = Parse.User.current();
- wx.setStorageSync("userLogin", user.id);
- if (!user.get('avatar') || user.get('nickname') == '微信用户' || !user.get('nickname')) {
- this.setData({
- phoneModal: false,
- wxModel: true
- })
- return
- }
- this.backLoad()
- return
- })
- .catch(async err => {
- console.log('❌ Parse.User.become 失败:', err);
-
- // 不要直接退出,而是尝试重新登录
- wx.showModal({
- title: '提示',
- content: '登录状态异常,是否重新登录?',
- showCancel: true,
- cancelText: '取消',
- confirmText: '重新登录',
- success: async (result) => {
- if (result.confirm) {
- // 清除登录状态
- wx.removeStorageSync("sessionToken");
- wx.removeStorageSync("userLogin");
-
- try {
- // 尝试重新登录
- await Parse.User.logOut();
- await getApp().checkAuth(true);
-
- // 重新获取用户信息
- const currentUser = Parse.User.current();
- if (currentUser && currentUser.get('mobile')) {
- wx.setStorageSync("userLogin", currentUser.id);
- this.backLoad();
- }
- } catch (reloginErr) {
- console.error('❌ 重新登录失败:', reloginErr);
- wx.showToast({
- title: '登录失败,请稍后重试',
- icon: 'none'
- });
- }
- } else {
- // 用户取消,返回上一页
- wx.navigateBack();
- }
- },
- });
- return
- })
- return
- }
- return
- }
- currentUser.set('mobile', mobile)
- await currentUser.save()
- if (!currentUser.get('avatar') || currentUser.get('nickname') == '微信用户' || !currentUser.get('nickname')) {
- this.setData({
- phoneModal: false,
- wxModel: true
- })
- return
- }
- this.backLoad()
- return
- },
- async getUpdateUserToken(oldUser, newUserId) {
- return new Promise((resolve, reject) => {
- wx.login({
- success: function (res) {
- let parms = {
- oldUserId: oldUser,
- newUserId: newUserId,
- appId: getApp().globalData.appid,
- code: res.code,
- companyId: company,
- appType: getApp().globalData.appType || ''
- }
- if (res.code) {
- let url = 'https://server.fmode.cn/api/wxapp/combine/user'
- wx.request({
- url: url,
- data: parms,
- header: { 'content-type': 'application/json' },
- method: 'POST',
- async success(res) {
- console.log(res);
- let data = res.data
- if (data.code == 200) {
- wx.setStorageSync("sessionToken", data.data.token);
-
- // 用户合并成功后,更新 ScanRecord 表中的 user 字段
- console.log('🔄 [用户合并] 开始更新 ScanRecord 中的用户关联');
- console.log(' - 旧用户ID:', oldUser);
- console.log(' - 新用户ID:', newUserId);
-
- try {
- // 使用 Parse.User.become 切换到新用户
- await Parse.User.become(data.data.token);
-
- // 查询所有旧用户的扫码记录
- const ScanRecord = Parse.Object.extend('ScanRecord');
- const scanQuery = new Parse.Query(ScanRecord);
- scanQuery.equalTo('user', {
- __type: 'Pointer',
- className: '_User',
- objectId: oldUser
- });
- scanQuery.limit(1000); // 设置查询上限
-
- const oldRecords = await scanQuery.find();
- console.log(`📋 [查询结果] 找到 ${oldRecords.length} 条旧用户的扫码记录`);
-
- if (oldRecords.length > 0) {
- // 批量更新所有记录,将 user 指向新用户
- const updatePromises = oldRecords.map(record => {
- record.set('user', {
- __type: 'Pointer',
- className: '_User',
- objectId: newUserId
- });
- return record.save();
- });
-
- await Promise.all(updatePromises);
- console.log(`✅ [更新成功] 已将 ${oldRecords.length} 条扫码记录的用户更新为新用户`);
- } else {
- console.log('ℹ️ [无需更新] 旧用户没有扫码记录');
- }
- } catch (updateError) {
- console.error('❌ [更新失败] 更新 ScanRecord 失败:', updateError);
- console.error(' - 错误信息:', updateError.message);
- // 不影响主流程,继续返回 token
- }
-
- resolve(data.data.token)
- } else {
- console.log(data?.mess);
- wx.showModal({
- title: '提示',
- content: data?.mess,
- showCancel: false,
- cancelText: '取消',
- cancelColor: '#000000',
- confirmText: '确定',
- confirmColor: '#3CC51F',
- success: (result) => {
- if (result.confirm) {
- }
- },
- fail: () => { },
- complete: () => { }
- });
- resolve()
- }
- },
- });
- }
- },
- fail: function (err) {
- wx.showModal({
- title: '提示',
- content: '登录超时,请稍后重试',
- showCancel: false,
- cancelText: '取消',
- cancelColor: '#000000',
- confirmText: '确定',
- confirmColor: '#3CC51F',
- success: (result) => {
- if (result.confirm) {
- }
- },
- fail: () => { },
- complete: () => { }
- });
- console.warn('小程序wx.login失败');
- resolve()
- }
- });
- })
- },
- //获取验证码
- async getPhoneCode() {
- let { mobile, s, countDown } = this.data
- if (!real.isPoneAvailable(mobile)) {
- wx.showToast({
- title: '手机号格式有误',
- icon: 'error',
- duration: 1500,
- mask: false,
- });
- return
- }
- if(countDown || s > 0) return
- this.setData({
- countDown:true
- })
- let parsm = {
- company: company,
- mobile: mobile
- }
- let code = await this.getRequest(parsm, 'message')
- if(code?.code == 1){
- this.setData({
- s:60
- })
- this.decrementTime()
- }else{
- wx.showToast({
- title: '验证码获取失败',
- icon: 'error',
- image: '',
- duration: 1500,
- mask: false,
- });
- this.setData({
- countDown:false
- })
- }
- },
- //接口请求
- getRequest(parsm, apig) {
- return new Promise((resolve, rej) => {
- let url = 'https://server.fmode.cn/api/apig/'
- wx.request({
- url: url + apig,
- data: parsm,
- header: { 'content-type': 'application/json' },
- method: 'POST',
- dataType: 'json',
- responseType: 'text',
- success: (result) => {
- console.log(result);
- resolve(result.data)
- },
- fail: () => {
- resolve(false)
- },
- complete: () => { }
- });
- })
- },
- // 倒计时
- decrementTime(){
- timer = setTimeout(() => {
- let { s } = this.data
- if(s == 0){
- this.setData({ countDown:false })
- timer && clearTimeout(timer)
- return
- }
- s--
- this.setData({
- s:s
- })
- this.decrementTime()
- }, 1000);
- },
- //验证码绑定手机号登录
- async completePhone() {
- let { mobile, verilyCode } = this.data
- if(!real.isPoneAvailable(mobile) || !verilyCode.toString().trim()){
- wx.showToast({
- title: '手机号或验证码不正确',
- icon: 'none',
- image: '',
- duration: 1500,
- mask: false,
- });
- return
- }
-
- // 标记正在处理授权
- this.setData({
- isProcessingAuth: true
- })
-
- let parsm = {
- mobile: mobile,
- code:verilyCode
- }
- let isVerify = await this.getRequest(parsm, 'verifyCode')
- console.log(isVerify);
- if(isVerify.code == 200){
- this.authMobileUser(mobile.toString())
- }else{
- // 验证失败,重置标记
- this.setData({
- isProcessingAuth: false
- })
- wx.showToast({
- title:isVerify?.msg || '验证码错误',
- icon: 'none',
- image: '',
- duration: 1500,
- mask: false,
- });
- return
- }
- },
- //关闭手机号授权弹窗
- hideModal: function () {
- this.setData({
- phoneModal: false,
- isProcessingAuth: false // 重置标记
- })
- },
- backLoad() {
- console.log('===========================================');
- console.log('======= backLoad 方法调用 =======');
-
- let pages = getCurrentPages();
- console.log('当前页面栈层数:', pages.length);
- console.log('当前页面路由:', pages[pages.length - 1]?.route);
-
- // 检查是否有 returnUrl 参数(从 H5 页面传递过来)
- const currentPage = pages[pages.length - 1];
- const returnUrl = currentPage?.options?.returnUrl;
-
- if (returnUrl) {
- console.log('📍 检测到 returnUrl 参数:', returnUrl);
-
- // 如果是 web-view 页面,跳转回去
- const decodedUrl = decodeURIComponent(returnUrl);
- console.log('🔙 准备跳转回 H5 页面:', decodedUrl);
-
- wx.navigateTo({
- url: `/common-page/pages/web-view/index?path=${encodeURIComponent(decodedUrl)}`,
- success: () => {
- console.log('✅ 跳转回 H5 页面成功');
- console.log('===========================================');
- },
- fail: (err) => {
- console.error('❌ 跳转回 H5 页面失败:', err);
- // 降级:正常返回上一页
- this.normalBackLoad();
- }
- });
- return;
- }
-
- // 没有 returnUrl,执行正常的返回逻辑
- this.normalBackLoad();
- },
-
- normalBackLoad() {
- let pages = getCurrentPages();
-
- // 如果页面栈只有1层或没有上一页,直接跳转到首页
- if (pages.length <= 1) {
- console.log('⚠️ 没有上一个页面,直接跳转到首页');
- this.goToHome();
- return;
- }
-
- // 有上一个页面
- let beforePage = pages[pages.length - 2];
- console.log('上一个页面路由:', beforePage.route);
-
- // 尝试调用上一个页面的 onLoad 方法(如果存在)
- if (beforePage && typeof beforePage.onLoad === 'function') {
- try {
- let options = beforePage.options || { isInit: true };
- beforePage.onLoad(options);
- console.log('✅ 已调用上一个页面的 onLoad');
- } catch (err) {
- console.warn('⚠️ 调用上一个页面 onLoad 失败:', err);
- }
- }
-
- // 返回上一页
- console.log('🔙 执行 navigateBack...');
- wx.navigateBack({
- delta: 1,
- success: () => {
- console.log('✅ navigateBack 成功');
- console.log('===========================================');
- },
- fail: (err) => {
- console.error('❌ navigateBack 失败:', err);
- console.log('⚠️ 尝试使用 reLaunch 跳转到首页');
- this.goToHome();
- }
- });
- },
-
- // 跳转到首页
- goToHome() {
- console.log('===========================================');
- console.log('======= goToHome 方法调用 =======');
-
- const app = getApp();
- console.log('globalData.rootPage:', app.globalData.rootPage);
- console.log('globalData.defaultTabBar:', app.globalData.defaultTabBar);
-
- // 尝试多个可能的首页路径
- let rootPage = app.globalData.rootPage
- || app.globalData.defaultTabBar?.list?.[0]?.pagePath
- || '/pages/index/index'
- || '/index/index';
-
- // 确保路径以 / 开头
- if (!rootPage.startsWith('/')) {
- rootPage = '/' + rootPage;
- }
-
- console.log('准备跳转到:', rootPage);
-
- wx.reLaunch({
- url: rootPage,
- success: () => {
- console.log('✅ reLaunch 成功');
- console.log('===========================================');
- },
- fail: (err) => {
- console.error('❌ reLaunch 失败:', err);
- console.log('⚠️ 尝试使用 switchTab');
-
- // 如果是 tabBar 页面,尝试使用 switchTab
- wx.switchTab({
- url: rootPage,
- success: () => {
- console.log('✅ switchTab 成功');
- console.log('===========================================');
- },
- fail: (err2) => {
- console.error('❌ switchTab 也失败:', err2);
- console.log('⚠️ 最后尝试:直接 navigateBack');
-
- // 最后的兜底:直接返回
- wx.navigateBack({
- delta: 1,
- fail: (err3) => {
- console.error('❌ 所有跳转方式都失败了:', err3);
- console.log('===========================================');
-
- // 显示错误提示
- wx.showModal({
- title: '提示',
- content: '页面跳转失败,请手动返回',
- showCancel: false
- });
- }
- });
- }
- });
- }
- });
- },
- goBack: function () {
- wx.navigateBack({
- delta: 1,
- })
- },
- //手动获取微信头像
- onChooseAvatar(e) {
- console.log('=== onChooseAvatar 触发 ===');
- console.log('事件对象:', e);
-
- const { avatarUrl } = e.detail;
- console.log('获取到的头像URL:', avatarUrl);
- console.log('头像URL类型:', typeof avatarUrl);
- console.log('头像URL长度:', avatarUrl ? avatarUrl.length : 0);
-
- if (avatarUrl) {
- // 微信头像URL可能是临时路径,需要先下载
- // 临时路径格式:http://tmp/xxx.jpg
- // 相机拍照路径格式:wxfile://tmp_xxx.jpg
-
- this.setData({
- avatarUrl: avatarUrl,
- avatarKey: Date.now() // 更新key强制刷新
- }, () => {
- console.log('✅ 头像URL已更新到data:', this.data.avatarUrl);
- console.log('✅ avatarKey已更新:', this.data.avatarKey);
- });
- } else {
- console.error('❌ 未获取到头像URL');
-
- // 在开发环境下,如果获取失败,提示用户可以跳过
- wx.showToast({
- title: '开发工具不支持,请真机测试或跳过',
- icon: 'none',
- duration: 2000
- });
- }
- },
- //获取昵称
- onChangeName(e) {
- console.log('=== 昵称输入事件 ===');
- console.log('事件对象:', e);
-
- // 注意:type="nickname" 的 input 会在用户输入时自动更新 model:value
- // 这里只是记录日志,实际的值更新由 model:value 自动处理
- if (e.detail && e.detail.value !== undefined) {
- console.log('昵称值:', e.detail.value);
- }
- },
- //确定头像昵称
- async onComplete() {
- console.log('=== onComplete 方法被调用 ===');
-
- let {
- nickname,
- avatarUrl
- } = this.data
-
- console.log('昵称:', nickname);
- console.log('头像URL:', avatarUrl);
-
- let user = Parse.User.current();
-
- if (!user) {
- console.error('❌ 用户未登录,无法保存信息');
- wx.showToast({
- title: '用户未登录',
- icon: 'none'
- });
- return;
- }
-
- console.log('当前用户ID:', user.id);
-
- // 显示加载提示
- wx.showLoading({
- title: '保存中...',
- mask: true
- });
-
- try {
- // 如果用户填写了信息,则更新
- if (nickname || avatarUrl) {
- console.log('ℹ️ 用户填写了信息,开始更新');
-
- // 如果有头像,上传头像
- if (avatarUrl) {
- console.log('📤 开始上传头像...');
- let avatar = await this.updataAvatar(avatarUrl);
- if (avatar) {
- user.set("avatar", avatar);
- console.log('✅ 头像上传成功:', avatar);
- } else {
- console.warn('⚠️ 头像上传失败');
- }
- }
-
- // 如果有昵称,更新昵称
- if (nickname) {
- user.set("nickname", nickname);
- console.log('✅ 昵称已设置:', nickname);
- }
-
- await user.save();
- console.log('✅ 用户信息保存成功');
- } else {
- // 用户没有填写任何信息,使用默认值
- console.log('ℹ️ 用户跳过头像昵称设置,使用默认值');
-
- // 如果用户没有昵称,设置默认昵称
- if (!user.get('nickname') || user.get('nickname') === '微信用户') {
- const defaultNickname = '用户' + user.id.substring(0, 6);
- user.set('nickname', defaultNickname);
- await user.save();
- console.log('✅ 已设置默认昵称:', defaultNickname);
- }
- }
-
- wx.hideLoading();
-
- // 关闭弹窗
- this.onClose();
-
- // 延迟一下再跳转,确保弹窗关闭动画完成
- setTimeout(() => {
- console.log('🚀 准备跳转...');
- this.backLoad();
- }, 300);
-
- } catch (err) {
- wx.hideLoading();
- console.error('❌ 保存用户信息失败:', err);
-
- wx.showModal({
- title: '提示',
- content: '保存失败,是否继续?',
- showCancel: true,
- cancelText: '重试',
- confirmText: '继续',
- success: (result) => {
- if (result.confirm) {
- // 用户选择继续,直接跳转
- this.onClose();
- setTimeout(() => {
- this.backLoad();
- }, 300);
- }
- // 用户选择重试,留在当前页面
- }
- });
- }
- },
-
- //跳过头像昵称设置
- async onSkip() {
- console.log('=== onSkip 方法被调用 ===');
-
- let user = Parse.User.current();
-
- if (!user) {
- console.error('❌ 用户未登录');
- wx.showToast({
- title: '用户未登录',
- icon: 'none'
- });
- return;
- }
-
- console.log('当前用户ID:', user.id);
-
- wx.showLoading({
- title: '处理中...',
- mask: true
- });
-
- try {
- // 设置默认昵称(如果没有)
- if (!user.get('nickname') || user.get('nickname') === '微信用户') {
- const defaultNickname = '用户' + user.id.substring(0, 6);
- user.set('nickname', defaultNickname);
- await user.save();
- console.log('✅ 已设置默认昵称:', defaultNickname);
- } else {
- console.log('ℹ️ 用户已有昵称:', user.get('nickname'));
- }
-
- wx.hideLoading();
-
- // 关闭弹窗
- this.onClose();
-
- // 延迟一下再跳转
- setTimeout(() => {
- console.log('🚀 准备跳转...');
- this.backLoad();
- }, 300);
-
- } catch (err) {
- wx.hideLoading();
- console.error('❌ 设置默认昵称失败:', err);
-
- // 即使失败也允许继续
- this.onClose();
- setTimeout(() => {
- this.backLoad();
- }, 300);
- }
- },
- //关闭头像昵称填写弹窗
- onClose() {
- this.setData({
- wxModel: false,
- isProcessingAuth: false // 重置标记
- })
- },
- //上传头像
- updataAvatar(url) {
- let that = this;
- return new Promise((resolve, rejcet) => {
- qiniuUploader.upload(
- url,
- async (res) => {
- let img = res.imageURL;
- resolve(img)
- },
- (error) => {
- console.log("error: " + error);
- resolve(false)
- }, {
- region: "SCN",
- uploadURL: that.data.uploadURL,
- domain: that.data.domain,
- uptoken: that.data.uptokenURL,
- }
- );
- })
- },
- //选择勾选用户协议
- onCheckAgreement() {
- this.setData({
- check: !this.data.check
- })
- },
- //附件下载
- openFile() {
- let {
- agreement
- } = this.data
- let url = agreement.content,
- name = agreement.title
- const _this = this;
- let rep = this.getFileType(url)
- console.log(url, name);
- wx.showLoading({
- title: '加载中',
- })
- wx.downloadFile({
- url: url, //要预览的PDF的地址
- filePath: wx.env.USER_DATA_PATH + `/${name}.${rep}`,
- success: function (res) {
- console.log(res);
- if (res.statusCode === 200) { //成功
- var Path = res.filePath //返回的文件临时地址,用于后面打开本地预览所用
- console.log(Path)
- wx.openDocument({
- filePath: Path, //要打开的文件路径
- showMenu: true,
- success: function (res) {
- wx.hideLoading()
- console.log(res, '打开PDF成功');
- },
- fail: function (res) {
- console.log(res)
- wx.hideLoading()
- }
- })
- }
- },
- fail: function (res) {
- wx.hideLoading()
- console.log(res); //失败
- },
- })
- },
- //解析文件类型
- getFileType(url) {
- let pdfReg = /^.+(\.pdf)$/
- let txtReg = /^.+(\.txt)$/
- let wordReg = /^.+(\.doc|\.docx)$/
- let excelReg = /^.+(\.xls|\.xlsx)$/
- let jpgPng = /^.+(\.png)$/
- let jpgJpg = /^.+(\.jpg)$/
- let jpgJpeg = /^.+(\.jpeg)$/
- if (pdfReg.test(url)) {
- return 'pdf'
- }
- if (txtReg.test(url)) {
- return 'txt'
- }
- if (wordReg.test(url)) {
- return 'docx'
- }
- if (excelReg.test(url)) {
- return 'xls'
- }
- if (jpgPng.test(url)) {
- return 'png'
- }
- if (jpgJpg.test(url)) {
- return 'jpg'
- }
- if (jpgJpeg.test(url)) {
- return 'jpeg'
- }
- },
- onShow: function () {
- console.log('=== onShow 方法被调用 ===');
-
- // 如果正在处理授权流程,不要自动返回
- if (this.data.isProcessingAuth) {
- console.log('ℹ️ 正在处理授权流程,不自动返回');
- return;
- }
-
- // 如果有弹窗显示(手机号弹窗或头像昵称弹窗),不要自动返回
- if (this.data.phoneModal || this.data.wxModel) {
- console.log('ℹ️ 有弹窗显示,不自动返回');
- return;
- }
-
- let userLogin = wx.getStorageSync('userLogin');
- let currentUser = Parse.User.current();
-
- console.log('userLogin 存储:', userLogin);
- console.log('当前用户:', currentUser ? currentUser.id : '无');
- console.log('手机号:', currentUser?.get('mobile') || '无');
-
- // 检查是否是从其他页面跳转过来的(有 returnUrl 参数)
- const pages = getCurrentPages();
- const currentPage = pages[pages.length - 1];
- const hasReturnUrl = currentPage?.options?.returnUrl;
-
- if (hasReturnUrl) {
- console.log('ℹ️ 检测到 returnUrl 参数,用户需要完成登录流程');
- // 不要自动返回,让用户完成登录
- return;
- }
-
- // 只有当用户已登录且有手机号,并且不是从其他页面跳转过来时才返回
- if (userLogin && currentUser && currentUser.get('mobile')) {
- console.log('✅ 用户已完整登录,返回上一页');
- wx.navigateBack({
- fail: () => {
- console.log('⚠️ 返回失败,可能是首页');
- }
- });
- } else {
- console.log('ℹ️ 用户未完整登录,显示授权页面');
- }
- },
- onReady: function () {
- },
- })
|