WMS_PDA/pages/login/index.vue

1348 lines
37 KiB
Vue
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.

<template>
<view class="login-container" :style="bgStyle">
<view class="form_box">
<view class="header-section">
<text class="system-title" @click="handleSystemTitleTap">PDA仓库管理系统</text>
</view>
<view class="login-methods">
<!-- 账号密码登录 -->
<view class="method-card direct-login-card">
<view class="direct-login-form">
<u--input
v-model="loginForm.username"
placeholder="请输入账号"
inputAlign="center"
clearable
border="bottom"
:customStyle="{ marginBottom: '24rpx' }"
></u--input>
<view class="password-input-wrap">
<u--input
v-model="loginForm.password"
placeholder="请输入密码"
inputAlign="center"
:type="showPassword ? 'text' : 'password'"
@confirm="Login"
clearable
border="bottom"
:customStyle="{ marginBottom: '24rpx' }"
></u--input>
<u-icon
class="password-toggle-icon"
:name="showPassword ? 'eye' : 'eye-off-outline'"
size="32rpx"
color="#666"
@click="togglePasswordVisibility"
></u-icon>
</view>
<u-button
type="primary"
text="登录"
@click="Login"
></u-button>
</view>
</view>
<!-- 广播扫描登录 -->
<view class="method-card scan-login-card" @click="handleManualScan">
<view class="method-icon">
<u-icon name="scan" size="36rpx" color="#19be6b"></u-icon>
</view>
<view class="scan-login-content">
<text class="method-desc">PDA扫描登录</text>
<u-button
type="success"
size="mini"
text="点击扫描"
@click.stop="handleManualScan"
></u-button>
</view>
</view>
<!-- 工作台登录码登录(免登录直达打包模式):隐藏入口,连续点击5次标题后显示 -->
<view v-if="showWorkbenchLogin" class="method-card workbench-login-card">
<u--input
v-model="workbenchCode"
placeholder="请输入工作台登录码"
inputAlign="center"
clearable
border="bottom"
:focus="workbenchInputFocus"
:customStyle="{ marginBottom: '24rpx' }"
@confirm="handleWorkbenchInputConfirm"
></u--input>
</view>
</view>
</view>
<view v-if="showUpdateDialog" class="update-mask">
<view class="update-dialog">
<view class="update-header">
<text class="update-title">发现新版本</text>
<text class="update-version">当前 {{ currentAppVersion || '--' }} → 最新 {{ updateInfo.version || '--' }}</text>
</view>
<view class="update-body">
<view class="update-row">
<text class="update-label">安装包</text>
<text class="update-value">{{ updateInfo.file || '未提供文件名' }}</text>
</view>
<view v-if="updateInfo.publishedAtUtc" class="update-row">
<text class="update-label">发布时间</text>
<text class="update-value">{{ formatUpdateTime(updateInfo.publishedAtUtc) }}</text>
</view>
<view class="update-tip-box">
<text class="update-tip">检测到新版本,确认后将开始下载安装包。</text>
<text class="update-tip">下载完成后会自动打开文件。</text>
</view>
<view v-if="isDownloadingUpdate" class="update-progress-section">
<view class="update-progress-head">
<text class="update-progress-text">正在下载更新</text>
<text class="update-progress-text">{{ updateDownloadProgress }}%</text>
</view>
<view class="update-progress-bar">
<view class="update-progress-inner" :style="{ width: updateDownloadProgress + '%' }"></view>
</view>
</view>
<text v-if="updateErrorMessage" class="update-error">{{ updateErrorMessage }}</text>
</view>
<view class="update-actions">
<u-button
v-if="!isDownloadingUpdate"
plain
text="暂不更新"
@click="closeUpdateDialog"
></u-button>
<u-button
type="primary"
:loading="isDownloadingUpdate"
:disabled="isDownloadingUpdate"
:text="isDownloadingUpdate ? '下载中...' : '立即更新'"
@click="confirmUpdateDownload"
></u-button>
</view>
</view>
</view>
<!-- 消息提示 -->
<u-toast ref="uToast"></u-toast>
<u-notify ref="uNotify"></u-notify>
</view>
</template>
<script>
import {
setToken,
getToken
} from '@/core/utils/auth'
export default {
data() {
return {
bgStyle: '',
updateLogSeq: 0,
currentAppVersion: '',
showUpdateDialog: false,
isCheckingUpdate: false,
isDownloadingUpdate: false,
updateDownloadProgress: 0,
updateErrorMessage: '',
hasCheckedUpdate: false,
updateTask: null,
updateInfo: {
version: '',
file: '',
url: '',
sha256: '',
publishedAtUtc: ''
},
showLoginConfirm: false,
showPassword: false,
scanning: false,
deviceCode: '',
scanUuid: '',
currentDevice: null,
qrCodeTimer: null,
scanTimer: null,
loginData: {
deviceId: '',
deviceName: '',
loginType: '' // qrcode, broadcast, manual
},
loginForm: {
username: '',
password: ''
},
workbenchCode: '',
workbenchLogining: false, // wblc 登录请求防重入锁
workbenchInputFocus: false, // 工作台登录码输入框自动聚焦(从打包模式退出回来时)
showWorkbenchLogin: false, // 工作台登录码输入框显隐(隐藏入口:连续点击5次标题切换)
workbenchTitleTapCount: 0, // 系统标题连点计数(满5次切换工作台登录码输入框显隐)
autoEntering: false, // 自动进入打包模式防重入锁(检测到有效工作台 token 时直接进入 packMode)
}
},
onLoad() {
const storageBg = uni.getStorageSync("bg");
const bgUrl = storageBg || "/static/loginbg.jpg";
this.bgStyle = `--bg-url: url(${bgUrl})`;
this.logNonBuildInfo('登录页启动调试信息', {
nodeEnv: process.env.NODE_ENV,
platform: process.env.VUE_APP_PLATFORM || 'unknown'
});
this.scanning = true;
uni.hideTabBar();
this.$store.dispatch('broadcast/setCallbacks', {
onResult: this.handleBroadcastResult
});
this.$store.dispatch('broadcast/start');
this.updateLogSeq = 0;
this.logUpdateStep('onLoad -> 准备执行 checkForAppUpdate');
this.checkForAppUpdate();
},
onShow() {
this.scanning = true;
// 检测到本地残留有效工作台 token 时自动进入打包模式(无需在登录页点击跳转)
this.autoEnterPackMode();
// 每次回到本页(reLaunch 重建 / 从其它页面返回)都重新绑定最新回调并确保广播监听
this.$store.dispatch('broadcast/setCallbacks', {
onResult: this.handleBroadcastResult
});
this.$store.dispatch('broadcast/start');
// 诊断日志:真机复现时确认接收器是否在监听
this.$store.dispatch('broadcast/getStatus').then((status) => {
console.log('[Login][bcast] onShow 广播状态:', JSON.stringify(status));
});
// 兜底:reLaunch 往返时旧页面(如 packMode)onUnload 的 stop 可能晚于本页 start,
// 把刚注册的接收器注销掉;延迟复查,若未在监听则重新 start,确保二次扫码可用
setTimeout(() => {
this.$store.dispatch('broadcast/getStatus').then((status) => {
const listening = !!(status && (status.moduleActive || status.isListening));
if (!listening) {
console.warn('[Login][bcast] 广播未在监听,延迟重启接收器');
this.$store.dispatch('broadcast/start');
}
});
}, 1200);
// 从打包模式退出回来:自动聚焦可见的“工作台登录码”输入框,
// 枪扫内容(键盘模拟)直接落入该框,回车即登录,无需再手动点输入框
if (uni.getStorageSync('loginAutoFocusScan') == 1) {
uni.removeStorageSync('loginAutoFocusScan');
this.$nextTick(() => {
setTimeout(() => {
this.workbenchInputFocus = true;
console.log('[Login][focus] 已自动聚焦工作台登录码输入框');
}, 400);
});
}
},
onHide() {
this.$store.dispatch('broadcast/stop');
},
onUnload() {
this.$store.dispatch('broadcast/stop');
},
methods: {
logNonBuildInfo(message, payload) {
if (process.env.NODE_ENV === 'production') {
return;
}
if (typeof payload === 'undefined') {
console.log(`[non-build] ${message}`);
return;
}
console.log(`[non-build] ${message}`, payload);
},
logUpdateStep(step, payload) {
this.updateLogSeq += 1;
const seq = String(this.updateLogSeq).padStart(2, '0');
if (typeof payload === 'undefined') {
console.log(`[update][${seq}] ${step}`);
return;
}
console.log(`[update][${seq}] ${step}`, payload);
},
async checkForAppUpdate() {
this.logUpdateStep('checkForAppUpdate -> 开始执行');
if (this.hasCheckedUpdate || this.isCheckingUpdate) {
this.logUpdateStep('checkForAppUpdate -> 已检查过或正在检查,直接返回', {
hasCheckedUpdate: this.hasCheckedUpdate,
isCheckingUpdate: this.isCheckingUpdate
});
return;
}
if (typeof plus === 'undefined' || !plus.runtime) {
this.logUpdateStep('checkForAppUpdate -> 非 APP-PLUS 环境,跳过更新检查');
return;
}
this.hasCheckedUpdate = true;
this.isCheckingUpdate = true;
this.updateErrorMessage = '';
this.logUpdateStep('checkForAppUpdate -> 状态已置为检查中');
try {
this.logUpdateStep('checkForAppUpdate -> 并行获取当前版本和远端配置');
const [currentVersion, latestInfoRaw] = await Promise.all([
this.getCurrentAppVersion(),
this.fetchLatestVersionInfo()
]);
const latestInfo = this.normalizeLatestInfo(latestInfoRaw);
this.currentAppVersion = currentVersion;
this.logUpdateStep('checkForAppUpdate -> 已拿到版本信息', {
currentVersion,
latestVersion: latestInfo && latestInfo.version ? latestInfo.version : ''
});
this.logUpdateStep('checkForAppUpdate -> 标准化后的远端配置', latestInfo || {});
if (!latestInfo || !latestInfo.version || !latestInfo.url) {
this.logUpdateStep('checkForAppUpdate -> 远端配置缺少必要字段,结束', latestInfo || {});
return;
}
const isNewer = this.isVersionNewer(latestInfo.version, currentVersion);
this.logUpdateStep('checkForAppUpdate -> 版本比较完成', {
latestVersion: latestInfo.version,
currentVersion,
isNewer
});
if (!isNewer) {
this.logUpdateStep('checkForAppUpdate -> 远端版本不高于当前版本,不弹窗');
return;
}
this.updateInfo = {
version: String(latestInfo.version || '').trim(),
file: String(latestInfo.file || '').trim(),
url: String(latestInfo.url || '').trim(),
sha256: String(latestInfo.sha256 || '').trim(),
publishedAtUtc: String(latestInfo.publishedAtUtc || '').trim()
};
this.showUpdateDialog = true;
this.logUpdateStep('checkForAppUpdate -> 发现新版本,显示更新弹窗', this.updateInfo);
} catch (error) {
this.logUpdateStep('checkForAppUpdate -> 检查异常', error);
console.warn('[update] check failed:', error);
} finally {
this.isCheckingUpdate = false;
this.logUpdateStep('checkForAppUpdate -> 结束,isCheckingUpdate=false');
}
},
fetchLatestVersionInfo() {
this.logUpdateStep('fetchLatestVersionInfo -> 发起请求', {
url: 'http://dl.wms.gztbyc.com/pda/latest.json'
});
return new Promise((resolve, reject) => {
uni.request({
url: 'http://dl.wms.gztbyc.com/pda/latest.json',
method: 'GET',
timeout: 10000,
success: (res) => {
this.logUpdateStep('fetchLatestVersionInfo -> 请求成功', {
statusCode: res.statusCode
});
if (res.statusCode !== 200) {
this.logUpdateStep('fetchLatestVersionInfo -> 状态码异常,reject', {
statusCode: res.statusCode
});
reject(new Error(`更新配置获取失败: ${res.statusCode}`));
return;
}
try {
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
this.logUpdateStep('fetchLatestVersionInfo -> 配置解析成功', data || {});
resolve(data || {});
} catch (parseError) {
this.logUpdateStep('fetchLatestVersionInfo -> 配置解析失败', parseError);
reject(parseError);
}
},
fail: (error) => {
this.logUpdateStep('fetchLatestVersionInfo -> 请求失败', error);
reject(error || new Error('更新配置获取失败'));
}
});
});
},
normalizeLatestInfo(raw) {
const source = raw && typeof raw === 'object' ? raw : {};
const version = String(source.version || source.versionName || source.appVersion || '').trim();
const url = String(
source.url ||
source.downloadUrl ||
source.apkUrl ||
source.download_url ||
''
).trim();
const file = String(source.file || source.fileName || source.apkName || source.name || '').trim();
return {
...source,
version,
url,
file,
sha256: String(source.sha256 || source.md5 || '').trim(),
publishedAtUtc: String(source.publishedAtUtc || source.publishedAt || source.releaseTime || '').trim()
};
},
getCurrentAppVersion() {
this.logUpdateStep('getCurrentAppVersion -> 开始读取当前版本');
return new Promise((resolve) => {
if (typeof plus === 'undefined' || !plus.runtime) {
this.logUpdateStep('getCurrentAppVersion -> 非 APP-PLUS,返回空版本');
resolve('');
return;
}
try {
plus.runtime.getProperty(plus.runtime.appid, (info) => {
const version = String(info?.version || plus.runtime.version || '').trim();
this.logUpdateStep('getCurrentAppVersion -> 读取成功', {
version,
appid: plus.runtime.appid
});
resolve(version);
});
} catch (error) {
const fallbackVersion = String((typeof plus !== 'undefined' && plus.runtime && plus.runtime.version) || '').trim();
this.logUpdateStep('getCurrentAppVersion -> 读取异常,走兜底版本', {
fallbackVersion,
error
});
resolve(fallbackVersion);
}
});
},
isVersionNewer(latestVersion, currentVersion) {
const normalize = (version) => String(version || '')
.split('.')
.map(item => parseInt(item, 10) || 0);
const latest = normalize(latestVersion);
const current = normalize(currentVersion);
const maxLength = Math.max(latest.length, current.length);
for (let i = 0; i < maxLength; i++) {
const latestPart = latest[i] || 0;
const currentPart = current[i] || 0;
if (latestPart > currentPart) {
return true;
}
if (latestPart < currentPart) {
return false;
}
}
return false;
},
formatUpdateTime(value) {
if (!value) {
return '';
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return value;
}
const pad = (num) => String(num).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
},
closeUpdateDialog() {
if (this.isDownloadingUpdate) {
this.logUpdateStep('closeUpdateDialog -> 下载中,禁止关闭弹窗');
return;
}
this.showUpdateDialog = false;
this.updateErrorMessage = '';
this.logUpdateStep('closeUpdateDialog -> 用户取消更新,弹窗关闭');
},
confirmUpdateDownload() {
if (this.isDownloadingUpdate) {
this.logUpdateStep('confirmUpdateDownload -> 已在下载中,忽略重复点击');
return;
}
this.logUpdateStep('confirmUpdateDownload -> 用户确认更新,准备下载');
this.startUpdateDownload();
},
startUpdateDownload() {
this.logUpdateStep('startUpdateDownload -> 开始下载流程', {
url: this.updateInfo.url,
file: this.updateInfo.file
});
if (!this.updateInfo.url) {
this.updateErrorMessage = '未获取到下载地址';
this.logUpdateStep('startUpdateDownload -> 缺少下载地址,终止');
return;
}
this.isDownloadingUpdate = true;
this.updateDownloadProgress = 0;
this.updateErrorMessage = '';
const downloadTask = uni.downloadFile({
url: this.updateInfo.url,
success: (res) => {
this.updateTask = null;
this.logUpdateStep('startUpdateDownload -> 下载完成回调', {
statusCode: res.statusCode,
tempFilePath: res.tempFilePath
});
if (res.statusCode !== 200 || !res.tempFilePath) {
this.isDownloadingUpdate = false;
this.updateErrorMessage = '安装包下载失败';
this.logUpdateStep('startUpdateDownload -> 下载结果无效,终止');
return;
}
this.updateDownloadProgress = 100;
this.logUpdateStep('startUpdateDownload -> 下载成功,准备打开文件');
this.openDownloadedFile(res.tempFilePath);
},
fail: (error) => {
this.updateTask = null;
this.isDownloadingUpdate = false;
this.updateErrorMessage = error?.errMsg || '安装包下载失败';
this.logUpdateStep('startUpdateDownload -> 下载失败', error);
}
});
this.updateTask = downloadTask;
this.logUpdateStep('startUpdateDownload -> downloadTask 已创建');
if (downloadTask && typeof downloadTask.onProgressUpdate === 'function') {
downloadTask.onProgressUpdate((progressEvent) => {
this.updateDownloadProgress = Number(progressEvent.progress || 0);
this.logUpdateStep('startUpdateDownload -> 下载进度', {
progress: this.updateDownloadProgress,
totalBytesWritten: progressEvent.totalBytesWritten,
totalBytesExpectedToWrite: progressEvent.totalBytesExpectedToWrite
});
});
} else {
this.logUpdateStep('startUpdateDownload -> 当前环境不支持进度回调');
}
},
openDownloadedFile(filePath) {
this.logUpdateStep('openDownloadedFile -> 尝试打开下载文件', {
filePath
});
if (typeof plus === 'undefined' || !plus.runtime || typeof plus.runtime.openFile !== 'function') {
this.updateTask = null;
this.isDownloadingUpdate = false;
this.updateErrorMessage = '当前环境不支持打开安装包';
this.logUpdateStep('openDownloadedFile -> 环境不支持 plus.runtime.openFile');
return;
}
try {
plus.runtime.openFile(filePath, {}, () => {
this.updateTask = null;
this.isDownloadingUpdate = false;
this.updateErrorMessage = '';
this.showUpdateDialog = false;
this.logUpdateStep('openDownloadedFile -> 文件打开成功,更新流程完成');
}, (error) => {
this.updateTask = null;
this.isDownloadingUpdate = false;
this.updateErrorMessage = error?.message || '文件已下载,但打开失败';
this.logUpdateStep('openDownloadedFile -> 文件打开失败', error);
});
} catch (error) {
this.updateTask = null;
this.isDownloadingUpdate = false;
this.updateErrorMessage = error?.message || '文件已下载,但打开失败';
this.logUpdateStep('openDownloadedFile -> 调用异常', error);
}
},
togglePasswordVisibility() {
this.showPassword = !this.showPassword;
},
handleSystemTitleTap() {
// 隐藏入口:连续点击标题 5 次,切换工作台登录码输入框的显示/隐藏
this.workbenchTitleTapCount += 1;
if (this.workbenchTitleTapCount >= 5) {
this.workbenchTitleTapCount = 0;
this.showWorkbenchLogin = !this.showWorkbenchLogin;
if (this.showWorkbenchLogin) {
console.log('[Login][hidden] 连续点击5次标题,工作台登录码输入框已显示');
// 显示后自动聚焦登录码输入框,便于扫码枪/键盘直接输入
this.$nextTick(() => {
setTimeout(() => {
this.workbenchInputFocus = true;
}, 300);
});
} else {
console.log('[Login][hidden] 连续点击5次标题,工作台登录码输入框已隐藏');
this.workbenchInputFocus = false;
}
}
},
// 自动进入打包模式:登录页检测到本地残留有效工作台 token(workbenchToken 非空)时,
// 无需手动点击,自动进入打包模式页(packMode 内部会调用 getWorkbenchInfo 刷新工作台信息)
autoEnterPackMode() {
if (this.autoEntering) return;
const token = String(uni.getStorageSync('workbenchToken') || '').trim();
if (!token) return;
this.autoEntering = true;
setTimeout(() => {
// 延迟后再次校验(期间可能已被退出流程清除)
const current = String(uni.getStorageSync('workbenchToken') || '').trim();
if (!current) {
this.autoEntering = false;
return;
}
// 工作台会话判定依赖 主 token === workbenchToken;
// 若主 token 被普通账号登录覆盖或被登出清空,用本地残留的有效工作台 token 恢复工作台会话,
// 否则路由守卫会把 packMode 视为未登录并重定向回登录页。
const mainToken = String(uni.getStorageSync('token') || '').trim();
if (mainToken !== current) {
console.log('[Login][auto] 主 token 与工作台 token 不一致,用本地工作台 token 恢复会话');
setToken(current);
}
console.log('[Login][auto] 检测到有效工作台 token,自动进入打包模式');
uni.reLaunch({
url: '/pages/packing/packMode',
fail: () => {
this.autoEntering = false;
}
});
}, 500);
},
handleWorkbenchInputConfirm() {
// 工作台登录码输入框回车 / 枪扫内容(键盘模拟)落入该框后的统一入口:
// 清空后交给 handleBroadcastResult 自动识别(wblc 工作台码 / 工牌 Base64)
const code = String(this.workbenchCode || '').trim();
if (!code) {
console.log('[Login][scan] 工作台输入框内容为空,忽略');
return;
}
this.workbenchCode = '';
console.log('[Login][scan] 工作台输入框收到内容 code len=', code.length, ' head=', code.slice(0, 12));
this.handleBroadcastResult({ data: code, source: 'keyboard' });
},
decodeBase64Text(value) {
if (!value) return '';
if (typeof atob !== 'function') return '';
const normalized = String(value).replace(/-/g, '+').replace(/_/g, '/');
const binary = atob(normalized);
try {
return decodeURIComponent(Array.prototype.map.call(binary, char => {
const code = char.charCodeAt(0).toString(16).padStart(2, '0');
return `%${code}`;
}).join(''));
} catch (e) {
return binary;
}
},
isBase64Text(value) {
if (!value) return false;
const text = String(value).trim().replace(/\s/g, '');
// 允许标准/URL安全Base64
return /^[A-Za-z0-9+/=_-]+$/.test(text) && text.length % 4 === 0;
},
parseScanCodeStrict(scanText) {
const raw = String(scanText || '').trim();
if (!raw) {
return {
ok: false,
error: '扫描内容为空',
uuid: ''
};
}
if (!this.isBase64Text(raw)) {
return {
ok: false,
error: '扫描内容不是Base64',
uuid: ''
};
}
const decoded = this.decodeBase64Text(raw);
if (!decoded) {
return {
ok: false,
error: 'Base64反序列化失败',
uuid: ''
};
}
let obj;
try {
obj = JSON.parse(decoded);
} catch (e) {
return {
ok: false,
error: '反序列化后不是JSON字符串',
uuid: ''
};
}
const uuid = String(obj?.uuid || '').trim();
if (!uuid) {
return {
ok: false,
error: 'JSON中缺少uuid键',
uuid: ''
};
}
return {
ok: true,
error: '',
uuid
};
},
parseScanUuid(scanText) {
if (!scanText) {
return '';
}
const text = String(scanText).trim();
try {
const jsonObj = JSON.parse(text);
if (jsonObj && jsonObj.uuid) {
return String(jsonObj.uuid).trim();
}
} catch (e) {}
try {
const decoded = this.decodeBase64Text(text);
if (decoded) {
const decodedObj = JSON.parse(decoded);
if (decodedObj && decodedObj.uuid) {
return String(decodedObj.uuid).trim();
}
}
} catch (e) {}
return text;
},
normalizeUniScanResult(scanResult) {
if (!scanResult) {
return '';
}
if (typeof scanResult === 'string') {
return scanResult.trim();
}
if (typeof scanResult.result === 'string') {
return scanResult.result.trim();
}
if (Array.isArray(scanResult.result)) {
const firstResult = scanResult.result.find(item => item);
if (typeof firstResult === 'string') {
return firstResult.trim();
}
if (firstResult && typeof firstResult.data === 'string') {
return firstResult.data.trim();
}
}
if (typeof scanResult.data === 'string') {
return scanResult.data.trim();
}
return '';
},
handleManualScan() {
uni.scanCode({
onlyFromCamera: false,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const rawCode = this.normalizeUniScanResult(res);
if (!rawCode) {
uni.showToast({
title: '未识别到有效内容',
icon: 'none'
});
return;
}
this.handleBroadcastResult({
data: rawCode,
source: 'uni.scanCode'
});
},
fail: (error) => {
const errMsg = String(error?.errMsg || '').toLowerCase();
if (errMsg.includes('cancel')) {
return;
}
uni.showToast({
title: '扫描失败,请重试',
icon: 'none'
});
}
});
},
extractToken(payload) {
if (!payload || typeof payload !== 'object') {
return '';
}
const keys = ['token', 'access_token', 'accessToken', 'jwt', 'jwtToken'];
for (let i = 0; i < keys.length; i++) {
const raw = payload[keys[i]];
if (raw) {
const text = String(raw).trim();
return text.startsWith('Bearer ') ? text.substring(7).trim() : text;
}
}
for (const key in payload) {
if (payload[key] && typeof payload[key] === 'object') {
const nestedToken = this.extractToken(payload[key]);
if (nestedToken) {
return nestedToken;
}
}
}
return '';
},
async loginByCode(uuid) {
const res = await this.$http('user.loginByCode', {
uuid: String(uuid).trim()
});
if (res?.flag === 'failure') {
throw new Error(res?.message || '工牌认证登录失败');
}
const token = this.extractToken(res);
if (token) {
setToken(token);
}
if (!getToken()) {
throw new Error('登录成功但未返回token');
}
},
async Login() {
try {
await this.$store.dispatch('login', this.loginForm)
uni.switchTab({ url: '/pages/index/index' })
} catch (error) {
uni.showToast({
title: error?.msg || error?.message || '登录失败',
icon: 'none'
})
}
},
async confirmLogin() {
try {
const code = String(this.deviceCode || '').trim()
const uuid = String(this.scanUuid || this.parseScanUuid(code) || '').trim()
if (!code || !uuid) {
throw new Error('请先扫描有效工牌')
}
await this.$store.dispatch('loginByCode', { code })
uni.switchTab({ url: '/pages/index/index' })
} catch (error) {
this.scanning = true;
this.deviceCode = '';
this.scanUuid = '';
this.currentDevice = null;
this.$store.dispatch('broadcast/resume');
uni.showToast({
title: error?.msg || error?.message || '工牌认证登录失败',
icon: 'none'
})
}
},
isWorkbenchLoginCode(text) {
const code = String(text || '').trim();
// 工作台登录码:前缀 wblc + 随机段,共 64 位(字母数字)
return /^wblc[A-Za-z0-9]+$/i.test(code) && code.length === 64;
},
handleWorkbenchLogin() {
const code = String(this.workbenchCode || '').trim();
if (!this.isWorkbenchLoginCode(code)) {
uni.showToast({ title: '请输入有效的工作台登录码(wblc 开头,共64位)', icon: 'none' });
return;
}
this.loginByWorkbenchCode(code);
},
async loginByWorkbenchCode(loginCode) {
try {
const code = String(loginCode || '').trim();
// 防重入:登录请求进行中,忽略重复的广播/点击触发
if (this.workbenchLogining) {
console.log('[Login][wblc] 登录进行中,忽略重复触发');
return;
}
this.workbenchLogining = true;
console.log('[Login][wblc] 开始工作台登录码登录, head=', code.slice(0, 6), ' len=', code.length);
// 登录请求期间暂停广播,避免期间重复扫码触发并发登录;
// 成功跳转 packMode 后由页面卸载自然 stop,失败时在 catch 中 resume 恢复
this.$store.dispatch('broadcast/stop');
// index.LoginWorkbenchByCode(免登录、免鉴权):校验工作台登录码,直接返回工作台 token 与身份
const loginRes = await this.$http('index.LoginWorkbenchByCode', {
loginCode: code
});
if (loginRes?.flag === 'failure' || Number(loginRes?.code) === 400 || Number(loginRes?.code) === 403) {
throw new Error(loginRes?.message || '工作台不存在或登录码无效');
}
const loginData = (loginRes && typeof loginRes === 'object' && loginRes.data && typeof loginRes.data === 'object')
? loginRes.data
: loginRes;
const token = String(loginData?.token || '').trim() || this.extractToken(loginData);
let workbenchId = loginData?.workbench_id ?? loginData?.workbenchId ?? loginData?.id ?? '';
let workbenchName = String(loginData?.name || '').trim();
if (!token) {
throw new Error('工作台登录成功但未返回token');
}
// 该 token 即最终工作台 token(后端已直接返回,无需再走绑定会话)
setToken(token);
// 用工作台 token 拉取完整工作台信息(含 warehouse_id/status/type 等)
// 只有 getWorkbenchInfo 返回成功后才会进入打包模块;失败则抛错中断
const infoRes = await this.$http('workbench.getWorkbenchInfo', { token });
if (infoRes?.flag === 'failure' || Number(infoRes?.code) === 400 || Number(infoRes?.code) === 403) {
throw new Error(infoRes?.message || '获取工作台信息失败');
}
const infoData = (infoRes && typeof infoRes === 'object' && infoRes.data && typeof infoRes.data === 'object')
? infoRes.data
: infoRes;
if (!infoData || typeof infoData !== 'object') {
throw new Error('获取工作台信息失败:返回数据无效');
}
const workbenchDetail = {
id: infoData?.workbench_id ?? infoData?.workbenchId ?? infoData?.id ?? workbenchId,
name: String(infoData?.name || workbenchName),
warehouse_id: infoData?.warehouse_id ?? infoData?.warehouseId ?? '',
status: infoData?.status ?? '',
type: String(infoData?.type || ''),
remark: String(infoData?.remark || ''),
token
};
workbenchId = workbenchDetail.id;
workbenchName = workbenchDetail.name;
uni.setStorageSync('workbenchInfo', workbenchDetail);
uni.setStorageSync('workbenchToken', token);
uni.showToast({ title: '工作台登录成功', icon: 'success' });
// 免登录成功:不进主控,直接进入打包模式占位页
// 注意:URL 仅传 workbenchId,中文 workbenchName 通过 storage(workbenchInfo)传递,避免真机 URL 中文乱码
const query = `workbenchId=${encodeURIComponent(String(workbenchId))}`;
setTimeout(() => {
uni.reLaunch({ url: `/pages/packing/packMode?${query}` });
}, 600);
} catch (error) {
this.scanning = true;
this.workbenchLogining = false;
this.deviceCode = '';
this.scanUuid = '';
this.currentDevice = null;
// 登录失败:恢复广播监听,允许再次扫码
this.$store.dispatch('broadcast/resume');
console.error('[Login][wblc] 工作台登录失败:', error?.msg || error?.message || error);
uni.showToast({
title: error?.msg || error?.message || '工作台登录失败',
icon: 'none'
})
}
},
handleBroadcastResult(result) {
console.log('[Login][bcast] handleBroadcastResult 触发 scanning=', this.scanning, ' data=', result && result.data);
if (!this.scanning || !result || !result.data) return;
const rawCode = String(result.data || '').trim(); // 扫描原文
console.log('[Login][bcast] rawCode len=', rawCode.length, ' head=', rawCode.slice(0, 12));
// 工作台登录码(wblc 前缀,共 64 位)→ 免登录直达打包模式,不进主控
if (this.isWorkbenchLoginCode(rawCode)) {
console.log('[Login][bcast] 判定为工作台登录码 -> loginByWorkbenchCode');
this.loginByWorkbenchCode(rawCode);
return;
}
console.log('[Login][bcast] 非工作台登录码,按工牌流程处理');
const parsed = this.parseScanCodeStrict(rawCode); // 仅用于校验与展示
if (!parsed.ok) {
this.scanning = true;
this.deviceCode = '';
this.scanUuid = '';
this.currentDevice = null;
this.$store.dispatch('broadcast/resume');
uni.showToast({ title: parsed.error || '扫码数据不合法', icon: 'none' });
return;
}
const uuid = parsed.uuid;
this.deviceCode = rawCode; // code = 扫描字符串
this.scanUuid = uuid;
this.currentDevice = {
deviceId: uuid,
deviceName: `工牌-${uuid}`
};
this.scanning = false;
uni.showToast({ title: '工牌扫描成功', icon: 'success' });
// 自动登录
this.confirmLogin();
},
}
}
</script>
<style lang="scss" scoped>
.login-container {
width: 100vw;
height: 100vh;
margin: 0 auto;
background-image: var(--bg-url, url('@/static/loginbg.jpg'));
background-size: cover;
background-position: center;
background-repeat: no-repeat;
display: flex;
align-items: center;
justify-content: center;
position: relative;
flex-direction: row;
flex-wrap: wrap;
}
.form_box {
width: 80%;
margin: 0 auto;
background: rgba(255, 255, 255, 0.95);
border-radius: 20rpx;
padding: 60rpx 40rpx;
backdrop-filter: blur(10px);
box-sizing: border-box;
}
.update-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.48);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
padding: 32rpx;
box-sizing: border-box;
}
.update-dialog {
width: 100%;
max-width: 680rpx;
background: #fff;
border-radius: 24rpx;
padding: 36rpx;
box-sizing: border-box;
box-shadow: 0 24rpx 80rpx rgba(0, 0, 0, 0.18);
}
.update-header {
display: flex;
flex-direction: column;
gap: 10rpx;
margin-bottom: 28rpx;
}
.update-title {
font-size: 36rpx;
font-weight: 600;
color: #222;
}
.update-version {
font-size: 24rpx;
color: #5c6b77;
}
.update-body {
display: flex;
flex-direction: column;
gap: 20rpx;
}
.update-row {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 20rpx;
}
.update-label {
font-size: 26rpx;
color: #86909c;
flex-shrink: 0;
}
.update-value {
font-size: 26rpx;
color: #333;
text-align: right;
word-break: break-all;
}
.update-tip-box {
background: #f6f9ff;
border-radius: 16rpx;
padding: 24rpx;
display: flex;
flex-direction: column;
gap: 12rpx;
}
.update-tip {
font-size: 26rpx;
line-height: 1.6;
color: #4e5969;
}
.update-progress-section {
margin-top: 8rpx;
}
.update-progress-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 14rpx;
}
.update-progress-text {
font-size: 26rpx;
color: #333;
}
.update-progress-bar {
height: 18rpx;
background: #eef1f5;
border-radius: 999rpx;
overflow: hidden;
}
.update-progress-inner {
height: 100%;
background: linear-gradient(90deg, #2979ff, #19be6b);
border-radius: 999rpx;
transition: width 0.2s ease;
}
.update-error {
font-size: 24rpx;
color: #fa3534;
line-height: 1.6;
}
.update-actions {
display: flex;
gap: 20rpx;
margin-top: 32rpx;
}
.update-actions :deep(.u-button) {
flex: 1;
}
.header-section {
text-align: left;
margin-bottom: 60rpx;
.system-title {
display: block;
text-align: center;
width: 100%;
font-size: 40rpx;
font-weight: 600;
color: #333;
margin-bottom: 20rpx;
}
}
.login-methods {
display: flex;
flex-direction: column;
gap: 30rpx;
}
.method-card {
background: #f8f9fa;
border-radius: 16rpx;
padding: 40rpx 30rpx;
text-align: center;
position: relative;
&:active {
background: #e9ecef;
}
.method-icon {
margin-bottom: 20rpx;
}
.method-title {
display: block;
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-bottom: 10rpx;
}
.method-desc {
display: block;
font-size: 24rpx;
color: #666;
}
.scan-status {
margin-top: 20rpx;
}
}
.direct-login-card {
text-align: left;
.direct-login-form {
margin-top: 20rpx;
}
.password-input-wrap {
position: relative;
.password-toggle-icon {
position: absolute;
left: 0;
top: 18rpx;
z-index: 2;
}
}
}
.scan-login-card {
display: flex;
align-items: center;
justify-content: center;
background: transparent;
&:active {
background: transparent;
}
.method-icon {
margin-bottom: 0;
margin-right: 16rpx;
display: flex;
align-items: center;
}
.method-desc {
margin: 0 40rpx 0 0;
}
.scan-login-content {
display: flex;
align-items: center;
}
}
.device-status {
margin-top: 40rpx;
.status-card {
background: #e7f3ff;
border-radius: 12rpx;
padding: 30rpx;
display: flex;
justify-content: space-between;
align-items: center;
.device-info {
flex: 1;
.device-name {
display: block;
font-size: 28rpx;
font-weight: 600;
color: #2979ff;
margin-bottom: 8rpx;
}
.device-id {
display: block;
font-size: 24rpx;
color: #666;
}
}
}
}
// 弹窗样式
.qr-popup, .input-popup {
width: 600rpx;
background: white;
border-radius: 20rpx;
padding: 40rpx;
.popup-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 40rpx;
.popup-title {
font-size: 36rpx;
font-weight: 600;
color: #333;
}
}
.qr-container {
text-align: center;
.qr-tip {
font-size: 26rpx;
color: #666;
}
}
.popup-footer {
text-align: center;
margin-top: 30rpx;
.refresh-text {
color: #2979ff;
font-size: 26rpx;
}
}
.input-container {
padding: 20rpx 0;
}
}
</style>