Files
device-voice-h5/pages/index/index.vue
邹进 c11d1881ef
Some checks failed
构建并部署前端到测试环境 / build-and-deploy (push) Has been cancelled
fix: 沉默期提醒每次登录都弹,有未支付延期订单时提示去支付或作废
- 频率从每天一次改为每次登录一次:重新登录后会再次提醒,同一次登录内回首页不重复
- 已过期套餐有未支付延期订单时,弹窗提示继续支付或作废
2026-11-07 21:04:12 +09:00

1143 lines
35 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="container">
<UserInfoCard :currentCardNo="currentCardNo" :deviceInfo="deviceInfo" :onlineStatus="onlineStatus"
:isDevice="userInfo.isDevice" :networkStatus="deviceInfo.network_status"
:isExpiring="deviceInfo.isExpiring" :expiryDays="deviceInfo.expiryDays" @renew="startHomepageRenewal" />
<DeviceStatusCard v-if="userInfo.isDevice" :deviceInfo="deviceInfo" :isRealName="isRealName"
:isDevice="userInfo.isDevice" @authentication="enterDetail('authentication')" />
<!-- <VoiceCard v-if="!userInfo.isDevice" :voiceStats="voiceStats" :dateRangeText="dateRangeText"
@openDatePicker="openDateRangePicker" /> -->
<TrafficCard :assetInfo="assetStore.state.assetInfo" />
<!-- <WhitelistCard v-if="!userInfo.isDevice" :whitelistData="whitelistData" @refresh="refreshWhitelist"
@add="showAddWhitelistDialog" @showSms="showSmsCodeDialog" /> -->
<WifiCard v-if="userInfo.isDevice" :deviceInfo="deviceInfo" @modify="modifyWifi"
@copy-config="copyWifiConfig" />
<FunctionCard :realNameStatus="realNameStatus" :assetPhoneBound="userStore.state.assetPhoneBound"
:customerPhone="userStore.state.customerPhone"
:isDevice="userInfo.isDevice" :walletBalance="deviceInfo.walletBalance" :unreadCount="notificationUnreadCount"
@enter="enterDetail" @sync="onSync">
<!-- 修改配置弹窗 -->
<up-popup :show="showModifyWifi" mode="center" @close="showModifyWifi=false">
<view class="wifi-popup">
<view class="title mb-md">修改配置</view>
<view class="flex-col-g20">
<view class="flex-col-g8">
<label class="caption">名称:</label>
<up-input placeholder="WIFI名称" class="wifi-input" v-model="wifi_info.ssid" />
</view>
<view class="flex-col-g8">
<label class="caption">密码:</label>
<up-input placeholder="WIFI密码" class="wifi-input" v-model="wifi_info.pwd" />
</view>
</view>
<view class="btn-group mt-20">
<button class="btn-apple btn-secondary" @tap="showModifyWifi=false">取消</button>
<button class="btn-apple btn-primary" @tap="confirmModify">确定</button>
</view>
</view>
</up-popup>
<!-- 重启设备 -->
<up-modal title="您确定要重启设备吗?" :show="restartShow" showCancelButton @confirm="YesRestart"
@cancel="restartShow=false" />
<!-- 恢复出厂设置 -->
<up-modal title="您确定要恢复出厂设置吗?" :show="recoverShow" showCancelButton @confirm="YesRecover"
@cancel="recoverShow=false" />
<!-- 退出登录 -->
<up-modal title="您确定要退出登录吗?" :show="logoutShow" showCancelButton @confirm="YesLogout"
@cancel="logoutShow=false" />
<!-- 添加白名单弹窗 -->
<up-popup :show="showAddWhitelist" mode="center" @close="showAddWhitelist=false">
<view class="wifi-popup">
<view class="title mb-md">添加白名单</view>
<view class="flex-col-g20">
<view class="flex-col-g8">
<label class="caption">姓名:</label>
<up-input placeholder="请输入姓名" border="surround" v-model="whitelistForm.name" />
</view>
<view class="flex-col-g8">
<label class="caption">手机号:</label>
<up-input placeholder="请输入手机号" border="surround" v-model="whitelistForm.phone" />
</view>
</view>
<view class="btn-group mt-20">
<button class="btn-apple btn-secondary" @tap="showAddWhitelist=false">取消</button>
<button class="btn-apple btn-primary" @tap="confirmAddWhitelist">确定</button>
</view>
</view>
</up-popup>
<!-- 上传短信码弹窗 -->
<up-popup :show="showSmsCode" mode="center" @close="showSmsCode=false">
<view class="wifi-popup">
<view class="title mb-md">上传短信验证码</view>
<view class="flex-col-g20">
<view class="flex-col-g8">
<label class="caption">手机号: {{smsCodePhone}}</label>
</view>
<view class="flex-col-g8">
<label class="caption">验证码:</label>
<up-input placeholder="请输入短信验证码" border="surround" v-model="smsCode" />
</view>
</view>
<view class="btn-group mt-20">
<button class="btn-apple btn-secondary" @tap="showSmsCode=false">取消</button>
<button class="btn-apple btn-primary" @tap="confirmUploadSmsCode">确定</button>
</view>
</view>
</up-popup>
</FunctionCard>
<view class="bottom-spacer"></view>
<ExpiryReminderPopup v-if="visibleExpiryReminder" :reminder="visibleExpiryReminder"
@close="closeExpiryReminder" @renew="renewFromExpiryReminder" />
<SilenceReminderPopup v-if="silenceReminderShow && silenceReminder" :reminder="silenceReminder"
@close="closeSilenceReminder" @action="openSilenceReminderAction" />
<NotificationPopup :show="notificationPopupShow" :items="notificationItems"
:current="notificationPopupCurrent" @change="onNotificationChange" @close="closeNotificationPopup"
@renew="startHomepageRenewal" />
<RenewalPaymentPopup ref="renewalPopupRef" :identifier="userStore.state.identifier"
paymentRefreshTarget="home" @completed="loadAssetInfo" @visibility-change="onRenewalVisibilityChange" />
<PopupCandidate v-if='popupCandidateShow' page='home' :identifier='userStore.state.identifier'
@close='onPopupCandidateClose' />
<!-- 日期选择器弹窗 -->
<up-datetime-picker v-if="!userInfo.isDevice" :show="showStartDatePicker" v-model="startDateTimestamp"
mode="date" @confirm="onStartDateConfirm" @cancel="showStartDatePicker=false"
@close="showStartDatePicker=false"></up-datetime-picker>
<up-datetime-picker v-if="!userInfo.isDevice" :show="showEndDatePicker" v-model="endDateTimestamp" mode="date"
@confirm="onEndDateConfirm" @cancel="showEndDatePicker=false"
@close="showEndDatePicker=false"></up-datetime-picker>
<FloatingButton @tap="connectKF" />
</view>
</template>
<script setup>
import {
ref,
reactive,
onMounted,
computed,
watch
} from 'vue';
import { onShow, onHide } from '@dcloudio/uni-app';
import UserInfoCard from '@/components/UserInfoCard.vue';
import DeviceStatusCard from '@/components/DeviceStatusCard.vue';
import VoiceCard from '@/components/VoiceCard.vue';
import TrafficCard from '@/components/TrafficCard.vue';
import WhitelistCard from '@/components/WhitelistCard.vue';
import WifiCard from '@/components/WifiCard.vue';
import FunctionCard from '@/components/FunctionCard.vue';
import FloatingButton from '@/components/FloatingButton.vue';
import NotificationPopup from '@/components/NotificationPopup.vue';
import ExpiryReminderPopup from '@/components/ExpiryReminderPopup.vue';
import SilenceReminderPopup from '@/components/SilenceReminderPopup.vue';
import RenewalPaymentPopup from '@/components/RenewalPaymentPopup.vue';
import PopupCandidate from '@/components/PopupCandidate.vue';
import {
assetApi,
deviceApi,
hasActiveOrPendingPackage,
notificationApi,
packageSilenceApi
} from '@/api/index.js';
import {
useUserStore,
useAssetStore
} from '@/store/index.js';
import { consumePendingPaymentRefresh, PAYMENT_REFRESH_TARGETS } from '@/utils/payment.js';
import { getSessionContext, isCurrentSession } from '@/utils/session-context.js';
import { getShanghaiDay } from '@/utils/expiry-reminder.js';
import { pickSilenceReminder, silenceReminderKey } from '@/utils/silence.js';
const userStore = useUserStore();
const assetStore = useAssetStore();
const homeActive = ref(false);
const shownExpiryReminder = ref(null);
const awaitingHomeReminders = ref(false);
const renewalOpening = ref(false);
const renewalVisible = ref(false);
let notificationFallbackPending = false;
let notificationQueued = false;
let homeEntryId = 0;
const visibleExpiryReminder = computed(() => {
const entry = shownExpiryReminder.value;
return homeActive.value && entry && isCurrentSession(entry) && entry.day === getShanghaiDay()
? entry.reminder : null;
});
const showPendingExpiryReminder = () => {
const entry = assetStore.state.expiryReminder;
if (!homeActive.value || awaitingHomeReminders.value || renewalOpening.value || renewalVisible.value || popupCandidateShow.value || notificationPopupShow.value ||
silenceReminderShow.value || visibleExpiryReminder.value || !entry || entry.shown || !isCurrentSession(entry) || entry.day !== getShanghaiDay()) return;
shownExpiryReminder.value = { ...entry };
assetStore.markExpiryReminderShown();
};
const closeExpiryReminder = (resumeQueue = true) => {
shownExpiryReminder.value = null;
assetStore.dismissExpiryReminder();
if (resumeQueue) advanceHomePopupQueue();
};
// 沉默期提醒:首页按"临期提醒 → 沉默期提醒 → 站内通知"的顺序依次弹出,同一资产同一笔套餐每天最多一次。
const silenceReminder = ref(null);
const silenceReminderShow = ref(false);
let silenceReminderIdentifier = '';
const loadSilenceReminder = async (entryId) => {
const identifier = String(userStore.state.identifier || '').trim();
silenceReminder.value = null;
if (!identifier) return;
try {
const data = await assetApi.getPackageHistory(identifier, 1, 20, { status: 0 });
if (entryId !== homeEntryId || !homeActive.value || identifier !== String(userStore.state.identifier || '').trim()) return;
const reminder = pickSilenceReminder(data?.items);
if (!reminder || uni.getStorageSync(silenceReminderKey(identifier, reminder, getSessionContext().token))) return;
// 已过期的套餐再查一次延期资格:有未支付的延期订单时,弹窗改为提醒去支付或作废
if (reminder.kind === 'expired') {
try {
const eligibility = await packageSilenceApi.getEligibility(reminder.packageUsageId);
if (eligibility?.pending_order_no) reminder.pendingOrderNo = eligibility.pending_order_no;
} catch (error) {
// 资格查询失败不影响提醒本身
}
}
if (entryId !== homeEntryId || !homeActive.value || identifier !== String(userStore.state.identifier || '').trim()) return;
silenceReminderIdentifier = identifier;
silenceReminder.value = reminder;
advanceHomePopupQueue();
} catch (error) {
// 提醒失败不影响首页其他功能
console.error('加载沉默期提醒失败', error);
}
};
const showPendingSilenceReminder = () => {
const reminder = silenceReminder.value;
if (!reminder || silenceReminderShow.value) return false;
if (silenceReminderIdentifier !== String(userStore.state.identifier || '').trim()) {
silenceReminder.value = null;
return false;
}
uni.setStorageSync(silenceReminderKey(silenceReminderIdentifier, reminder, getSessionContext().token), 1);
silenceReminderShow.value = true;
return true;
};
const closeSilenceReminder = () => {
silenceReminderShow.value = false;
silenceReminder.value = null;
advanceHomePopupQueue();
};
const openSilenceReminderAction = () => {
const reminder = silenceReminder.value;
silenceReminderShow.value = false;
silenceReminder.value = null;
if (!reminder) return;
uni.navigateTo({
url: reminder.kind === 'expired'
? `/pages/silence-extension/silence-extension?package_usage_id=${reminder.packageUsageId}`
: '/pages/asset-package-history/asset-package-history'
});
};
const advanceHomePopupQueue = () => {
if (!homeActive.value || awaitingHomeReminders.value || renewalOpening.value || renewalVisible.value || popupCandidateShow.value ||
visibleExpiryReminder.value || notificationPopupShow.value || silenceReminderShow.value) return;
showPendingExpiryReminder();
if (visibleExpiryReminder.value) return;
if (showPendingSilenceReminder()) return;
if (notificationQueued) {
notificationQueued = false;
notificationPopupShow.value = true;
markNotificationRead(notificationItems.value[0]);
} else if (notificationFallbackPending) {
notificationFallbackPending = false;
loadUnreadNotifications();
}
};
watch(() => assetStore.state.expiryReminder, advanceHomePopupQueue);
let showModifyWifi = ref(false);
let restartShow = ref(false);
let recoverShow = ref(false);
let logoutShow = ref(false);
let loading = ref(false);
let syncing = ref(false);
let assetRequestId = 0;
let userInfo = reactive({
isDevice: true,
avatar: ''
});
let deviceInfo = reactive({
battery: 0,
connect: 0,
network_status: 1,
status: 1,
packageName: '-',
currentPackageId: 0,
renewalPrice: null,
expireDate: '-',
isExpiring: false,
expiryDays: null,
expiryEstimateStatus: 'none',
walletBalance: 0,
iccid: '-',
currentIccid: '-',
category: '-',
phone: '-',
flowSize: 0,
totalBytesCnt: 0,
ssidName: '-',
ssidPwd: '-',
signal_quality: '暂无数据',
signal_bad_reason: '',
onlineStatus: '0',
connCnt: 0,
run_time: 0,
last_online_time: '-',
lan_ip: '-',
kf_url: '-',
mchList: [],
imei: '-',
max_clients: 1,
asset_type: 'device',
bound_phone: ''
});
let isRealName = ref(false);
const boundPhone = computed(() => userStore.state.customerPhone || '');
watch(boundPhone, (phone) => { deviceInfo.bound_phone = phone; });
let realNameStatus = ref('');
let effectiveRealnamePolicy = ref('none');
let realnameEntryChecking = ref(false);
let wifi_info = reactive({
ssid: '',
pwd: ''
});
let currentCardNo = ref('');
let accountName = ref('');
let voiceCardStatus = reactive({
cardStatus: '',
online: '离线'
});
let voiceStats = reactive({
totalVoice: 0,
usedVoice: 0,
remainingVoice: 0
});
let showStartDatePicker = ref(false);
let showEndDatePicker = ref(false);
let startDate = ref('');
let endDate = ref('');
let startDateTimestamp = ref(Date.now());
let endDateTimestamp = ref(Date.now());
let dateRangeText = ref('');
let whitelistData = reactive([]);
let showAddWhitelist = ref(false);
let whitelistForm = reactive({
name: '',
phone: ''
});
let showSmsCode = ref(false);
let smsCodePhone = ref('');
let smsCode = ref('');
let notificationUnreadCount = ref(0);
let notificationPopupShow = ref(false);
let notificationItems = ref([]);
let notificationPopupCurrent = ref(0);
let renewalPopupRef = ref(null);
const notificationReadPending = new Set();
let popupCandidateShow = ref(false);
const formatDate = (dateStr) => {
if (!dateStr) return '-';
return dateStr.split('T')[0] || '-';
};
const resolveCurrentCard = (cards = []) => {
if (cards.length === 1) return cards[0];
if (cards.length > 1) return cards.find(card => card.is_current) || null;
return null;
};
const loadAssetInfo = async () => {
const identifier = String(userStore.state.identifier || uni.getStorageSync('identifier') || '').trim();
if (!identifier) return;
if (userStore.state.identifier !== identifier) userStore.setIdentifier(identifier);
const context = getSessionContext();
const requestId = ++assetRequestId;
loading.value = true;
try {
const data = await assetApi.getInfo(identifier);
if (!isCurrentSession(context) || requestId !== assetRequestId) return null;
// 基本信息
userInfo.isDevice = data.asset_type === 'device';
currentCardNo.value = data.identifier || '-';
deviceInfo.network_status = data.network_status;
deviceInfo.status = data.status;
deviceInfo.imei = data.imei || '-';
deviceInfo.asset_type = data.asset_type || 'device';
deviceInfo.bound_phone = userStore.state.customerPhone || '';
deviceInfo.packageName = data.current_package || '-';
deviceInfo.currentPackageId = Number(data.current_package_id || 0);
deviceInfo.renewalPrice = data.renewal_price ?? null;
deviceInfo.expireDate = formatDate(data.estimated_final_expires_at);
deviceInfo.isExpiring = data.is_expiring === true;
deviceInfo.expiryDays = data.days_until_final_expiry ?? null;
deviceInfo.expiryEstimateStatus = data.expiry_estimate_status || 'none';
deviceInfo.iccid = data.iccid || '-';
deviceInfo.walletBalance = data.wallet_balance ?? 0;
const currentCard = resolveCurrentCard(data.cards || []);
isRealName.value = Number(data.real_name_status) === 1;
realNameStatus.value = isRealName.value ? '已实名' : '未实名';
effectiveRealnamePolicy.value = data.effective_realname_policy || 'none';
userStore.setRealNameStatus(data.real_name_status);
// 流量卡片消费同一次 asset/info 快照,支付和有效期变化后一起更新。
// 当前卡信息
if (data.cards && data.cards.length > 0) {
deviceInfo.currentIccid = currentCard?.iccid || '-';
// 卡列表
deviceInfo.mchList = data.cards.map(card => ({
iccidMark: card.iccid || '-',
category: card.slot_position,
is_current: card.is_current
}));
} else {
deviceInfo.currentIccid = '-';
deviceInfo.mchList = [];
}
// 运营商信息
const carrierTypeMap = {
CMCC: '中国移动',
CUCC: '中国联通',
CTCC: '中国电信',
CBN: '中国广电'
};
deviceInfo.carrier_name = (currentCard && carrierTypeMap[currentCard.carrier_type]) || '-';
// 设备实时信息
if (data.device_realtime) {
const rt = data.device_realtime;
deviceInfo.onlineStatus = rt.online_status === 1 ? '1' : '0';
deviceInfo.battery = rt.battery_level ?? 0;
deviceInfo.ssidName = rt.ssid || '-';
deviceInfo.ssidPwd = rt.wifi_password || '-';
deviceInfo.lan_ip = rt.lan_ip || '-';
deviceInfo.connCnt = rt.client_number ?? 0;
deviceInfo.max_clients = rt.max_clients ?? 1;
deviceInfo.run_time = rt.run_time || 0;
deviceInfo.signal_quality = rt.signal_quality || '暂无数据';
deviceInfo.signal_bad_reason = rt.signal_bad_reason || '';
} else {
// 没有实时信息时设置默认值
deviceInfo.onlineStatus = '0';
deviceInfo.battery = 0;
deviceInfo.ssidName = '-';
deviceInfo.ssidPwd = '-';
deviceInfo.lan_ip = '-';
deviceInfo.connCnt = 0;
deviceInfo.max_clients = 1;
deviceInfo.run_time = 0;
deviceInfo.signal_quality = '暂无数据';
deviceInfo.signal_bad_reason = '';
}
// 最终到期时间和临期状态均以后端 asset/info 返回值为准。
return data;
} catch (e) {
console.error('加载资产信息失败', e);
return null;
} finally {
if (requestId === assetRequestId) loading.value = false;
}
};
const handleIndexEntry = async () => {
if (userStore.state.loginPending) return;
const token = uni.getStorageSync('token');
const identifier = String(userStore.state.identifier || uni.getStorageSync('identifier') || '').trim();
if (!token || !identifier) {
if (token && !identifier) {
userStore.clearUser();
uni.showToast({ title: '缺少资产标识,请重新输入或扫码登录', icon: 'none' });
}
uni.reLaunch({ url: '/pages/login/login' });
return;
}
if (userStore.state.identifier !== identifier) userStore.setIdentifier(identifier);
await loadAssetInfo();
};
const onRenewalVisibilityChange = (visible) => {
renewalVisible.value = visible;
if (!visible) advanceHomePopupQueue();
};
const startHomepageRenewal = async () => {
if (renewalOpening.value || renewalVisible.value) return;
const packageId = Number(deviceInfo.currentPackageId || 0);
const packageName = String(deviceInfo.packageName || '').trim();
if (!packageId || !packageName || packageName === '-') {
uni.showToast({ title: '当前资产暂无可续费套餐', icon: 'none' });
return;
}
renewalOpening.value = true;
try {
await renewalPopupRef.value?.open([packageId], [packageName], deviceInfo.renewalPrice);
} finally {
renewalOpening.value = false;
advanceHomePopupQueue();
}
};
const renewFromExpiryReminder = async () => {
if (!visibleExpiryReminder.value || renewalOpening.value || renewalVisible.value) return;
closeExpiryReminder(false);
await startHomepageRenewal();
advanceHomePopupQueue();
};
const modifyWifi = () => {
wifi_info.ssid = deviceInfo.ssidName;
wifi_info.pwd = deviceInfo.ssidPwd;
showModifyWifi.value = true;
};
const confirmModify = async () => {
try {
await deviceApi.setWifi(
userStore.state.identifier,
wifi_info.ssid,
wifi_info.pwd,
true
);
deviceInfo.ssidName = wifi_info.ssid;
deviceInfo.ssidPwd = wifi_info.pwd;
uni.showToast({
title: '修改成功',
icon: 'success'
});
} catch (e) {
console.error('修改WiFi失败', e);
}
showModifyWifi.value = false;
};
const connectKF = () => {
const kfUrl =
'https://work.weixin.qq.com/kfid/kfc0fd79f27686fb65e?enc_scene=ENCfR9AVui6UfvvxySGVuvaG&scene_param=commonlink';
// #ifdef H5
window.location.href = kfUrl;
// #endif
// #ifdef MP-WEIXIN
// 微信小程序跳转到企业微信客服
wx.openCustomerServiceChat({
extInfo: {
url: kfUrl
},
corpId: 'ww4e3b7f9f7c8a9b0c',
success: () => {
console.log('打开客服会话成功');
},
fail: (err) => {
console.error('打开客服会话失败', err);
// 失败时使用网页跳转
uni.navigateTo({
url: `/pages/webview/webview?url=${encodeURIComponent(kfUrl)}`
});
}
});
// #endif
// #ifndef H5 || MP-WEIXIN
// 其他平台,复制链接
uni.showModal({
title: '联系客服',
content: '是否复制客服链接?',
confirmText: '复制',
success: (res) => {
if (res.confirm) {
uni.setClipboardData({
data: kfUrl,
success: () => {
uni.showToast({
title: '客服链接已复制',
icon: 'success'
});
}
});
}
}
});
// #endif
};
const enterBack = async () => {
if (!deviceInfo.lan_ip || deviceInfo.lan_ip === '-') {
uni.showModal({
title: '提示',
content: '请将设备开机后, 等待2分钟左右进行连接WiFi',
showCancel: false,
buttonText: '我知道了'
});
return;
}
await new Promise((resolve) => {
uni.showModal({
title: '提示',
content: '请先连接当前设备WiFi,否则无法访问后台管理',
cancelText: '取消',
confirmText: '我知道了',
success: (res) => res.confirm && resolve()
});
});
// 跳转到设备后台管理地址
const url = deviceInfo.lan_ip.startsWith('http') ? deviceInfo.lan_ip : `http://${deviceInfo.lan_ip}`;
// #ifdef H5
window.location.href = url;
// #endif
// #ifndef H5
uni.showModal({
title: '后台地址',
content: url,
confirmText: '复制',
success: (res) => {
if (res.confirm) {
uni.setClipboardData({
data: url,
success: () => {
uni.showToast({
title: '地址已复制',
icon: 'success'
});
}
});
}
}
});
// #endif
};
const YesRestart = async () => {
try {
await deviceApi.reboot(userStore.state.identifier);
uni.showToast({
title: '重启指令已发送',
icon: 'success'
});
} catch (e) {
console.error('重启设备失败', e);
}
restartShow.value = false;
};
const YesRecover = async () => {
try {
await deviceApi.factoryReset(userStore.state.identifier);
uni.showToast({
title: '恢复出厂设置指令已发送',
icon: 'success'
});
} catch (e) {
console.error('恢复出厂设置失败', e);
}
recoverShow.value = false;
};
const YesLogout = () => {
userStore.clearUser();
uni.clearStorageSync();
uni.reLaunch({
url: '/pages/login/login'
});
logoutShow.value = false;
};
const onlineStatus = computed(() => {
if (!userInfo.isDevice) return voiceCardStatus.online || '离线';
return deviceInfo.onlineStatus === '1' ? '在线' : '离线';
});
const initCurrentMonth = () => {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
startDate.value = `${year}-${month}-01`;
const lastDay = new Date(year, parseInt(month), 0).getDate();
endDate.value = `${year}-${month}-${String(lastDay).padStart(2, '0')}`;
updateDateRangeText();
};
const updateDateRangeText = () => {
if (startDate.value && endDate.value) {
const [sYear, sMonth, sDay] = startDate.value.split('-');
const [eYear, eMonth, eDay] = endDate.value.split('-');
dateRangeText.value = `${sYear}-${sMonth}-${sDay} 至 ${eYear}-${eMonth}-${eDay}`;
}
};
const openDateRangePicker = () => {
if (startDate.value) startDateTimestamp.value = new Date(startDate.value).getTime();
showStartDatePicker.value = true;
};
const onStartDateConfirm = (e) => {
const date = new Date(e.value);
startDate.value =
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
showStartDatePicker.value = false;
setTimeout(() => {
if (endDate.value) endDateTimestamp.value = new Date(endDate.value).getTime();
else endDateTimestamp.value = e.value;
showEndDatePicker.value = true;
}, 300);
};
const onEndDateConfirm = (e) => {
const date = new Date(e.value);
endDate.value =
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
showEndDatePicker.value = false;
if (new Date(startDate.value) > new Date(endDate.value)) {
uni.showToast({
title: '开始日期不能大于结束日期',
icon: 'none'
});
return;
}
updateDateRangeText();
};
const refreshWhitelist = () => uni.showToast({
title: '刷新成功',
icon: 'success'
});
const showAddWhitelistDialog = () => {
whitelistForm.name = '';
whitelistForm.phone = '';
showAddWhitelist.value = true;
};
const confirmAddWhitelist = () => {
if (!whitelistForm.name || !whitelistForm.phone) {
uni.showToast({
title: '请输入姓名和手机号',
icon: 'none'
});
return;
}
const phoneReg = /^1[3-9]\d{9}$/;
if (!phoneReg.test(whitelistForm.phone)) {
uni.showToast({
title: '请输入正确的手机号',
icon: 'none'
});
return;
}
whitelistData.push({
name: whitelistForm.name,
phone: whitelistForm.phone,
state: '1',
createTime: new Date().toISOString().split('T')[0]
});
uni.showToast({
title: '添加成功',
icon: 'none'
});
showAddWhitelist.value = false;
};
const showSmsCodeDialog = (phone, state) => {
if (state !== '5' && state !== '3') {
uni.showToast({
title: '当前状态无需上传短信验证码',
icon: 'none'
});
return;
}
smsCodePhone.value = phone;
smsCode.value = '';
showSmsCode.value = true;
};
const confirmUploadSmsCode = () => {
if (!smsCode.value) {
uni.showToast({
title: '请输入短信验证码',
icon: 'none'
});
return;
}
uni.showToast({
title: '操作成功',
icon: 'success'
});
showSmsCode.value = false;
};
const onSync = async () => {
if (syncing.value) return;
const identifier = userStore.state.identifier;
if (!identifier) {
uni.showToast({
title: '请先登录',
icon: 'none'
});
return;
}
const context = getSessionContext();
uni.showModal({
title: '确认同步',
content: '确定要同步运营商数据吗?受理不代表同步或停复机已执行完成,结果以稍后读取的实际状态为准。',
success: (res) => {
if (!res.confirm || syncing.value || !isCurrentSession(context)) return;
syncing.value = true;
uni.showLoading({
title: '同步中...',
mask: true
});
assetApi.refresh(identifier).then((data) => {
uni.hideLoading();
if (!isCurrentSession(context)) return;
if (data?.accepted === true || data?.accepted === 1) {
const refreshTypeText = data.refresh_type === 'device' ? '设备' : '卡';
uni.showToast({
title: `${refreshTypeText}同步请求已受理,请稍后查看状态`,
icon: 'none',
duration: 3000
});
loadAssetInfo();
setTimeout(() => {
if (homeActive.value && isCurrentSession(context)) loadAssetInfo();
}, 2000);
} else {
uni.showToast({
title: '同步失败,请稍后重试',
icon: 'none'
});
}
}).catch((e) => {
uni.hideLoading();
if (!isCurrentSession(context)) return;
console.error('同步数据失败', e);
if (e.msg && e.msg.includes('冷却')) {
uni.showToast({
title: e.msg,
icon: 'none',
duration: 2000
});
} else {
uni.showToast({
title: '同步失败',
icon: 'none'
});
}
}).finally(() => { syncing.value = false; });
}
});
};
const shouldRedirectRealnameToPackageOrder = async () => {
if (effectiveRealnamePolicy.value !== 'after_order') return false;
const identifier = userStore.state.identifier;
let cards = [{ real_name_status: isRealName.value ? 1 : 0 }];
if (userInfo.isDevice) {
const data = await deviceApi.getCards(identifier);
cards = Array.isArray(data?.cards) ? data.cards : [];
}
if (cards.some(card => Number(card?.real_name_status) === 1)) return false;
return !(await hasActiveOrPendingPackage(identifier));
};
const openRealnameEntry = async () => {
if (realnameEntryChecking.value) return;
realnameEntryChecking.value = true;
uni.showLoading({ title: '校验中...', mask: true });
try {
const shouldRedirect = await shouldRedirectRealnameToPackageOrder();
uni.hideLoading();
if (!shouldRedirect) {
uni.navigateTo({ url: '/pages/auth/auth' });
return;
}
uni.showModal({
title: '提示',
content: '当前设备所有卡均未实名,且暂无生效中或待生效套餐。请先订购套餐,再进行实名认证。',
confirmText: '去订购',
cancelText: '取消',
success: ({ confirm }) => {
if (confirm) uni.navigateTo({ url: '/pages/package-order/package-order' });
}
});
} catch (error) {
uni.hideLoading();
console.error('校验实名入口条件失败', error);
uni.showToast({ title: '实名条件校验失败,请稍后重试', icon: 'none' });
} finally {
realnameEntryChecking.value = false;
}
};
const enterDetail = (name) => {
switch (name) {
case 'notifications':
uni.navigateTo({
url: '/pages/notifications/notifications'
});
break;
case 'package-order':
uni.navigateTo({
url: '/pages/package-order/package-order'
});
break;
case 'order-list':
uni.navigateTo({
url: '/pages/order-list/order-list'
});
break;
case 'back':
enterBack();
break;
case 'switch':
uni.navigateTo({
url: '/pages/switch/switch'
});
break;
case 'asset-package':
uni.navigateTo({
url: '/pages/asset-package-history/asset-package-history'
});
break;
case 'bind':
uni.navigateTo({
url: '/pages/bind/bind'
});
break;
case 'change-phone':
if (!boundPhone.value) {
uni.showToast({
title: '请先去绑定手机号',
icon: 'none',
duration: 2000
});
return;
}
uni.navigateTo({
url: '/pages/change-phone/change-phone'
});
break;
case 'device-exchange':
uni.navigateTo({
url: '/pages/device-exchange/device-exchange'
});
break;
case 'wallet':
uni.navigateTo({
url: '/pages/my-wallet/my-wallet'
});
break;
case 'authentication':
openRealnameEntry();
break;
case 'recover':
recoverShow.value = true;
break;
case 'restart':
restartShow.value = true;
break;
case 'out':
logoutShow.value = true;
break;
}
};
const loadNotificationUnreadCount = async () => {
const context = getSessionContext();
try {
const data = await notificationApi.getUnreadCount();
if (!isCurrentSession(context)) return;
notificationUnreadCount.value = Number(data?.count || 0);
} catch (error) {
console.error('加载通知未读数失败', error);
}
};
const markNotificationRead = async (item) => {
if (!item || item.is_read || notificationReadPending.has(item.id)) return;
notificationReadPending.add(item.id);
const context = getSessionContext();
try {
await notificationApi.markRead(item.id);
if (!isCurrentSession(context)) return;
item.is_read = true;
item.read_at = new Date().toISOString();
notificationUnreadCount.value = Math.max(notificationUnreadCount.value - 1, 0);
} catch (error) {
console.error('标记首页通知已读失败', error);
} finally {
notificationReadPending.delete(item.id);
}
};
const loadUnreadNotifications = async () => {
const context = getSessionContext();
const entryId = homeEntryId;
try {
const data = await notificationApi.getList(1, 50, false);
if (!homeActive.value || entryId !== homeEntryId || !isCurrentSession(context)) return;
const items = (data?.items || [])
.filter(item => !item.is_read && item.category !== 'expiry');
if (!items.length) return;
notificationItems.value = items;
notificationPopupCurrent.value = 0;
notificationQueued = true;
advanceHomePopupQueue();
} catch (error) {
console.error('加载首页未读通知失败', error);
}
};
const copyWifiConfig = (content) => {
uni.setClipboardData({
data: content,
success: () => uni.showToast({ title: '配置已复制', icon: 'none' })
});
};
const onNotificationChange = (event) => {
const index = Number(event?.detail?.current ?? event?.current ?? 0);
notificationPopupCurrent.value = index;
markNotificationRead(notificationItems.value[index]);
};
const closeNotificationPopup = () => {
notificationPopupShow.value = false;
advanceHomePopupQueue();
};
const runPopupCandidate = () => {
popupCandidateShow.value = true;
};
const onPopupCandidateClose = (reason) => {
if (!homeActive.value) return;
popupCandidateShow.value = false;
// The candidate action navigates away immediately. Keep any unshown
// expiry reminder pending rather than consuming it before that navigation.
if (reason === 'action') return;
if (reason === 'empty' || reason === 'invisible') {
notificationFallbackPending = true;
}
advanceHomePopupQueue();
loadNotificationUnreadCount();
};
onMounted(() => {
initCurrentMonth();
});
onShow(async () => {
const entryId = ++homeEntryId;
homeActive.value = true;
shownExpiryReminder.value = null;
awaitingHomeReminders.value = true;
notificationFallbackPending = false;
notificationQueued = false;
if (userStore.state.loginPending) {
awaitingHomeReminders.value = false;
return;
}
if (!getSessionContext().token || !String(userStore.state.identifier || uni.getStorageSync('identifier') || '').trim()) {
awaitingHomeReminders.value = false;
handleIndexEntry();
return;
}
// 每次返回首页都重新读取实际状态,支付返回不再重复发起两次请求。
consumePendingPaymentRefresh(PAYMENT_REFRESH_TARGETS.HOME);
loadNotificationUnreadCount();
runPopupCandidate();
await handleIndexEntry();
if (!homeActive.value || entryId !== homeEntryId) return;
awaitingHomeReminders.value = false;
advanceHomePopupQueue();
// 沉默期提醒在后台加载,不阻塞首页其他弹窗;加载完成后按队列顺序择机弹出。
loadSilenceReminder(entryId);
});
onHide(() => {
homeEntryId++;
assetRequestId++;
homeActive.value = false;
shownExpiryReminder.value = null;
notificationPopupShow.value = false;
popupCandidateShow.value = false;
silenceReminderShow.value = false;
silenceReminder.value = null;
notificationQueued = false;
notificationFallbackPending = false;
});
watch(() => [userStore.state.token, userStore.state.identifier], () => {
shownExpiryReminder.value = null;
notificationItems.value = [];
notificationUnreadCount.value = 0;
notificationPopupShow.value = false;
notificationQueued = false;
notificationFallbackPending = false;
});
</script>
<style scoped lang="scss">
.wifi-popup {
width: 600rpx;
padding: 30rpx;
.title {
font-size: 32rpx;
font-weight: 600;
color: var(--text-primary);
}
.wifi-input {
border: 2rpx solid var(--border-light);
border-radius: 8rpx;
padding: 8rpx 16rpx;
}
}
.bottom-spacer {
height: 120rpx;
}
</style>