Files
xk-client-wx/utils/login.js
2026-01-14 20:59:32 +08:00

220 lines
6.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 登录工具函数
* 抽离登录逻辑,支持静默登录和正常登录
*/
import { getsLogin } from '@/request/api/api.js';
import { bindUserApi } from '@/request/api/salesperson';
import { storeChange } from '@/request/api/api.js';
import { clearGuestMode, getRedirectInfo, clearRedirectInfo, buildUrlWithParams } from '@/common/utils/auth.js';
import { webSocketManager } from '@/utils/ws/websocket.js';
/**
* 执行登录流程
* @param {Object} options - 配置选项
* @param {boolean} options.silent - 是否静默模式
* - true: 静默登录(不显示提示,不跳转)
* - false: 正常登录(显示提示,执行跳转)
* @param {Object} options.toastRef - Toast 引用(正常登录时用于显示错误提示)
* @returns {Promise<Object>} 返回登录结果 { success: boolean, data: Object, message: string }
*/
export async function performLogin(options = { silent: false, toastRef: null }) {
const { silent = false, toastRef = null } = options;
try {
// 步骤 1:显示加载提示(仅非静默模式)
if (!silent) {
uni.showLoading({
title: "登录中"
});
}
// 步骤 2:获取微信登录凭证
const loginRes = await new Promise((resolve, reject) => {
uni.login({
provider: 'weixin',
success: resolve,
fail: reject
});
});
const code = loginRes.code;
// 步骤 3:调用登录接口
const res = await getsLogin({
method: "post",
data: {
code: code,
status: 1
}
});
// 步骤 4:隐藏加载提示(仅非静默模式)
if (!silent) {
uni.hideLoading();
}
// 步骤 5:处理登录结果
if (res.data.errcode == 0) {
// 登录成功
// 5.1 存储用户信息
uni.setStorageSync('token', res.data.data.token);
uni.setStorageSync('user_id', res.data.data.data.user.id);
uni.setStorageSync('userinfo', res.data.data.data['user']);
// 5.2 绑定推广员(如果存在)
const salespersonId = uni.getStorageSync('salesperson_id');
if (salespersonId) {
bindUserApi({
user_id: res.data.data.data.user.id,
salesperson_id: salespersonId,
}).then((bindRes) => {
console.log(bindRes, 'bindUserApi', bindRes);
}).catch((err) => {
console.error('绑定推广员失败:', err);
});
}
// 5.3 处理门店切换/设置
// 优先使用已存在的 store_id(可能是扫码设置的),避免覆盖
const existingStoreId = uni.getStorageSync('store_id');
if (existingStoreId) {
// 如果已存在 store_id(可能是扫码设置的),使用现有的值进行门店切换
console.log('[登录调试] 使用已存在的 store_id 进行门店切换:', existingStoreId);
storeChange({
method: "post",
data: {
store_id: existingStoreId
}
}).catch((err) => {
console.error('[登录调试] 切换门店失败:', err);
});
} else {
// 只有在 store_id 不存在时才使用服务器返回的值
const serverStoreId = res.data.data.data.store_id;
if (serverStoreId) {
console.log('[登录调试] store_id 不存在,使用服务器返回的值:', serverStoreId);
uni.setStorageSync('store_id', serverStoreId);
} else {
console.warn('[登录调试] 服务器未返回 store_id,保持默认值');
}
}
// 5.4 清除 Guest 模式标记
clearGuestMode();
// 5.5 重新绑定 WebSocket(登录成功后)
try {
webSocketManager.rebindUser();
} catch (error) {
console.error('重新绑定 WebSocket 失败:', error);
}
// 5.6 页面跳转(仅非静默模式)
if (!silent) {
const redirectInfo = getRedirectInfo();
const userMobile = res.data.data.data.user.mobile;
if (userMobile != '') {
setTimeout(() => {
if (redirectInfo) {
// 有跳转信息,跳转回原页面
clearRedirectInfo();
const redirectUrl = buildUrlWithParams(redirectInfo.path, redirectInfo.params);
uni.navigateTo({
url: redirectUrl,
fail: () => {
// 如果跳转失败,使用redirectTo
uni.redirectTo({
url: redirectUrl
});
}
});
} else {
// 没有跳转信息,跳转到首页
uni.reLaunch({
url: '/pages/home/home'
});
}
}, 500);
}
}
return {
success: true,
data: res.data.data,
message: '登录成功'
};
} else {
// 登录失败
const errorMsg = res.data.msg || '登录失败';
// 显示错误提示(仅非静默模式)
if (!silent && toastRef) {
toastRef.show({
title: errorMsg,
type: 'default',
icon: false
});
} else if (!silent) {
// 如果没有 toastRef,使用 uni.showToast
uni.showToast({
title: errorMsg,
icon: 'none',
duration: 2000
});
} else {
// 静默模式:仅记录日志
console.error('静默登录失败:', errorMsg);
}
return {
success: false,
data: null,
message: errorMsg
};
}
} catch (error) {
// 处理异常
const errorMsg = error.message || '登录过程发生错误';
// 隐藏加载提示(仅非静默模式)
if (!silent) {
uni.hideLoading();
}
// 显示错误提示(仅非静默模式)
if (!silent && toastRef) {
toastRef.show({
title: errorMsg,
type: 'default',
icon: false
});
} else if (!silent) {
uni.showToast({
title: errorMsg,
icon: 'none',
duration: 2000
});
} else {
// 静默模式:仅记录日志
console.error('静默登录异常:', error);
}
return {
success: false,
data: null,
message: errorMsg
};
}
}
/**
* 静默登录(便捷方法)
* @returns {Promise<Object>} 返回登录结果
*/
export async function silentLogin() {
return performLogin({ silent: true });
}