feat: improve campus bike discovery and add independent live preview
This commit is contained in:
@@ -0,0 +1,499 @@
|
||||
// ========== 用车计时相关 ==========
|
||||
function clearRentalState() {
|
||||
if (rentalCountdownTimer) {
|
||||
clearInterval(rentalCountdownTimer);
|
||||
rentalCountdownTimer = null;
|
||||
}
|
||||
activeRental = null;
|
||||
localStorage.removeItem(RENTAL_KEY);
|
||||
const bar = document.getElementById("rental-bar");
|
||||
if (bar) bar.classList.remove("show");
|
||||
}
|
||||
|
||||
async function openRentalSettingsModal() {
|
||||
closeAllModals();
|
||||
SettingsPages.open("rental-settings-modal");
|
||||
try {
|
||||
const resp = await apiFetch("/api/auth/rental_settings", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const result = await resp.json();
|
||||
if (result.rtn_code !== 0) throw new Error(result.message || "加载失败");
|
||||
const settings = result.data;
|
||||
document.getElementById("rs-reminder-enabled").checked = !!settings.reminder_enabled;
|
||||
document.getElementById("rs-duration").value = settings.rental_duration_minutes || 19;
|
||||
document.getElementById("rs-auto-return").checked = !!settings.auto_return_enabled;
|
||||
document.getElementById("rs-rounds").value = settings.rental_rounds || 1;
|
||||
document.getElementById("rs-protect-card").checked = settings.protect_card !== false;
|
||||
const selected = new Set((settings.reminder_minutes || []).map(String));
|
||||
document.querySelectorAll("#rs-minute-options input").forEach(el => el.checked = selected.has(el.value));
|
||||
} catch (err) {
|
||||
showToast("设置加载失败:" + friendlyError(err));
|
||||
}
|
||||
}
|
||||
|
||||
function closeRentalSettingsModal() { SettingsPages.back(); }
|
||||
|
||||
async function saveRentalSettings() {
|
||||
const reminderMinutes = [...document.querySelectorAll("#rs-minute-options input:checked")].map(el => Number(el.value));
|
||||
const payload = {
|
||||
reminder_enabled: document.getElementById("rs-reminder-enabled").checked,
|
||||
reminder_minutes: reminderMinutes,
|
||||
rental_duration_minutes: Number(document.getElementById("rs-duration").value),
|
||||
auto_return_enabled: document.getElementById("rs-auto-return").checked,
|
||||
rental_rounds: Number(document.getElementById("rs-rounds").value),
|
||||
protect_card: document.getElementById("rs-protect-card").checked
|
||||
};
|
||||
try {
|
||||
const resp = await apiFetch("/api/auth/rental_settings", {
|
||||
method: "POST",
|
||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const result = await resp.json();
|
||||
if (result.rtn_code !== 0) throw new Error(result.message || "保存失败");
|
||||
closeRentalSettingsModal();
|
||||
showToast("用车设置已保存");
|
||||
} catch (err) {
|
||||
showToast("保存失败:" + friendlyError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function syncWechatOrder() {
|
||||
if (!authToken) return;
|
||||
try {
|
||||
const resp = await apiFetch("/api/rental/sync", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
const data = await resp.json();
|
||||
console.log("[syncWechatOrder] 同步结果:", data);
|
||||
if (data.rtn_code === 0 && data.data && data.data.active && data.data.source === "reminder") {
|
||||
const r = data.data;
|
||||
activeRental = {
|
||||
rental_id: r.rental_id,
|
||||
bike_code: r.bike_code,
|
||||
end_time: r.end_time,
|
||||
source: r.source || "reminder",
|
||||
remaining_seconds: r.remaining_seconds
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
} else if (data.rtn_code === 0 && data.data) {
|
||||
// 真实订单走订单横幅(checkOrderStatus / fetchOrderCountdown 驱动),
|
||||
// 本地计时条只承载 reminder 计时
|
||||
clearRentalState();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[syncWechatOrder] 同步失败:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function checkRentalStatus() {
|
||||
// 已登录才查询
|
||||
if (!authToken) {
|
||||
console.log("[checkRentalStatus] 无token,跳过");
|
||||
return;
|
||||
}
|
||||
|
||||
apiFetch("/api/rental/status", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
console.log("[checkRentalStatus] 响应:", data);
|
||||
if (data.rtn_code === 0 && data.data && data.data.active) {
|
||||
const r = data.data;
|
||||
|
||||
// 剩余时间 <= 0 也视为无活跃
|
||||
if (r.remaining_seconds <= 0) {
|
||||
clearRentalState();
|
||||
return;
|
||||
}
|
||||
|
||||
// 既然后端已按用户过滤,有记录就直接显示状态栏
|
||||
activeRental = {
|
||||
rental_id: r.rental_id,
|
||||
order_id: r.order_id || null,
|
||||
bike_code: r.bike_code,
|
||||
email: r.email,
|
||||
end_time: r.end_time,
|
||||
final_end_time: r.final_end_time || null,
|
||||
current_round: r.current_round || 1,
|
||||
total_rounds: r.total_rounds || null,
|
||||
source: r.source || null,
|
||||
remaining_seconds: r.remaining_seconds
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
showRentalBar();
|
||||
} else {
|
||||
// 无活跃租车,清空
|
||||
console.log("[checkRentalStatus] 无活跃租车");
|
||||
clearRentalState();
|
||||
}
|
||||
})
|
||||
.catch(err => console.error("检查租车状态失败:", err));
|
||||
}
|
||||
|
||||
function startRental(bikeCode) {
|
||||
// 先显示二维码,用户体验更好
|
||||
showQrModal(bikeCode);
|
||||
closeCard();
|
||||
|
||||
console.log("[startRental] authToken:", authToken, "currentUser:", currentUser);
|
||||
|
||||
if (!currentUser) {
|
||||
showToast("登录后可开启用车计时提醒");
|
||||
return;
|
||||
}
|
||||
|
||||
// 调后端开启计时
|
||||
apiFetch("/api/rental/start", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}`
|
||||
},
|
||||
body: JSON.stringify({ bike_code: bikeCode })
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.rtn_code === 0) {
|
||||
const now = new Date();
|
||||
const endTime = new Date(now.getTime() + data.data.remaining_seconds * 1000);
|
||||
activeRental = {
|
||||
rental_id: data.data.rental_id,
|
||||
bike_code: bikeCode,
|
||||
email: currentUser.email,
|
||||
remaining_seconds: data.data.remaining_seconds,
|
||||
end_time: endTime.toISOString().slice(0, 19).replace('T', ' ')
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
showRentalBar();
|
||||
showToast("提醒计时已开始;未绑定微信订单,请到期前手动还车");
|
||||
} else {
|
||||
showToast(data.message || "计时启动失败");
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
showToast("计时未开启,请检查网络");
|
||||
console.error("启动计时失败:", err);
|
||||
});
|
||||
}
|
||||
|
||||
function showRentalBar() {
|
||||
if (!activeRental) return;
|
||||
const bar = document.getElementById("rental-bar");
|
||||
document.getElementById("rental-bike-code").textContent = `#${activeRental.bike_code}`;
|
||||
// +1轮 按钮仅对真实微信订单展示(reminder 计时不支持)
|
||||
const addBtn = document.getElementById("rental-add-round-btn");
|
||||
if (addBtn) {
|
||||
const realOrder = activeRental.source ? activeRental.source !== "reminder"
|
||||
: !!activeRental.order_id;
|
||||
addBtn.style.display = realOrder ? "inline-flex" : "none";
|
||||
}
|
||||
updateRentalFinalTime();
|
||||
bar.classList.add("show");
|
||||
updateRentalCountdown();
|
||||
// 每秒更新倒计时
|
||||
if (rentalCountdownTimer) clearInterval(rentalCountdownTimer);
|
||||
rentalCountdownTimer = setInterval(updateRentalCountdown, 1000);
|
||||
}
|
||||
|
||||
function updateRentalFinalTime() {
|
||||
const el = document.getElementById("rental-final-time");
|
||||
if (!el) return;
|
||||
if (activeRental && activeRental.final_end_time) {
|
||||
const hhmm = String(activeRental.final_end_time).slice(11, 16);
|
||||
const total = activeRental.total_rounds || activeRental.rounds_planned;
|
||||
el.textContent = total ? ` · 共${total}轮 预计${hhmm}还车` : ` · 预计${hhmm}还车`;
|
||||
el.style.display = "inline";
|
||||
} else {
|
||||
el.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
function updateRentalCountdown() {
|
||||
if (!activeRental) return;
|
||||
const el = document.getElementById("rental-time");
|
||||
const remaining = Math.max(0, activeRental.remaining_seconds - 1);
|
||||
activeRental.remaining_seconds = remaining;
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
|
||||
const mins = Math.floor(remaining / 60);
|
||||
const secs = remaining % 60;
|
||||
el.textContent = `${mins}:${secs.toString().padStart(2, "0")}`;
|
||||
|
||||
// 变色提示
|
||||
if (remaining <= 60) {
|
||||
el.style.color = "#ff3b30";
|
||||
} else if (remaining <= 300) {
|
||||
el.style.color = "#ff9f0a";
|
||||
} else {
|
||||
el.style.color = "white";
|
||||
}
|
||||
|
||||
if (remaining <= 0) {
|
||||
clearInterval(rentalCountdownTimer);
|
||||
// 超时后每分钟查一次后端确认状态
|
||||
rentalCountdownTimer = setInterval(checkRentalStatus, 60000);
|
||||
}
|
||||
}
|
||||
|
||||
function showReturnModal() {
|
||||
if (!activeRental) return;
|
||||
document.getElementById("return-bike-code").textContent = `#${activeRental.bike_code}`;
|
||||
document.getElementById("return-modal").classList.add("show");
|
||||
}
|
||||
|
||||
function closeReturnModal() {
|
||||
document.getElementById("return-modal").classList.remove("show");
|
||||
}
|
||||
|
||||
async function confirmReturn() {
|
||||
closeReturnModal();
|
||||
if (!activeRental) return;
|
||||
|
||||
try {
|
||||
const response = await apiFetch("/api/rental/return", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}`
|
||||
},
|
||||
body: JSON.stringify({ rental_id: activeRental.rental_id })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
// 只有后端返回成功才清除本地状态
|
||||
if (data.rtn_code === 0) {
|
||||
clearRentalState();
|
||||
showToast("已确认还车,祝您使用愉快!");
|
||||
} else {
|
||||
// 后端返回错误,保持本地状态,提示用户
|
||||
showToast(data.message || "还车失败,请重试");
|
||||
console.error("还车失败:", data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("确认还车失败:", err);
|
||||
showToast("网络错误,请检查网络后重试");
|
||||
}
|
||||
}
|
||||
|
||||
// 原生壳(Android)判定:UA 由 Android WebView 注入 xbniu-native,head 脚本已给 <html> 加 in-native-shell
|
||||
function isNativeShell() {
|
||||
return document.documentElement && document.documentElement.classList.contains('in-native-shell');
|
||||
}
|
||||
// 网页点“开锁用车”时,把开锁交给安卓原生(原生里选账号/共享并开锁);返回 true 表示已交给原生
|
||||
function nativeUnlockBike(code) {
|
||||
try {
|
||||
if (isNativeShell() && window.xbniuAndroid && typeof window.xbniuAndroid.unlock === 'function') {
|
||||
window.xbniuAndroid.unlock(String(code));
|
||||
return true;
|
||||
}
|
||||
} catch (e) { console.error("[原生桥] 调用失败:", e); }
|
||||
return false;
|
||||
}
|
||||
|
||||
function unlockBike() {
|
||||
if (!selectedBike) return;
|
||||
|
||||
// 检查车辆状态
|
||||
const bikeState = getBikeState(selectedBike);
|
||||
if (bikeState === 'inuse') {
|
||||
showToast("该车正在使用中,请稍后再试");
|
||||
closeCard();
|
||||
return;
|
||||
}
|
||||
if (bikeState === 'locked') {
|
||||
showToast("该车已锁定,无法使用");
|
||||
closeCard();
|
||||
return;
|
||||
}
|
||||
if (bikeState === 'reserved') {
|
||||
showToast("该车已被预约");
|
||||
closeCard();
|
||||
return;
|
||||
}
|
||||
|
||||
// 原生壳:点击即交给安卓原生开锁(账号选择在原生 BikeDetailActivity),不在此出网页二维码
|
||||
if (nativeUnlockBike(selectedBike.code)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 网页端默认:显示二维码弹窗(长按二维码才开始计时)
|
||||
showQrModal(selectedBike.code);
|
||||
}
|
||||
|
||||
// 显示二维码弹窗(适配微信扫码 - img格式)
|
||||
let currentQrPosition = null; // 当前二维码对应的位置
|
||||
|
||||
function showQrModal(code) {
|
||||
const modal = document.getElementById("qr-modal");
|
||||
const qrBox = document.getElementById("qrcode-box");
|
||||
const quickBtn = document.getElementById("quick-unlock-btn");
|
||||
|
||||
// 清空旧的二维码
|
||||
qrBox.innerHTML = "";
|
||||
|
||||
// 获取当前位置
|
||||
currentQrPosition = null;
|
||||
if (navigator.geolocation) {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
pos => {
|
||||
currentQrPosition = {
|
||||
lat: pos.coords.latitude,
|
||||
lng: pos.coords.longitude
|
||||
};
|
||||
},
|
||||
err => console.error("获取位置失败:", err),
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
}
|
||||
|
||||
// 生成新二维码
|
||||
const url = "http://bike.sdlongren.com/bicycle?code=" + code;
|
||||
|
||||
// 判断暗色模式
|
||||
const isDark = UIPreferences.isDark();
|
||||
const dark = isDark ? '#ffffff' : '#000000';
|
||||
const light = isDark ? '#1a1a1a' : '#ffffff';
|
||||
|
||||
// 生成 img 格式二维码(参考 xbcr.html)
|
||||
createQrImage(url, dark, light, function(dataUrl) {
|
||||
qrBox.innerHTML = ""; // 清空旧内容
|
||||
if (!dataUrl) {
|
||||
// 二维码库不可用:明确告知并保留一键开锁入口,避免“点了没反应”
|
||||
qrBox.innerHTML = '<div style="padding:30px 10px;color:var(--text-secondary);font-size:13px;">二维码生成组件加载失败,<br/>可直接使用下方一键开锁。</div>';
|
||||
modal.classList.add("show");
|
||||
quickBtn.style.display = (authToken && currentUser) ? "block" : "none";
|
||||
showToast("二维码组件加载失败,可一键开锁");
|
||||
return;
|
||||
}
|
||||
const img = document.createElement('img');
|
||||
img.src = dataUrl;
|
||||
img.alt = '用车二维码';
|
||||
img.style.cssText = 'width:160px;height:160px;border-radius:4px;box-shadow:rgba(0,0,0,0.4) 2px 2px 8px;display:block;';
|
||||
qrBox.appendChild(img);
|
||||
qrBox.dataset.bikeCode = code; // 存车牌,长按时用
|
||||
modal.classList.add("show");
|
||||
|
||||
// 如果用户已登录,显示一键开锁按钮
|
||||
if (authToken && currentUser) {
|
||||
quickBtn.style.display = "block";
|
||||
} else {
|
||||
quickBtn.style.display = "none";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 生成高质量二维码图片(img格式,适配微信长按识别)
|
||||
function createQrImage(text, dark, light, callback) {
|
||||
const size = 160;
|
||||
const padding = 20;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = canvas.height = size + padding * 2;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// 白色背景
|
||||
ctx.fillStyle = light;
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// 生成二维码到临时容器
|
||||
const tmp = document.createElement('div');
|
||||
tmp.style.display = 'none';
|
||||
document.body.appendChild(tmp);
|
||||
|
||||
// qrcodejs 加载失败时(如外链 CDN 不可达)给出明确提示,而不是无声无息
|
||||
if (typeof QRCode === "undefined") {
|
||||
document.body.removeChild(tmp);
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
|
||||
new QRCode(tmp, {
|
||||
text: text,
|
||||
width: size,
|
||||
height: size,
|
||||
colorDark: dark,
|
||||
colorLight: light,
|
||||
correctLevel: QRCode.CorrectLevel.L
|
||||
});
|
||||
|
||||
// 从临时容器提取 canvas 并画到带padding的画布上
|
||||
setTimeout(function() {
|
||||
var qrCanvas = tmp.querySelector('canvas');
|
||||
if (qrCanvas) {
|
||||
ctx.drawImage(qrCanvas, padding, padding);
|
||||
}
|
||||
document.body.removeChild(tmp);
|
||||
callback(qrCanvas ? canvas.toDataURL('image/png', 1) : null);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// 关闭二维码弹窗
|
||||
function closeQrModal() {
|
||||
document.getElementById("qr-modal").classList.remove("show");
|
||||
document.getElementById("quick-unlock-btn").style.display = "none";
|
||||
// 清除长按定时器
|
||||
longPressTimer = null;
|
||||
longPressTarget = null;
|
||||
currentQrPosition = null;
|
||||
}
|
||||
|
||||
// 长按检测变量
|
||||
let longPressTimer = null;
|
||||
let longPressTarget = null;
|
||||
let qrModalBikeCode = null; // 当前二维码对应的车牌
|
||||
|
||||
// 二维码弹窗的二维码区域长按检测
|
||||
function setupQrLongPress() {
|
||||
const qrBox = document.getElementById("qrcode-box");
|
||||
|
||||
// 统一用 pointer 事件(兼容触摸和鼠标)
|
||||
qrBox.addEventListener("pointerdown", function(e) {
|
||||
if (!currentUser) return;
|
||||
e.preventDefault(); // 阻止右键菜单等默认行为
|
||||
qrModalBikeCode = qrBox.dataset.bikeCode || "";
|
||||
longPressTimer = setTimeout(() => {
|
||||
longPressTimer = null;
|
||||
if (qrModalBikeCode && currentUser) {
|
||||
// 视觉反馈
|
||||
qrBox.style.backgroundColor = "rgba(52,199,89,0.2)";
|
||||
setTimeout(() => { qrBox.style.backgroundColor = "white"; }, 500);
|
||||
startRental(qrModalBikeCode);
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
|
||||
qrBox.addEventListener("pointerup", function(e) {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
qrBox.addEventListener("pointerleave", function(e) {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
qrBox.addEventListener("pointercancel", function(e) {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 页面加载时初始化长按检测
|
||||
setupQrLongPress();
|
||||
|
||||
// 点击遮罩关闭
|
||||
document.getElementById("qr-modal").addEventListener("click", function(e) {
|
||||
if (e.target === this) closeQrModal();
|
||||
});
|
||||
Reference in New Issue
Block a user