WMS_PDA/components/AppUpdateDialog/AppUpdateDialog.vue
2026-08-12 14:55:47 +08:00

565 lines
16 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 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>
</template>
<script>
/**
* AppUpdateDialog 版本更新弹窗组件
* 复用登录页 checkForAppUpdate 的完整更新流程:
* 读取远端 latest.json → 比较版本 → 弹窗 → 下载 APK → plus.runtime.openFile 调用系统安装器
* 使用方法:
* <app-update-dialog ref="appUpdateDialog"></app-update-dialog>
* this.$refs.appUpdateDialog.checkForAppUpdate(true) // force=true 每次强制重新检查
*/
export default {
name: 'AppUpdateDialog',
data() {
return {
updateLogSeq: 0,
// 远端更新配置地址。注意:当前为 http 明文,Android 9+ 默认禁止明文流量,
// 若真机请求 latest.json 失败,建议与主接口(https://api.youzixy.com)保持一致改用 https。
updateConfigUrl: 'http://dl.wms.gztbyc.com/pda/latest.json',
currentAppVersion: '',
showUpdateDialog: false,
isCheckingUpdate: false,
isDownloadingUpdate: false,
updateDownloadProgress: 0,
updateErrorMessage: '',
hasCheckedUpdate: false,
updateTask: null,
updateInfo: {
version: '',
file: '',
url: '',
sha256: '',
publishedAtUtc: ''
}
};
},
methods: {
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);
},
/**
* 检查更新并弹窗
* @param {Boolean} force 为 true 时忽略 hasCheckedUpdate,强制重新检查远端配置
* @returns {Promise<Boolean>} 是否发现新版本并弹窗;检查失败时返回 false 且 updateErrorMessage 有值
*/
async checkForAppUpdate(force = false) {
this.logUpdateStep('checkForAppUpdate -> 开始执行', { force });
if (force) {
this.hasCheckedUpdate = false;
}
if (this.hasCheckedUpdate || this.isCheckingUpdate) {
this.logUpdateStep('checkForAppUpdate -> 已检查过或正在检查,直接返回', {
hasCheckedUpdate: this.hasCheckedUpdate,
isCheckingUpdate: this.isCheckingUpdate
});
return false;
}
if (typeof plus === 'undefined' || !plus.runtime) {
this.logUpdateStep('checkForAppUpdate -> 非 APP-PLUS 环境,跳过更新检查');
return false;
}
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 (!currentVersion) {
this.logUpdateStep('checkForAppUpdate -> 未获取到当前应用版本,无法比较', { currentVersion });
this.updateErrorMessage = '获取当前应用版本失败';
return false;
}
if (!latestInfo || !latestInfo.version || !latestInfo.url) {
this.logUpdateStep('checkForAppUpdate -> 远端配置缺少必要字段,结束', latestInfo || {});
return false;
}
const isNewer = this.isVersionNewer(latestInfo.version, currentVersion);
this.logUpdateStep('checkForAppUpdate -> 版本比较完成', {
latestVersion: latestInfo.version,
currentVersion,
isNewer
});
if (!isNewer) {
this.logUpdateStep('checkForAppUpdate -> 远端版本不高于当前版本,不弹窗');
return false;
}
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);
return true;
} catch (error) {
this.logUpdateStep('checkForAppUpdate -> 检查异常', error);
console.warn('[update] check failed:', error);
this.updateErrorMessage = error?.message || '更新检查失败';
return false;
} finally {
this.isCheckingUpdate = false;
this.logUpdateStep('checkForAppUpdate -> 结束,isCheckingUpdate=false');
}
},
fetchLatestVersionInfo() {
this.logUpdateStep('fetchLatestVersionInfo -> 发起请求', {
url: this.updateConfigUrl
});
return new Promise((resolve, reject) => {
uni.request({
url: this.updateConfigUrl,
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);
const message = error?.errMsg || error?.message || '更新配置获取失败';
reject(new Error(message));
}
});
});
},
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;
}
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
this.logUpdateStep('getCurrentAppVersion -> getProperty 回调超时,返回空版本');
resolve('');
}, 3000);
const done = (version) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(version);
};
try {
// 注意:plus.runtime.version 是 HTML5+ 运行时版本(如 3.x),不是应用版本,
// 数值可能比应用版本大,若用作比较会导致「永远认为已是最新、不弹窗」。
// 因此这里只取 info.version(manifest 的 versionName),读不到就返回空。
plus.runtime.getProperty(plus.runtime.appid, (info) => {
const version = String(info?.version || '').trim();
this.logUpdateStep('getCurrentAppVersion -> 读取成功', {
version,
appid: plus.runtime.appid
});
done(version);
});
} catch (error) {
this.logUpdateStep('getCurrentAppVersion -> 读取异常,返回空版本', { error });
done('');
}
});
},
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);
}
}
}
};
</script>
<style lang="scss" scoped>
.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;
}
</style>