| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867 |
- 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() // 用于强制刷新头像显示
- },
- 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({
- phoneModal: true
- })
- },
- async getPhoneNumber(e) {
- let auth = this.getAgreementAuth()
- if (!auth) return
- let userProfile = await this.getUserProfile()
- if (!userProfile) return
- 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);
- 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
- }
- 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{
- wx.showToast({
- title:isVerify?.msg || '验证码错误',
- icon: 'none',
- image: '',
- duration: 1500,
- mask: false,
- });
- return
- }
- },
- //关闭手机号授权弹窗
- hideModal: function () {
- this.setData({
- phoneModal: false
- })
- },
- backLoad() {
- console.log('===========================================');
- console.log('======= backLoad 方法调用 =======');
-
- let pages = getCurrentPages();
- console.log('当前页面栈层数:', pages.length);
- console.log('当前页面路由:', pages[pages.length - 1]?.route);
-
- // 如果页面栈只有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
- })
- },
- //上传头像
- 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 () {
- let userLogin = wx.getStorageSync('userLogin');
- if (userLogin != '') {
- wx.navigateBack();
- };
- },
- onReady: function () {
- },
- })
|