feat: improve campus bike discovery and add independent live preview

This commit is contained in:
zzy
2026-11-04 16:42:47 +08:00
parent f986c8deae
commit b6b7b3dbe5
42 changed files with 5267 additions and 4313 deletions
+32
View File
@@ -0,0 +1,32 @@
/* Bounded requests; mutation requests are never retried automatically. */
(function () {
'use strict';
const pending = new Map();
async function request(url, options = {}) {
const controller = new AbortController();
const abort = () => controller.abort();
if (options.signal?.aborted) controller.abort();
else options.signal?.addEventListener('abort', abort, { once: true });
const timer = setTimeout(abort, options.timeout || 15000);
try {
return await fetch(url, { ...options, signal: controller.signal });
} catch (error) {
if (error.name === 'AbortError') throw new Error('请求超时或已取消,请刷新状态后重试');
throw error;
} finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', abort);
}
}
async function run(key, button, action) {
if (pending.has(key)) return pending.get(key);
if (button) { button.disabled = true; button.setAttribute('aria-busy', 'true'); }
const task = Promise.resolve().then(action).finally(() => {
pending.delete(key);
if (button) { button.disabled = false; button.removeAttribute('aria-busy'); }
});
pending.set(key, task);
return task;
}
window.AppAPI = { fetch: request, run };
})();
+41
View File
@@ -0,0 +1,41 @@
/* Shared vehicle rules. Unknown battery data is never invented. */
(function (root) {
'use strict';
function electric(bike) {
const raw = bike?.electric_quantity ?? bike?.electricQuantity ?? bike?.electric;
if (raw === null || raw === undefined || typeof raw === 'boolean' || String(raw).trim() === '') return null;
const n = Number(raw);
return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null;
}
function state(bike) {
const s = Number(bike?.state), occupied = Number(bike?.status), e = electric(bike);
if (s === 1 && occupied === 1) return 'inuse';
if (s === 4) return 'locked';
if (s === 2) return 'reserved';
if (s === 10 || (e !== null && e < 20)) return 'lowbattery';
if (s === 1 && occupied === 0) return 'available';
return 'unknown';
}
const labels = { available: '可用', inuse: '使用中', locked: '欠压', reserved: '损坏', lowbattery: '低电量', unknown: '状态未知' };
function kind(bike) {
const code = String(bike?.code ?? bike?.bike_code ?? '');
if (/^\d{8}$/.test(code)) return 'red';
return Number(code.slice(0, 3)) >= 511 ? 'big' : 'small';
}
function validCode(code) { return /^(?:\d{5}|\d{8})$/.test(String(code)); }
function distance(a, b) {
if (!a || !b || ![a.lat, a.lng, b.lat, b.lng].every(Number.isFinite)) return null;
const rad = Math.PI / 180, dlat = (b.lat - a.lat) * rad, dlng = (b.lng - a.lng) * rad;
const h = Math.sin(dlat / 2) ** 2 + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dlng / 2) ** 2;
return 12742000 * Math.asin(Math.sqrt(Math.min(1, h)));
}
function matches(bike, filters) {
const e = electric(bike);
return (!filters.onlyAvailable || state(bike) === 'available') &&
(!filters.kind || filters.kind === 'all' || kind(bike) === filters.kind) &&
(!(filters.minElectric > 0) || (e !== null && e >= filters.minElectric));
}
const api = { electric, state, labels, kind, validCode, distance, matches };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
root.BikeData = api;
})(typeof window !== 'undefined' ? window : globalThis);
File diff suppressed because it is too large Load Diff
+54
View File
@@ -0,0 +1,54 @@
// ========== 启动 ==========
// 启动时检查登录状态,然后检查租车
checkAuthStatus().then(() => {
if (authToken && typeof SettingsPages !== "undefined") SettingsPages.restore();
checkRentalStatus();
if (authToken) shareAfterLogin();
});
// 未登录:全屏登录门覆盖地图(后端 /api/map 同样有登录门禁)
if (!authToken) showLoginGate();
document.addEventListener("DOMContentLoaded", initMap);
window.addEventListener("xbniu-map-ready", initMap);
document.getElementById("scan-input").addEventListener("keydown", e => {
if (e.key === "Enter") scanCode();
});
// Refresh at the shared snapshot's expiry, not 60 seconds after an old cache hit.
setInterval(updateMapFreshnessBadge, 1000);
// 进行中订单:每 2 分钟主动刷新一次(与上游对账 + 重算剩余时长/预计还车)
setInterval(async () => {
if (!authToken || document.visibilityState !== "visible") return;
if (!currentOrder || Number(currentOrder.status) !== 2) return;
try {
await syncWechatOrder(); // 上游可能已被还车/换单
checkOrderStatus(); // 刷新横幅状态
if (currentOrder && currentOrder.order_id) {
fetchOrderCountdown(currentOrder.order_id); // 重算剩余 + 预计还车
}
} catch (e) {
console.error("[订单2分钟刷新] 失败:", e);
}
}, 120000);
// 页面重新可见时检查租车状态
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
if (authToken && map) loadMapData(currentType, false, true);
checkAuthStatus().then(async () => {
// 从微信或其他端回到页面时,先主动对账,再刷新本地横幅。
if (authToken) await syncWechatOrder();
// 如果有租车计时横幅,同步服务端时间
const rentalBar = document.getElementById("rental-bar");
console.log("[visibilitychange] 同步服务端用车状态");
checkRentalStatus();
// 如果有订单横幅且在进行中,同步倒计时
const orderBanner = document.getElementById("order-banner");
if (orderBanner && orderBanner.classList.contains("show") && currentOrder && currentOrder.status === 2) {
console.log("[visibilitychange] order-banner 进行中,同步倒计时");
fetchOrderCountdown(currentOrder.order_id);
}
});
}
});
+175
View File
@@ -0,0 +1,175 @@
/* Find vehicles by location, availability, battery and kind. Coordinates here are BD09. */
(function () {
'use strict';
const storageKey = 'xbniu_discovery', favoriteKey = 'xbniu_places';
let filters = { onlyAvailable: false, minElectric: 0, kind: 'all', radius: 500, sort: 'distance' };
let favorites = [], locations = [], origin = null, originName = '', initialized = false, renderFrame = null;
const byId = id => document.getElementById(id);
const escape = text => String(text ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
try {
const saved = JSON.parse(localStorage.getItem(storageKey) || '{}');
filters.onlyAvailable = saved.onlyAvailable === true;
if ([0,20,40,60,80].includes(saved.minElectric)) filters.minElectric = saved.minElectric;
if (['all','small','big','red'].includes(saved.kind)) filters.kind = saved.kind;
if ([200,500,1000,0].includes(saved.radius)) filters.radius = saved.radius;
if (['distance','electric'].includes(saved.sort)) filters.sort = saved.sort;
const stored = JSON.parse(localStorage.getItem(favoriteKey) || '[]');
if (Array.isArray(stored)) favorites = stored.filter(p => p && typeof p.name === 'string' && Number.isFinite(p.lat) && Number.isFinite(p.lng) && Math.abs(p.lat) <= 90 && Math.abs(p.lng) <= 180).slice(0, 12);
} catch (_) {}
function center() {
if (origin) return origin;
if (autoLocationMarker) return autoLocationMarker.getPosition();
return map?.getCenter() || null;
}
function items(availableOnly = false) {
const point = center();
return Object.values(markersData).filter(b => BikeData.matches(b, { ...filters, onlyAvailable: availableOnly || filters.onlyAvailable }))
.map(b => ({ bike: b, id: BikeClusters.bikeId(b), distance: BikeData.distance(point, offsetCoord(b.latitude, b.longitude)), electric: BikeData.electric(b) }))
.filter(row => !filters.radius || row.distance === null || row.distance <= filters.radius)
.sort((a, b) => filters.sort === 'electric'
? (b.electric ?? -1) - (a.electric ?? -1) || (a.distance ?? Infinity) - (b.distance ?? Infinity)
: (a.distance ?? Infinity) - (b.distance ?? Infinity) || (b.electric ?? -1) - (a.electric ?? -1));
}
function visibleBikes(bikes) { return bikes.filter(b => BikeData.matches(b, filters)); }
function persist() { try { localStorage.setItem(storageKey, JSON.stringify(filters)); } catch (_) {} }
function render() {
if (!initialized) return;
const rows = items();
byId('nearby-count').textContent = rows.length;
byId('discovery-origin').textContent = originName || (autoLocationMarker ? '以我的位置查找' : '以地图中心查找');
byId('nearby-summary').textContent = `${filters.radius ? filters.radius + ' 米内' : '全部范围'} · ${rows.length} 辆符合条件 · 距离为直线距离`;
const batteryText = e => e === null ? '电量未知' : `${Math.round(e)}% 电量`;
byId('nearby-list').innerHTML = rows.length ? rows.slice(0, 100).map(row => {
const s = BikeData.state(row.bike), k = { small:'小车', big:'大车', red:'红车' }[BikeData.kind(row.bike)];
const distance = row.distance === null ? '距离待确认' : row.distance < 1000 ? `${Math.round(row.distance)} 米` : `${(row.distance / 1000).toFixed(1)} 公里`;
return `<button class="nearby-row" data-bike-id="${escape(row.id)}"><span><strong>#${escape(row.bike.code)}</strong><span class="nearby-row-meta">${k} · ${batteryText(row.electric)}</span></span><span class="nearby-row-end"><span class="vehicle-status ${s}">${BikeData.labels[s]}</span><span>${distance}</span></span></button>`;
}).join('') : '<div class="discovery-empty"><strong>这里暂时没有符合条件的车辆</strong><p>可以扩大范围、降低电量要求或切换车型。</p><button type="button" data-relax>放宽筛选条件</button></div>';
if (rows.length > 100) byId('nearby-summary').textContent += ',先展示前 100 辆,请缩小范围';
}
function refresh() {
if (!initialized) return;
persist();
rebuildMarkersForZoom();
render();
}
function relax() {
filters = { onlyAvailable: true, minElectric: 0, kind: 'all', radius: 0, sort: 'distance' };
fillControls(); refresh();
showToast('已扩大至全部范围,保留可用车辆');
}
function fillControls() {
byId('filter-available').checked = filters.onlyAvailable;
byId('filter-electric').value = filters.minElectric;
byId('filter-kind').value = filters.kind;
byId('filter-radius').value = filters.radius;
byId('nearby-sort').value = filters.sort;
}
function showList(open = true) {
byId('nearby-panel').hidden = !open;
byId('nearby-toggle').setAttribute('aria-expanded', String(open));
if (open) { render(); byId('nearby-close').focus({ preventScroll: true }); }
else byId('nearby-toggle').focus({ preventScroll: true });
}
function choosePlace(point, name) {
if (!map) { showToast('地图正在加载,请稍后重试'); return; }
origin = { lat: point.lat, lng: point.lng }; originName = name;
map.panTo(new BMapGL.Point(point.lng, point.lat));
byId('place-search').value = name;
byId('place-results').hidden = true;
render(); showList();
}
function searchPlaces() {
const q = byId('place-search').value.trim().toLocaleLowerCase();
const selected = locations.filter(p => !q || p.name.toLocaleLowerCase().includes(q)).slice(0, 8);
byId('place-results').hidden = false;
byId('place-results').innerHTML = selected.length ? selected.map(p => `<button type="button" data-place-id="${p.id}"><span>${escape(p.name)}</span><small>${p.kind === 'parking' ? '停车点' : '校园地点'}</small></button>`).join('') : '<p class="discovery-empty">未找到地点,可拖动地图后收藏当前位置。</p>';
}
function renderFavorites() {
byId('favorite-places').innerHTML = favorites.length ? favorites.map((p, index) => `<span class="favorite-place"><button type="button" data-favorite="${index}">${escape(p.name)}</button><button type="button" data-remove-favorite="${index}" aria-label="删除常用地点 ${escape(p.name)}">×</button></span>`).join('') : '<span class="discovery-muted">常用地点保存在这台设备</span>';
}
function savePlace() {
const p = origin || map?.getCenter();
if (!p) { showToast('地图加载后可收藏地点'); return; }
const name = byId('place-search').value.trim().slice(0, 24) || originName || `地图位置 ${favorites.length + 1}`;
if (favorites.length >= 12) { showToast('最多收藏 12 个地点,请先移除不需要的'); return; }
if (favorites.some(f => f.name === name)) { showToast('已收藏同名地点'); return; }
favorites.push({ name, lat: p.lat, lng: p.lng });
try { localStorage.setItem(favoriteKey, JSON.stringify(favorites)); } catch (_) { showToast('浏览器未允许保存常用地点'); return; }
renderFavorites(); showToast('已收藏当前查找地点');
}
function locationStatus(message, retry = false) {
const box = byId('location-status'); if (!box) return;
box.hidden = false;
byId('location-message').textContent = message;
byId('location-retry').hidden = !retry;
}
async function nearest(point) {
if (!authToken) { showLoginGate(); return; }
if (point) { origin = { lat: point.lat, lng: point.lng }; originName = '我的位置'; }
const candidates = items(true).filter(row => row.electric !== null && row.electric >= 20);
if (!candidates.length) {
showList(); locationStatus('没有符合当前条件的可用车,可在列表中放宽筛选。');
return;
}
candidates.sort((a, b) => (a.distance ?? Infinity) - (b.distance ?? Infinity));
const row = candidates[0];
nearestBikeId = row.id; showList(false); showBikeDetail(row.id);
showToast(`最近可用:#${row.bike.code},${Math.round(row.distance || 0)} 米,电量 ${row.electric}%`);
}
async function init() {
if (initialized) return;
initialized = true; fillControls(); renderFavorites();
['filter-available','filter-electric','filter-kind','filter-radius','nearby-sort'].forEach(id => byId(id).addEventListener('change', () => {
filters.onlyAvailable = byId('filter-available').checked;
filters.minElectric = Number(byId('filter-electric').value);
filters.kind = byId('filter-kind').value;
filters.radius = Number(byId('filter-radius').value);
filters.sort = byId('nearby-sort').value; refresh();
}));
byId('nearby-toggle').addEventListener('click', () => showList(byId('nearby-panel').hidden));
byId('discovery-filters').addEventListener('toggle', () => {
if (byId('discovery-filters').open && !byId('nearby-panel').hidden) showList(false);
});
byId('nearby-close').addEventListener('click', () => showList(false));
byId('nearby-panel').addEventListener('keydown', e => { if (e.key === 'Escape') showList(false); });
byId('nearby-list').addEventListener('click', event => {
const row = event.target.closest('[data-bike-id]');
if (row) { showList(false); showBikeDetail(row.dataset.bikeId); }
if (event.target.closest('[data-relax]')) relax();
});
byId('place-search').addEventListener('input', searchPlaces);
byId('place-search').addEventListener('focus', searchPlaces);
byId('place-search').addEventListener('keydown', e => {
if (e.key === 'Escape') byId('place-results').hidden = true;
if (e.key === 'ArrowDown') { e.preventDefault(); byId('place-results').querySelector('button')?.focus(); }
if (e.key === 'Enter') { e.preventDefault(); byId('place-results').querySelector('button')?.click(); }
});
byId('place-results').addEventListener('click', e => {
const button = e.target.closest('[data-place-id]');
const place = locations.find(p => String(p.id) === button?.dataset.placeId);
if (place) { const p = offsetCoord(place.latitude, place.longitude); choosePlace(p, place.name); }
});
byId('favorite-save').addEventListener('click', savePlace);
byId('favorite-places').addEventListener('click', e => {
const remove = e.target.closest('[data-remove-favorite]');
if (remove) { favorites.splice(Number(remove.dataset.removeFavorite), 1); try { localStorage.setItem(favoriteKey, JSON.stringify(favorites)); } catch (_) {} renderFavorites(); return; }
const button = e.target.closest('[data-favorite]');
if (button) { const place = favorites[Number(button.dataset.favorite)]; if (place) choosePlace(place, place.name); }
});
byId('location-center').addEventListener('click', () => { origin = null; originName = ''; if (autoLocationMarker) { const p = map.getCenter(); origin = {lat:p.lat,lng:p.lng}; originName='地图中心'; } render(); showList(); locationStatus('已按地图中心查找,无需定位权限。'); });
byId('location-retry').addEventListener('click', () => { origin = null; originName = ''; startAutoLocation(); });
byId('discovery-origin').addEventListener('click', () => { origin = null; originName = ''; byId('place-search').value = ''; refresh(); });
document.addEventListener('click', e => { if (!e.target.closest('.place-search-wrap')) byId('place-results').hidden = true; });
map.addEventListener('moveend', () => { if (!renderFrame) renderFrame = requestAnimationFrame(() => { renderFrame = null; render(); }); });
map.addEventListener('dragend', () => {
const point = map.getCenter(); origin = {lat:point.lat,lng:point.lng}; originName = '地图中心';
byId('place-search').value = ''; render();
});
try {
const response = await AppAPI.fetch('/api/campus/locations'); const data = await response.json();
locations = Array.isArray(data.data) ? data.data : [];
} catch (_) { locationStatus('校园地点加载失败,可拖动地图查找或重试刷新。'); }
render();
}
window.BikeDiscovery = { init, render, visibleBikes, locationStatus, nearest, showList };
})();
+191
View File
@@ -0,0 +1,191 @@
// ========== 订单历史(我的 → 订单历史) ==========
function fmtDuration(seconds) {
if (seconds === null || seconds === undefined) return "--";
const mins = Math.round(seconds / 60);
if (mins < 60) return `${mins} 分钟`;
return `${Math.floor(mins / 60)} 小时 ${mins % 60} 分钟`;
}
function fmtOrderTime(s) {
if (!s) return "--";
return String(s).replace("T", " ").slice(5, 16); // MM-DD HH:MM
}
function fmtClock(s) {
if (!s) return "--";
return String(s).slice(11, 16); // HH:MM
}
function orderCardHtml(o) {
const badge = o.returned
? '<span class="badge muted" style="padding:2px 8px;border-radius:8px;font-size:11px;background:var(--ui-surface-raised);color:var(--ui-muted);">已完成</span>'
: '<span class="badge" style="padding:2px 8px;border-radius:8px;font-size:11px;background:var(--ui-surface-raised);color:var(--discovery-available);">进行中</span>';
const sharedRow = o.shared
? `<div style="margin-top:2px;">${o.role === "owner" ? "共享给" : "使用"} <b>${escHtml(o.partner || "--")}</b> 的车</div>` : "";
// 多轮续租合并显示:共 N 轮 · 总用时 · 起止时钟
const roundsRow = (o.rounds && o.rounds > 1)
? `<div style="margin-top:2px;color:var(--ui-muted);">共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}</div>` : "";
const timeRow = `${fmtOrderTime(o.start_time)} → ${fmtOrderTime(o.end_time)}`;
return `
<div class="device-item" style="display:block;padding:10px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
<div style="display:flex;justify-content:space-between;align-items:center;">
<b style="font-size:14px;">#${escHtml(o.bike_code)}</b>
<span style="display:flex;align-items:center;gap:6px;">
<span style="font-size:12px;color:var(--text-secondary);">${o.duration_seconds !== null ? fmtDuration(o.duration_seconds) : ""}</span>
${badge}
</span>
</div>
<div style="font-size:12.5px;color:var(--text-secondary);margin-top:3px;line-height:1.7;">
<div>${timeRow}</div>
<div>${escHtml(o.start_label || "起点未知")} <span style="margin:0 3px;">→</span> ${escHtml(o.end_label || (o.returned ? "终点未知" : "骑行中"))}</div>
${roundsRow}
${sharedRow}
</div>
<div style="margin-top:6px;text-align:right;">
<button class="btn" style="padding:4px 10px;border:none;border-radius:8px;font-size:12px;background:#e7f0fd;color:var(--ui-muted);"
onclick="openOrderTrajectory(${o.id})">查看轨迹</button>
</div>
</div>`;
}
// ========== 订单骑行轨迹 ==========
let orderTrajMap = null;
let orderTrajOverlays = [];
async function openOrderTrajectory(rentalId){
SettingsPages.open("order-traj-modal");
document.getElementById("order-traj-summary").textContent = "加载轨迹中...";
document.getElementById("order-traj-hint").textContent = "轨迹来自每 5-10 分钟一次的车辆定位采集。";
try{
const resp = await apiFetch(`/api/user/orders/trajectory?rental_id=${encodeURIComponent(rentalId)}`, {
headers: { "Authorization": `Bearer ${authToken}` }
});
const data = await resp.json();
if (data.rtn_code !== 0) {
document.getElementById("order-traj-summary").textContent = data.message || "轨迹加载失败";
return;
}
renderOrderTrajectory(data.data);
}catch(e){
document.getElementById("order-traj-summary").textContent = "网络错误,请重试";
}
}
function closeOrderTrajModal(){
SettingsPages.back();
// 保留地图实例,下次复用;只清理覆盖物
if (orderTrajMap) {
try { orderTrajMap.clearOverlays(); } catch(e) {}
}
orderTrajOverlays = [];
}
function renderOrderTrajectory(t){
const pts = t.points || [];
// textContent 不解析 HTML,这里不能用 escHtml(会把 & 显示成 &amp;)
document.getElementById("order-traj-summary").textContent =
`#${t.bike_code} · ${fmtOrderTime(t.start_time)} → ${fmtOrderTime(t.end_time)} · ` +
`${t.start_label || "起点未知"} → ${t.end_label || (t.returned ? "终点未知" : "骑行中")}`;
const initMap = () => {
if (!orderTrajMap) {
orderTrajMap = new BMapGL.Map("order-traj-map");
orderTrajMap.enableScrollWheelZoom(true);
}
const overlayPts = [];
try { orderTrajMap.clearOverlays(); } catch(e) {}
const toBd = (lat, lng) => offsetCoord(lat, lng);
// 轨迹线(GCJ02 → BD09 逐点转换)
const linePts = pts.map(p => {
const c = toBd(p.lat, p.lng);
return new BMapGL.Point(c.lng, c.lat);
});
// 采集缺失时用订单起终点兜底成两点直线
if (linePts.length < 2 && (t.start_point || t.end_point)) {
const s = t.start_point, e = t.end_point || t.start_point;
const cs = toBd(s.lat, s.lng), ce = toBd(e.lat, e.lng);
linePts.push(new BMapGL.Point(cs.lng, cs.lat), new BMapGL.Point(ce.lng, ce.lat));
}
if (linePts.length >= 2) {
const poly = new BMapGL.Polyline(linePts, {
strokeColor: "#0a84ff", strokeWeight: 5, strokeOpacity: 0.85,
});
orderTrajMap.addOverlay(poly);
overlayPts.push(...linePts);
}
// 起终点标记
const mark = (pt, color, text) => {
if (!pt) return;
const c = toBd(pt.lat, pt.lng);
const p = new BMapGL.Point(c.lng, c.lat);
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 26;
const ctx = canvas.getContext("2d");
ctx.beginPath(); ctx.arc(13, 13, 10, 0, Math.PI * 2);
ctx.fillStyle = color; ctx.fill();
ctx.fillStyle = "#fff"; ctx.font = "bold 12px Arial";
ctx.textAlign = "center"; ctx.textBaseline = "middle";
ctx.fillText(text, 13, 13);
const marker = new BMapGL.Marker(p, {
icon: new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(26, 26), new BMapGL.Size(13, 13))
});
orderTrajMap.addOverlay(marker);
overlayPts.push(p);
};
mark(t.start_point, "#34c759", "起");
mark(t.end_point, "#ff3b30", "终");
if (overlayPts.length) {
try {
orderTrajMap.setViewport(overlayPts, { margins: [30, 30, 30, 30] });
} catch (e) {
orderTrajMap.centerAndZoom(overlayPts[0], 18);
}
} else {
apiFetch("/api/config").then(r => r.json()).then(cfg => {
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
orderTrajMap.centerAndZoom(new BMapGL.Point(c.lng, c.lat), 17);
});
}
document.getElementById("order-traj-hint").textContent = pts.length
? `共 ${pts.length} 个定位点`
: "该时间段没有采集到定位点(采集间隔 5-10 分钟),已用订单起终点示意";
};
// 弹窗刚显示,等一帧再初始化,避免容器尺寸为 0
setTimeout(initMap, 60);
}
let orderHistoryRows = [], orderHistorySerial = 0, orderHistoryController = null;
async function openOrdersModal() {
closeAllModals(); SettingsPages.open("orders-modal");
await loadOrderPage(true);
}
function closeOrdersModal() { SettingsPages.back(); }
function resetOrderFilters() {
["orders-from", "orders-to", "orders-code"].forEach(id => document.getElementById(id).value = "");
document.getElementById("orders-source").value = "all";
loadOrderPage(true);
}
async function loadOrderPage(reset) {
const from = document.getElementById("orders-from").value, to = document.getElementById("orders-to").value;
const code = document.getElementById("orders-code").value.trim();
if (from && to && from > to) { showToast("开始日期不能晚于结束日期"); return; }
if (code && !/^\d{1,8}$/.test(code)) { showToast("车牌筛选只能包含最多8位数字"); return; }
const serial = ++orderHistorySerial;
orderHistoryController?.abort(); orderHistoryController = new AbortController();
const box = document.getElementById("orders-list"), more = document.getElementById("orders-more");
if (reset) { orderHistoryRows = []; box.innerHTML = '<div class="device-loading">正在查询记录...</div>'; }
more.disabled = true;
document.getElementById("orders-search").disabled = true;
const query = new URLSearchParams({limit:"20", offset:String(orderHistoryRows.length), from, to, code, source:document.getElementById("orders-source").value});
try {
const response = await apiFetch(`/api/user/orders?${query}`, { headers:{Authorization:`Bearer ${authToken}`}, signal:orderHistoryController.signal });
const data = await response.json();
if (serial !== orderHistorySerial) return;
if (data.rtn_code !== 0) throw new Error(data.message || "查询失败");
orderHistoryRows.push(...(data.data || []));
document.getElementById("orders-summary").textContent = `共 ${data.total ?? orderHistoryRows.length} 条记录,已显示 ${orderHistoryRows.length} 条`;
box.innerHTML = orderHistoryRows.length ? orderHistoryRows.map(orderCardHtml).join("") : '<div class="device-loading">没有符合条件的订单,可调整日期、车牌或来源后重试。</div>';
more.hidden = !data.has_more;
} catch (error) {
if (serial !== orderHistorySerial) return;
if (reset) box.innerHTML = `<div class="device-loading">${escHtml(error.message)},请点击“查询记录”重试。</div>`;
else showToast(error.message || "加载失败,请重试");
} finally {
if (serial === orderHistorySerial) { more.disabled = false; document.getElementById("orders-search").disabled = false; }
}
}
+976
View File
@@ -0,0 +1,976 @@
// ========== 订单状态检测 ==========
let currentOrder = null; // 当前订单信息
async function checkOrderStatus() {
if (!authToken) {
hideOrderBanner();
return;
}
try {
const resp = await apiFetch("/api/order/status", {
headers: { "Authorization": `Bearer ${authToken}` }
});
const data = await resp.json();
if (data.rtn_code === 0) {
if (!data.has_credentials) {
// 用户没有配置凭据
hideOrderBanner();
return;
}
if (data.has_order && data.order) {
currentOrder = data.order;
// 仅当“当前微信订单本身就是我共享出去的这笔订单”时隐藏普通横幅。
// 骑行者自己账号另有待支付/进行中订单时,必须与借用中的共享横幅同时保留。
if (data.order.shared) {
hideOrderBanner();
} else {
showOrderBanner(data.order);
}
} else {
currentOrder = null;
hideOrderBanner();
}
} else if (data.rtn_code === 102001 || data.token_invalid) {
// token_id 已失效(小程序重新登录会踢掉旧会话):弹窗引导重新配置(带冷却,避免每20秒轮询骚扰)
notifyCredentialInvalid(data.message);
}
} catch (err) {
console.error("检查订单状态失败:", err);
}
}
function showOrderBanner(order) {
const banner = document.getElementById("order-banner");
const icon = document.getElementById("order-banner-icon");
const text = document.getElementById("order-banner-text");
const btn = document.getElementById("order-banner-btn");
banner.classList.remove("warning", "riding");
if (Number(order.status) === 1) {
// 待支付
banner.classList.add("warning");
icon.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>';
text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`;
btn.textContent = "去支付";
hideOrderCountdown();
const progress = document.getElementById("order-final-time");
progress.textContent = "待支付 · 骑行已结束";
progress.style.display = "inline";
} else if (Number(order.status) === 2) {
// 进行中 - 获取倒计时
banner.classList.add("riding");
icon.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="5.5" cy="17.5" r="3.5"/><circle cx="18.5" cy="17.5" r="3.5"/><path d="M15 6h3l2 4-2.5 1.5a8 8 0 0 1-7 3.5c-2.5 0-4.5-1.5-5.5-3.5L2 12l4-4h4"/></svg>';
if (order.shared) {
const sName = partnerLabel(order.shared.rider_name, order.shared.rider_email, order.shared.remark);
text.textContent = ("共享中 #" + (order.code || order.order_id.slice(-6)) + " · " + sName + "使用中");
} else {
text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`;
}
btn.textContent = "还车";
if (String(orderCountdownOrderId) !== String(order.order_id)) {
hideOrderCountdown();
const progress = document.getElementById("order-final-time");
progress.textContent = "骑行中 · 正在同步计时";
progress.style.display = "inline";
}
// 从后端获取剩余时间并启动倒计时
fetchOrderCountdown(order.order_id);
}
banner.classList.add("show");
}
let orderCountdownTimer = null;
let orderCountdownSeconds = 0;
let orderCountdownDeadline = null;
let orderCountdownOrderId = null;
function rideProgressText(summary) {
const current = Math.max(1, Number(summary.current_round) || 1);
const total = Math.max(current, Number(summary.total_rounds) || current);
const end = String(summary.final_end_time || summary.end_time || "").match(/(?:T|\s)(\d{2}:\d{2})/);
const phase = summary.auto_return ? "自动还车已开启" : "手动还车";
return `第 ${current}/${total} 轮 · ${phase}` + (end ? ` · 预计 ${end[1]} 结束` : "");
}
function remainingTimeText(seconds) {
const remaining = Math.max(0, Math.ceil(Number(seconds) || 0));
return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`;
}
function fetchOrderCountdown(orderId) {
if (!authToken || !orderId) return;
apiFetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, {
headers: { "Authorization": `Bearer ${authToken}` }
})
.then(r => r.json())
.then(data => {
if (!currentOrder || String(currentOrder.order_id) !== String(orderId) || Number(currentOrder.status) !== 2) return;
if (data.rtn_code === 0 && data.data && data.data.active) {
orderCountdownSeconds = Math.max(0, Number(data.data.remaining_seconds) || 0);
orderCountdownDeadline = performance.now() + orderCountdownSeconds * 1000;
orderCountdownOrderId = orderId;
// 多轮适配:展示计划总轮数与最终预计还车时间
const finalEl = document.getElementById("order-final-time");
const addBtn = document.getElementById("order-banner-add-round-btn");
if (finalEl) {
finalEl.textContent = rideProgressText(data.data);
finalEl.style.display = "inline";
}
if (addBtn) {
// 真实订单才可加轮; reminder 计时不显示
const eligible = data.data.order_id && String(data.data.source) !== "reminder";
addBtn.style.display = eligible ? "inline-block" : "none";
}
showOrderCountdown();
startOrderCountdown();
} else if (data.rtn_code === 0) {
hideOrderCountdown();
const progress = document.getElementById("order-final-time");
progress.textContent = "骑行中 · 计时同步中";
progress.style.display = "inline";
}
})
.catch(err => console.error("获取倒计时失败:", err));
}
function showOrderCountdown() {
const el = document.getElementById("order-countdown");
el.style.display = "inline";
updateOrderCountdownText();
}
function hideOrderCountdown() {
orderCountdownDeadline = null;
orderCountdownOrderId = null;
document.getElementById("order-banner-add-round-btn").style.display = "none";
document.getElementById("order-final-time").style.display = "none";
const el = document.getElementById("order-countdown");
el.style.display = "none";
if (orderCountdownTimer) {
clearInterval(orderCountdownTimer);
orderCountdownTimer = null;
}
}
function updateOrderCountdownText() {
const el = document.getElementById("order-countdown");
const remaining = Math.max(0, orderCountdownSeconds);
const mins = Math.floor(remaining / 60);
const secs = remaining % 60;
el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中";
// 变色提示
if (remaining <= 60) {
el.style.color = "#ff3b30";
} else if (remaining <= 300) {
el.style.color = "#ffcc00";
} else {
el.style.color = "white";
}
}
function startOrderCountdown() {
if (orderCountdownTimer) clearInterval(orderCountdownTimer);
orderCountdownTimer = setInterval(() => {
orderCountdownSeconds = Math.max(0, Math.ceil((orderCountdownDeadline - performance.now()) / 1000));
updateOrderCountdownText();
if (orderCountdownSeconds <= 0) {
clearInterval(orderCountdownTimer);
// 倒计时结束,刷新订单状态
checkOrderStatus();
}
}, 1000);
}
function hideOrderBanner() {
document.getElementById("order-banner").classList.remove("show");
hideOrderCountdown();
closeOrderActionsModal();
}
function isOrderActionEligible(order) {
if (!order) return false;
const type = String(order.type || "").toLowerCase();
const source = String(order.source || "").toLowerCase();
return type !== "reminder" && source !== "reminder";
}
function handleOrderBannerSurfaceClick(event) {
// 横幅右侧已有的两个按钮继续走原有行为,不触发全屏面板。
if (event && event.target && event.target.closest && event.target.closest("button")) return;
if (!isOrderActionEligible(currentOrder)) return;
showOrderActionsModal();
}
function showOrderActionsModal() {
if (!isOrderActionEligible(currentOrder)) return;
const modal = document.getElementById("order-actions-modal");
const meta = document.getElementById("order-actions-meta");
const status = document.getElementById("order-actions-status");
const hint = document.getElementById("order-actions-hint");
const code = currentOrder.code || currentOrder.order_id || "未知";
const pending = Number(currentOrder.status) === 1;
meta.textContent = `车辆 #${code}`;
status.textContent = pending ? "待支付订单" : "订单进行中";
status.classList.toggle("warning", pending);
status.classList.toggle("riding", !pending);
hint.textContent = pending
? "当前订单尚未支付,请先完成支付后再使用车辆操作。"
: "临时锁车不会结束订单,确认车辆停放安全后再操作。";
// 待支付订单明确不展示临时锁车/临时开车。
["order-action-lock", "order-action-unlock"].forEach(id => {
const button = document.getElementById(id);
if (button) button.style.display = pending ? "none" : "flex";
});
const pay = document.getElementById("order-action-pay");
const ret = document.getElementById("order-action-return");
if (pay) pay.style.display = pending ? "flex" : "none";
if (ret) ret.style.display = pending ? "none" : "flex";
modal.classList.add("show");
modal.setAttribute("aria-hidden", "false");
document.body.classList.add("order-actions-open");
window.setTimeout(() => document.getElementById("order-actions-close")?.focus(), 0);
}
function closeOrderActionsModal() {
const modal = document.getElementById("order-actions-modal");
if (!modal) return;
modal.classList.remove("show");
modal.setAttribute("aria-hidden", "true");
document.body.classList.remove("order-actions-open");
}
function viewBikeDetailFromOrderModal() {
closeOrderActionsModal();
viewBikeDetailFromOrder();
}
async function findCurrentOrderBike() {
if (!isOrderActionEligible(currentOrder)) return;
const code = (currentOrder.code || "").toString().trim();
if (!code) {
showToast("该订单没有车牌信息");
return;
}
const button = document.getElementById("order-action-find");
if (button) {
button.disabled = true;
button.querySelector("strong").textContent = "发送中...";
}
try {
const data = await _doFindBikeRequest(code);
if (data && (data.rtn_code === 0 || data.success)) {
showToast("寻车指令已发送,请听声音");
} else {
showToast((data && data.message) || "寻车失败");
}
} catch (err) {
console.error("订单寻车失败:", err);
showToast("寻车失败,请重试");
} finally {
if (button) {
button.disabled = false;
button.querySelector("strong").textContent = "寻车";
}
}
}
function payCurrentOrderFromModal() {
closeOrderActionsModal();
tryCardPayOrRedirect();
}
function returnCurrentOrderFromModal() {
closeOrderActionsModal();
showReturnConfirm();
}
function handleOrderBannerClick() {
if (!currentOrder) {
showToast("订单状态已变化,正在刷新,请稍后重试");
checkOrderStatus();
return;
}
if (Number(currentOrder.status) === 1) {
// 待支付 - 先检查是否有月卡/周卡
tryCardPayOrRedirect();
} else if (Number(currentOrder.status) === 2) {
// 进行中 - 显示还车确认弹窗
showReturnConfirm();
} else {
showToast("订单状态已变化,正在刷新,请稍后重试");
checkOrderStatus();
}
}
// 查看详情:等同在搜索框输入当前订单车牌并点击查询,直接弹出车辆详情
function viewBikeDetailFromOrder() {
if (!currentOrder) { showToast("当前没有进行中的订单"); return; }
const code = (currentOrder.code || "").toString().trim();
if (!code) { showToast("该订单没有车牌信息"); return; }
document.getElementById("scan-input").value = code;
scanCode();
}
document.addEventListener("keydown", event => {
if (event.key !== "Escape") return;
// 确认弹窗优先响应 ESC(原生壳没有系统对话框,全靠页面内弹窗)
const _cm = document.getElementById("app-confirm-modal");
if (_cm && _cm.classList.contains("show")) { appConfirmClose(); return; }
const _arm = document.getElementById("add-round-modal");
if (_arm && _arm.classList.contains("show")) { closeAddRoundModal(); return; }
const _oam = document.getElementById("order-actions-modal");
if (_oam && _oam.classList.contains("show")) { closeOrderActionsModal(); return; }
});
// ========== 月卡/周卡自动支付 ==========
let cardPayLoading = false;
async function tryCardPayOrRedirect() {
if (cardPayLoading || !currentOrder) return;
const btn = document.getElementById("order-banner-btn");
cardPayLoading = true;
btn.textContent = "检测中…";
btn.disabled = true;
try {
// 1. 查询可用支付方式
const methodsResp = await apiFetch(
`/api/order/pay_methods?code=${encodeURIComponent(currentOrder.code || "")}`,
{ headers: { "Authorization": `Bearer ${authToken}` } }
);
const methodsData = await methodsResp.json();
if (methodsData.rtn_code !== 0) {
// 接口失败,降级提示跳转
showToast("请到小白超人小程序支付订单");
return;
}
const cardMethods = methodsData.data?.card_methods || [];
if (cardMethods.length === 0) {
// 没有月卡/周卡 → 原来逻辑
showToast("未找到月卡,请到小白超人小程序支付");
return;
}
// 2. 优先选 get_type=2(推荐/激活)的卡,否则取第一个
const preferred = cardMethods.find(m => m.get_type === 2) || cardMethods[0];
const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡";
// 3. 更新按钮状态
btn.textContent = `${cardTypeName}支付中…`;
// 4. 调用月卡支付接口
const payResp = await apiFetch("/api/order/pay_with_card", {
method: "POST",
headers: {
"Authorization": `Bearer ${authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
order_id: currentOrder.order_id,
code: currentOrder.code || "",
type: String(preferred.type),
package_id: String(preferred.package_id)
})
});
const payData = await payResp.json();
if (payData.rtn_code === 0 && payData.data?.paid) {
// 月卡支付成功
showToast(`${cardTypeName}支付成功 ✓`);
currentOrder = null;
hideOrderBanner();
refreshMap();
} else if (payData.rtn_code === 0 && payData.data?.need_wechat_pay) {
// 月卡不足,需要微信支付
showToast("月卡余额不足,请到小白超人小程序完成支付");
} else {
showToast(payData.message || "支付失败,请到小白超人小程序支付");
}
} catch (err) {
console.error("月卡支付失败:", err);
showToast("请到小白超人小程序支付订单");
} finally {
cardPayLoading = false;
btn.textContent = "去支付";
btn.disabled = false;
}
}
// ========== 还车确认 ==========
let returnLoading = false;
let pendingReturnOrder = null;
async function getOrderOperationLocation() {
let position = null;
if (navigator.geolocation) {
position = await new Promise(resolve => {
navigator.geolocation.getCurrentPosition(
pos => resolve(pos),
err => {
console.error("获取位置失败:", err);
resolve(null);
},
{ timeout: 5000 }
);
});
}
const latitude = Number.isFinite(position?.coords?.latitude)
? position.coords.latitude : 36.67;
const longitude = Number.isFinite(position?.coords?.longitude)
? position.coords.longitude : 116.98;
return { latitude, longitude };
}
function showReturnConfirm() {
if (returnLoading) return;
if (!currentOrder || Number(currentOrder.status) !== 2) {
showToast("当前没有可还车的进行中订单,正在刷新");
checkOrderStatus();
return;
}
pendingReturnOrder = { ...currentOrder };
document.getElementById("return-confirm-text").textContent =
`车辆 #${currentOrder.code || currentOrder.order_id} 正在骑行,确认要还车吗?`;
document.getElementById("return-confirm-modal").classList.add("show");
document.getElementById("return-confirm-btn").disabled = false;
document.getElementById("return-confirm-btn").textContent = "确认还车";
}
function closeReturnConfirm() {
document.getElementById("return-confirm-modal").classList.remove("show");
pendingReturnOrder = null;
}
async function doReturnBike() {
if (returnLoading) return;
const order = pendingReturnOrder;
if (!order) {
showToast("请重新点击还车并确认订单");
return;
}
returnLoading = true;
const btn = document.getElementById("return-confirm-btn");
btn.disabled = true;
btn.textContent = "还车中...";
try {
// 还车和临时锁车共用同一套当前位置获取逻辑。
const { latitude, longitude } = await getOrderOperationLocation();
const resp = await apiFetch("/api/order/return", {
method: "POST",
headers: {
"Authorization": `Bearer ${authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
order_id: order.order_id,
code: order.code,
latitude: latitude,
longitude: longitude
})
});
const data = await resp.json();
if (data.rtn_code === 0) {
let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功";
// 显示月卡支付结果
if (data.card_pay) {
msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`;
}
showToast(msg);
closeReturnConfirm();
if (!currentOrder || String(currentOrder.order_id) === String(order.order_id)) {
currentOrder = null;
hideOrderBanner();
}
// 刷新地图
refreshMap();
refreshShareBanners();
} else {
showToast(data.message || "还车失败");
}
} catch (err) {
showToast("还车失败,请重试");
} finally {
returnLoading = false;
btn.disabled = false;
btn.textContent = "确认还车";
}
}
let orderTempActionLoading = false;
async function tempLockCurrentOrder() {
if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return;
const button = document.getElementById("order-action-lock");
orderTempActionLoading = true;
if (button) {
button.disabled = true;
button.querySelector("strong").textContent = "锁车中...";
}
try {
const { latitude, longitude } = await getOrderOperationLocation();
const resp = await apiFetch("/api/order/temp_lock", {
method: "POST",
headers: {
"Authorization": `Bearer ${authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
order_id: currentOrder.order_id,
code: currentOrder.code,
latitude,
longitude
})
});
const data = await resp.json();
if (data.rtn_code === 0) {
showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功");
const status = document.getElementById("order-actions-status");
if (status) status.textContent = "车辆已临时锁定,订单仍在进行中";
} else {
showToast(data.message || "临时锁车失败");
}
} catch (err) {
console.error("临时锁车失败:", err);
showToast("临时锁车失败,请重试");
} finally {
orderTempActionLoading = false;
if (button) {
button.disabled = false;
button.querySelector("strong").textContent = "临时锁车";
}
}
}
async function tempUnlockCurrentOrder() {
if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return;
const button = document.getElementById("order-action-unlock");
orderTempActionLoading = true;
if (button) {
button.disabled = true;
button.querySelector("strong").textContent = "开车中...";
}
try {
const resp = await apiFetch("/api/order/temp_unlock", {
method: "POST",
headers: {
"Authorization": `Bearer ${authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ order_id: currentOrder.order_id })
});
const data = await resp.json();
if (data.rtn_code === 0) {
showToast(data.message || "临时开车成功");
const status = document.getElementById("order-actions-status");
if (status) status.textContent = "车辆正在解锁,请稍候";
} else {
showToast(data.message || "临时开车失败");
}
} catch (err) {
console.error("临时开车失败:", err);
showToast("临时开车失败,请重试");
} finally {
orderTempActionLoading = false;
if (button) {
button.disabled = false;
button.querySelector("strong").textContent = "临时开车";
}
}
}
// ========== 一键开锁 ==========
let unlockPendingCode = null; // 待开锁的车牌
let unlockPendingPosition = null; // 待开锁的位置
function handleQuickUnlock() {
const qrBox = document.getElementById("qrcode-box");
const code = qrBox.dataset.bikeCode;
if (!code) {
showToast("无法获取车辆编码");
return;
}
if (!currentUser) {
showToast("请先登录");
return;
}
// 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位)
const baseLat = parseFloat(selectedBike?.latitude) || 36.67;
const baseLng = parseFloat(selectedBike?.longitude) || 116.98;
const jit = 0.0001;
unlockPendingCode = code;
unlockPendingPosition = {
lat: baseLat + (Math.random() * 2 - 1) * jit,
lng: baseLng + (Math.random() * 2 - 1) * jit
};
// 有共享绑定 → 先选开锁账号;否则直接确认
openUnlockAccountChooser();
}
// ===== 开锁账号选择(自己 / 共享者列表) =====
let unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
let unlockSrcList = [];
let unlockSrcShowAll = false;
function openUnlockAccountChooser() {
unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
unlockSrcShowAll = false;
if (!authToken || !currentUser) { proceedToUnlockConfirm(); return; }
apiFetch("/api/share/sources", { headers: { "Authorization": "Bearer " + authToken } })
.then(r => r.json())
.then(data => {
if (data.rtn_code !== 0 || !data.data) { proceedToUnlockConfirm(); return; }
const d = data.data;
if (!d.has_any) { proceedToUnlockConfirm(); return; }
renderUnlockSrcList(d);
document.getElementById("unlock-src-modal").classList.add("show");
})
.catch(() => proceedToUnlockConfirm());
}
function renderUnlockSrcList(d) {
const box = document.getElementById("unlock-src-list");
let html = "";
html += '<button class="unlock-src-item" onclick="chooseUnlockSrc(0)"><span>自己的账号</span><span class="tag">自己付费</span></button>';
const srcs = d.sources || [];
unlockSrcList = srcs.slice();
if (srcs.length === 0 && d.hidden_count > 0) {
html += '<div class="share-desc">共享者今日次数都已用完,可查看或直接用自己的账号。</div>';
}
srcs.forEach(s => {
const dis = s.can_use ? "" : "unavailable";
const tagTxt = s.can_use ? ("剩余可用 " + s.remaining_today + " 次") : (s.reasons && s.reasons.length ? s.reasons.join(" / ") : "不可用");
const label = partnerLabel(s.owner_name, s.owner_email, s.remark);
html += '<button class="unlock-src-item ' + dis + '" onclick="chooseUnlockSrc(' + s.owner_user_id + ')"><span>' + escHtml(label) + '</span><span class="tag">' + escHtml(tagTxt) + '</span></button>';
});
if (d.hidden_count > 0) {
html += '<a class="unlock-src-more" onclick="event.stopPropagation();loadUnlockSrcShowAll()">还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)</a>';
}
box.innerHTML = html;
}
function loadUnlockSrcShowAll() {
unlockSrcShowAll = true;
apiFetch("/api/share/sources?show_unavailable=1", { headers: { "Authorization": "Bearer " + authToken } })
.then(r => r.json())
.then(data => { if (data.rtn_code === 0) renderUnlockSrcList(data.data); });
}
function chooseUnlockSrc(ownerId) {
ownerId = ownerId || 0;
const rec = unlockSrcList.find(x => Number(x.owner_user_id) === Number(ownerId));
if (ownerId && !rec) { closeUnlockSrc(); return; }
unlockChoice = rec
? { mode: "shared", owner_user_id: rec.owner_user_id, owner_email: rec.owner_email,
owner_display: partnerLabel(rec.owner_name, rec.owner_email, rec.remark) }
: { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
closeUnlockSrc();
proceedToUnlockConfirm();
}
function closeUnlockSrc() {
document.getElementById("unlock-src-modal").classList.remove("show");
}
function proceedToUnlockConfirm() {
if (!unlockPendingCode) return;
const btn = document.getElementById("unlock-confirm-btn");
btn.disabled = false;
btn.textContent = unlockChoice.mode === "shared"
? ("确认用 " + (unlockChoice.owner_display || "对方") + " 的共享开锁")
: "确认开锁";
// 开锁前预览:月卡余量 + 自动续租轮次预估(共享单用车主的卡)
loadUnlockPreview(unlockPendingCode,
unlockChoice.mode === "shared" ? unlockChoice.owner_user_id : null);
document.getElementById("unlock-confirm-modal").classList.add("show");
}
function closeUnlockConfirm() {
document.getElementById("unlock-confirm-modal").classList.remove("show");
unlockPendingCode = null;
unlockPendingPosition = null;
}
async function doUnlockBike() {
if (!unlockPendingCode || !authToken) {
closeUnlockConfirm();
return;
}
const btn = document.getElementById("unlock-confirm-btn");
btn.disabled = true;
btn.textContent = "开锁中...";
const isShared = unlockChoice && unlockChoice.mode === "shared";
try {
const payload = {
code: unlockPendingCode,
latitude: unlockPendingPosition.lat,
longitude: unlockPendingPosition.lng
};
if (isShared) payload.owner_user_id = unlockChoice.owner_user_id;
const resp = await apiFetch(isShared ? "/api/order/shared_unlock" : "/api/order/unlock", {
method: "POST",
headers: {
"Authorization": `Bearer ${authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
const data = await resp.json();
console.log("[开锁] 响应:", data);
closeUnlockConfirm();
if (data.rtn_code === 0) {
showToast(data.message || "开锁成功!");
closeQrModal();
if (isShared) {
// 共享开锁:横幅由后端订单状态驱动,不启动本地计时
refreshShareBanners();
checkOrderStatus();
} else {
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
const _ud = data.data || {};
startRentalFromServer(data.order_id, unlockPendingCode, 19,
_ud.end_time, _ud);
// 刷新订单状态
checkOrderStatus();
}
} else if (data.need_pay) {
// 未支付订单月卡也付不了 → 提示用户并刷新订单横幅
showToast(data.message || "存在未支付订单,请先支付");
checkOrderStatus(); // 刷新横幅显示待支付
} else {
showToast(data.message || "开锁失败");
}
} catch (err) {
console.error("[开锁] 请求失败:", err);
showToast("开锁失败,请重试");
} finally {
btn.disabled = false;
btn.textContent = isShared ? "确认共享开锁" : "确认开锁";
unlockPendingCode = null;
unlockPendingPosition = null;
unlockChoice = { mode: "own", owner_user_id: null, owner_email: null };
}
}
async function quickUnlock(code, latitude, longitude) {
if (!authToken) {
showToast("请先登录");
return;
}
try {
const resp = await apiFetch("/api/order/unlock", {
method: "POST",
headers: {
"Authorization": `Bearer ${authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
code: code,
latitude: latitude,
longitude: longitude
})
});
const data = await resp.json();
console.log("[开锁] 响应:", data); // 调试日志
if (data.rtn_code === 0) {
showToast(data.message || "开锁成功!");
closeQrModal();
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
const _qd = data.data || {};
startRentalFromServer(data.order_id, code, 19, _qd.end_time, _qd);
// 刷新订单状态
checkOrderStatus();
} else {
showToast(data.message || "开锁失败");
}
} catch (err) {
console.error("[开锁] 请求失败:", err); // 调试日志
showToast("开锁失败,请重试");
}
}
// 从后端计时器启动前端计时器(隐藏横幅,由后端控制邮件通知)
function startRentalFromServer(rentalId, bikeCode, durationMinutes, endTime, summary) {
// 启动本地计时器(不显示横幅,由后端统一管理)
const remaining = durationMinutes * 60;
activeRental = {
rental_id: rentalId,
bike_code: bikeCode,
remaining_seconds: remaining,
source: "unlock", // 网页开锁 → 真实订单,+1轮可用
end_time: endTime || null,
final_end_time: (summary && summary.final_end_time) || endTime || null,
current_round: (summary && summary.current_round) || 1,
total_rounds: (summary && summary.total_rounds) || null,
auto_return: true
};
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
// 启动倒计时更新(每秒)
if (rentalCountdownTimer) clearInterval(rentalCountdownTimer);
rentalCountdownTimer = setInterval(() => {
if (activeRental && activeRental.remaining_seconds > 0) {
activeRental.remaining_seconds--;
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
// 到期动作由后端依据订单类型及用户设置执行
// 这里不需要做任何操作
}
}, 1000);
}
// ========== 开锁前预览(月卡余量 + 轮次预估) ==========
function renderUnlockPreview(p) {
const box = document.getElementById("unlock-preview");
if (!box) return;
if (!p) { box.style.display = "none"; box.innerHTML = ""; return; }
const lines = [];
lines.push(`<div><b style="color:var(--text-primary);">${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}</b></div>`);
if (p.has_card) {
const cardText = (p.cards || []).slice(0, 3).map(c =>
`${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(",");
lines.push(`<div>优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}</div>`);
} else {
lines.push(`<div style="color:#c62828;">未检测到优惠卡:本次费用将按小程序计费(还车后需支付)</div>`);
}
if (p.auto_return) {
lines.push(`<div>自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车</div>`);
} else {
lines.push(`<div>自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车</div>`);
}
box.innerHTML = lines.join("");
box.style.display = "block";
}
async function loadUnlockPreview(code, ownerUserId) {
const box = document.getElementById("unlock-preview");
if (box) { box.style.display = "block"; box.innerHTML = '<div style="color:var(--text-secondary);">预览加载中...</div>'; }
try {
const q = new URLSearchParams({ code: String(code) });
if (ownerUserId) q.set("owner_user_id", ownerUserId);
const resp = await apiFetch(`/api/order/preview?${q.toString()}`, {
headers: { "Authorization": `Bearer ${authToken}` }
});
const data = await resp.json();
renderUnlockPreview(data.rtn_code === 0 ? data.data : null);
} catch (err) {
renderUnlockPreview(null);
}
}
// ========== 手动 +1 轮 ==========
// ========== 手动 +1 轮(带确认弹窗) ==========
// 语义:只把「计划轮数」+1。当前这一轮照常到点 → 自动还车 → 优惠卡支付
// → 立刻重新开锁同一辆车进入下一轮(绝不延长本轮时长)。
let _addRoundTarget = null;
function showAddRoundConfirm(target) {
_addRoundTarget = target;
const remainSec = target.kind === "rental"
? (activeRental && activeRental.remaining_seconds) || orderCountdownSeconds || 0
: orderCountdownSeconds || 0;
const mins = Math.max(1, Math.round(remainSec / 60));
const btn = document.getElementById("add-round-confirm-btn");
if (btn) { btn.disabled = false; btn.textContent = "确认加 1 轮"; }
const text = document.getElementById("add-round-text");
if (text) {
text.innerHTML =
`当前这一轮还剩约 <b>${mins} 分钟</b>,<b>不会延长</b>。<br/>` +
`到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`;
}
document.getElementById("add-round-modal").classList.add("show");
}
function closeAddRoundModal() {
document.getElementById("add-round-modal").classList.remove("show");
_addRoundTarget = null;
}
async function confirmAddRound() {
if (!_addRoundTarget || !authToken) { closeAddRoundModal(); return; }
const btn = document.getElementById("add-round-confirm-btn");
if (btn) { btn.disabled = true; btn.textContent = "提交中..."; }
const payload = _addRoundTarget.kind === "rental"
? { rental_id: _addRoundTarget.value }
: { order_id: _addRoundTarget.value };
try {
const resp = await apiFetch("/api/order/add_round", {
method: "POST",
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
const data = await resp.json();
if (data.rtn_code === 0) {
showToast(data.message || "已加 1 轮");
// 本轮剩余不变,只更新计划轮数与预计还车时间
if (activeRental) {
activeRental.total_rounds = data.data.total_rounds;
activeRental.final_end_time = data.data.final_end_time;
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
updateRentalFinalTime();
}
if (currentOrder && currentOrder.order_id) fetchOrderCountdown(currentOrder.order_id);
checkOrderStatus();
} else {
showToast(data.message || "加轮失败");
}
} catch (err) {
showToast("网络错误,请重试");
} finally {
closeAddRoundModal();
}
}
function addRoundForCurrent() {
if (!activeRental || !authToken) { showToast("当前没有进行中的订单"); return; }
showAddRoundConfirm({ kind: "rental", value: activeRental.rental_id });
}
function addRoundFromBanner() {
if (!currentOrder || !currentOrder.order_id) { showToast("当前没有进行中的订单"); return; }
showAddRoundConfirm({ kind: "order", value: currentOrder.order_id });
}
// 页面加载时检查订单状态和租车状态
document.addEventListener("DOMContentLoaded", async () => {
if (authToken) {
await syncWechatOrder(); // 先同步微信订单状态
checkOrderStatus();
checkRentalStatus(); // 再恢复租车横幅
checkStrictGuide(); // 强签名验证:缺 AccessToken 进页面立即引导
refreshAuthExpiry(); // 登录态有效期:不足 2 天在主页面挂提醒横幅
}
});
+499
View File
@@ -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();
});
+345
View File
@@ -0,0 +1,345 @@
// ================= 共享电动车 =================
function shareApi(url, method, body) {
const opts = { method: method || "GET", headers: {} };
if (authToken) opts.headers["Authorization"] = `Bearer ${authToken}`;
if (body !== undefined) {
opts.headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(body);
}
return apiFetch(url, opts).then(r => r.json());
}
// ===== 私密备注(昵称) 工具 =====
// 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱
function partnerLabel(name, email, remark) {
return (remark && String(remark).trim()) || name || email || "";
}
// share_id -> {email,name,remark},备注编辑用(不把用户文本嵌进 HTML 属性/JS 字面量)
let shareRec = {};
// ---------- 管理弹窗 ----------
let shareTabNow = "usable";
function openShareModal() {
if (!authToken || !currentUser) { showToast("请先登录"); return; }
SettingsPages.open("share-modal");
switchShareTab(shareTabNow);
loadShareData();
}
function closeShareModal() {
SettingsPages.back();
}
function switchShareTab(tab) {
shareTabNow = tab;
document.getElementById("share-tab-usable").classList.toggle("active", tab === "usable");
document.getElementById("share-tab-mine").classList.toggle("active", tab === "mine");
document.getElementById("share-list-usable").style.display = tab === "usable" ? "flex" : "none";
document.getElementById("share-list-mine").style.display = tab === "mine" ? "flex" : "none";
loadShareData();
}
function sharePendingHtml(pending) {
if (!pending || !pending.length) { document.getElementById("share-pending-box").style.display = "none"; return; }
const rows = pending.map(p =>
`<div class="prow"><span>等待接受:<b>${escHtml(p.from_email||'')}</b></span>
<span style="display:flex;gap:6px;flex-shrink:0">
<button class="share-mini-btn danger" onclick="rejectShareRequest(${p.id})">拒绝</button>
<button class="share-mini-btn primary" onclick="acceptShareRequest(${p.id}, '${(p.from_email||'').replace(/'/g,"")}')">接受</button>
</span></div>`).join("");
const box = document.getElementById("share-pending-box");
box.innerHTML = `<div style="font-weight:600;margin-bottom:2px;">待处理的共享申请</div>${rows}`;
box.style.display = "block";
}
async function loadShareData() {
if (!authToken) return;
try {
const data = await shareApi("/api/share/list");
if (data.rtn_code !== 0) { showToast(data.message || "加载失败"); return; }
const d = data.data || { usable: [], shared: [] };
shareRec = {};
document.getElementById("share-list-usable").innerHTML = d.usable.map(u => {
const uLabel = partnerLabel(u.owner_name, u.owner_email, u.remark);
shareRec[u.share_id] = { email: u.owner_email || "", name: u.owner_name || "", remark: u.remark || "" };
const state = u.can_use
? ('<div class="share-row-state ok">今日可用 ' + u.remaining_today + '/' + u.daily_limit + ' 次 · 对方需有优惠卡' + (u.require_card ? "是" : "否") + '</div>')
: ('<div class="share-row-state err">不可用:' + (u.reasons && u.reasons.length ? u.reasons.join(";") : "今日次数已用完") + '</div>');
return '<div class="share-row">'
+ '<div class="share-row-top"><span class="share-row-email">' + escHtml(uLabel) + '</span></div>'
+ state
+ '<div class="share-row-btns">'
+ '<button class="share-mini-btn primary" onclick="openShareRemark(' + u.share_id + ')">备注</button>'
+ '<button class="share-mini-btn danger" onclick="unbindShare(' + u.share_id + ')">解绑</button>'
+ '</div></div>';
}).join("");
document.getElementById("share-list-mine").innerHTML = d.shared.map(sr => {
const sLabel = partnerLabel(sr.rider_name, sr.rider_email, sr.remark);
shareRec[sr.share_id] = { email: sr.rider_email || "", name: sr.rider_name || "", remark: sr.remark || "" };
return '<div class="share-row">'
+ '<div class="share-row-top"><span class="share-row-email">' + escHtml(sLabel) + '</span>'
+ '<span style="font-size:12px;color:var(--text-secondary);flex-shrink:0;">今日已用 ' + sr.rider_used_today + '/' + sr.daily_limit + '</span></div>'
+ '<div class="share-row-state">每天 ' + sr.daily_limit + ' 次' + (sr.require_card ? (' · 需我有优惠卡且剩余 ≥ ' + sr.card_min_times) : " · 无卡要求") + '</div>'
+ '<div class="share-row-btns">'
+ '<button class="share-mini-btn primary" onclick="openShareRemark(' + sr.share_id + ')">备注</button>'
+ '<button class="share-mini-btn primary" onclick="openShareConfig(' + sr.share_id + ', ' + sr.daily_limit + ', ' + (sr.require_card ? 1 : 0) + ', ' + sr.card_min_times + ', \'' + String(sr.rider_email || "").replace(/'/g, "") + '\')">修改权限</button>'
+ '<button class="share-mini-btn danger" onclick="unbindShare(' + sr.share_id + ')">解绑</button>'
+ '</div></div>';
}).join("");
const pending = await shareApi("/api/share/pending");
if (pending.rtn_code === 0) sharePendingHtml(pending.data || []);
} catch (e) { console.error("[share] load失败", e); }
}
async function sendShareRequest() {
if (!authToken) { showToast("请先登录"); return; }
const email = document.getElementById("share-req-email").value.trim();
if (!email) { showToast("请输入对方邮箱"); return; }
const btn = document.querySelector(".share-req-row button");
if (btn) { btn.disabled = true; }
try {
const data = await shareApi("/api/share/request", "POST", { to_email: email });
showToast(data.message || (data.rtn_code === 0 ? "已发送" : "发送失败"));
if (data.rtn_code === 0) document.getElementById("share-req-email").value = "";
} finally {
if (btn) { btn.disabled = false; }
}
}
async function acceptShareRequest(reqId, fromEmail) {
const askM = document.getElementById("share-ask-modal");
if (askM) askM.classList.remove("show");
shareAskActive = false;
try {
const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: true });
if (data.rtn_code === 0 && data.data) {
showToast("已接受,请设置权限");
openShareConfig(data.data.share_id, data.data.daily_limit, data.data.require_card, data.data.card_min_times, data.data.rider_email);
} else {
showToast(data.message || "操作失败");
}
} finally {
loadShareData();
checkPendingShareRequests();
}
}
async function rejectShareRequest(reqId) {
const askM = document.getElementById("share-ask-modal");
if (askM) askM.classList.remove("show");
shareAskActive = false;
try {
const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: false });
showToast(data.message || "已拒绝");
} finally {
loadShareData();
checkPendingShareRequests();
}
}
// ---------- 权限设置 ----------
let shareCfg = { share_id: null };
function openShareConfig(shareId, daily, requireCard, minTimes, email) {
shareCfg = { share_id: shareId };
document.getElementById("share-config-title").textContent = email ? `为 ${email} 设置共享权限` : "";
document.getElementById("sharecfg-daily").value = daily ?? 3;
document.getElementById("sharecfg-card").checked = !!requireCard;
document.getElementById("sharecfg-mintimes").value = minTimes ?? 0;
SettingsPages.open("share-config-modal");
}
function closeShareConfig() {
SettingsPages.back();
setTimeout(() => checkPendingShareRequests(), 0);
}
async function saveShareConfig() {
if (!shareCfg.share_id) return;
const daily = parseInt(document.getElementById("sharecfg-daily").value, 10) || 0;
const require_card = document.getElementById("sharecfg-card").checked ? 1 : 0;
const minTimes = parseInt(document.getElementById("sharecfg-mintimes").value, 10) || 0;
const data = await shareApi("/api/share/config", "POST", {
share_id: shareCfg.share_id, daily_limit: daily, require_card, card_min_times: minTimes
});
showToast(data.message || (data.rtn_code === 0 ? "权限已保存" : "保存失败"));
if (data.rtn_code === 0) closeShareConfig();
loadShareData();
checkPendingShareRequests();
}
async function unbindShare(shareId) {
if (!(await appConfirm("解绑后对方将无法再用你的共享额度开锁,可随时重新申请。", { title: "解绑共享关系", okText: "解绑", danger: true }))) return;
const data = await shareApi("/api/share/unbind", "POST", { share_id: shareId });
showToast(data.message || "已解绑");
loadShareData();
refreshShareBanners();
}
// ---------- 给对方的私密备注(昵称) ----------
let shareRemarkCfg = { share_id: null };
function openShareRemark(shareId) {
const rec = shareRec[shareId];
if (!rec) return;
shareRemarkCfg.share_id = shareId;
document.getElementById("share-remark-input").value = rec.remark || "";
const shown = partnerLabel(rec.name, rec.email, rec.remark);
document.getElementById("share-remark-desc").innerHTML =
'给 <b>' + escHtml(shown) + '</b> 起一个昵称备注,仅自己可见;未设置时对 TA 的显示退回邮箱 (<b>' + escHtml(rec.email || "") + '</b>)。';
SettingsPages.open("share-remark-modal");
}
function closeShareRemark() {
SettingsPages.back();
shareRemarkCfg.share_id = null;
}
async function saveShareRemark() {
if (!shareRemarkCfg.share_id) return;
const remark = document.getElementById("share-remark-input").value.trim();
const btn = document.querySelector("#share-remark-modal .auth-submit");
if (btn) btn.disabled = true;
try {
const data = await shareApi("/api/share/remark", "POST", { share_id: shareRemarkCfg.share_id, remark: remark });
showToast(data.message || (data.rtn_code === 0 ? "备注已保存" : "保存失败"));
if (data.rtn_code === 0) closeShareRemark();
loadShareData();
refreshShareBanners();
} catch (e) { console.error("[share] remark失败", e); showToast("保存失败"); }
finally { if (btn) btn.disabled = false; }
}
// ---------- 全屏接收申请 ----------
let shareAskQueue = [];
let shareAskActive = false;
let shareAskCur = null;
async function checkPendingShareRequests() {
if (!authToken || shareAskActive) return;
try {
const data = await shareApi("/api/share/pending");
if (data.rtn_code === 0 && data.data && data.data.length) {
shareAskQueue = data.data.slice();
nextShareAskIfQueue();
}
} catch (e) { /* 忽略 */ }
}
function nextShareAskIfQueue() {
if (shareAskQueue.length > 0) {
shareAskCur = shareAskQueue.shift();
shareAskActive = true;
document.getElementById("share-ask-from").textContent = shareAskCur.from_email || "";
document.getElementById("share-ask-modal").classList.add("show");
} else if (shareAskActive) {
shareAskActive = false;
document.getElementById("share-ask-modal").classList.remove("show");
}
}
async function acceptCurrentShareAsk() {
if (!shareAskCur) return;
await acceptShareRequest(shareAskCur.id, shareAskCur.from_email);
// 接受后弹权限设置由 acceptShareRequest 处理;队列推进
}
async function rejectCurrentShareAsk() {
if (!shareAskCur) return;
await rejectShareRequest(shareAskCur.id);
}
// ---------- 共享横幅(车主:共享中 / 骑行者:使用中) ----------
let shareActiveList = [];
let pendingShareReturn = null;
async function refreshShareBanners() {
const cont = document.getElementById("share-banners");
if (!cont) return;
if (!authToken || !currentUser) { cont.innerHTML = ""; return; }
try {
const data = await shareApi("/api/share/active");
if (data.rtn_code !== 0) return;
shareActiveList = data.data || [];
shareActiveList.forEach(it => { it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1000; });
let html = "";
shareActiveList.forEach((it, idx) => {
const isOwner = it.role === "owner";
const label = partnerLabel(it.partner_name, it.partner_email, it.remark);
const esc = escHtml(label);
const bike = escHtml(it.bike_code || "");
let text;
if (isOwner) {
text = '<span>共享中</span><b style="margin:0 4px;">#' + bike + '</b><span style="opacity:.85;">' + esc + ' 使用中</span>';
} else {
text = '<span>使用 ' + esc + ' 的车中</span><b style="margin:0 4px;">#' + bike + '</b>';
}
html += '<div class="share-banner show ' + (isOwner ? "" : "rider") + '">'
+ '<div class="share-banner-copy"><div class="share-banner-title">' + text + '</div>'
+ '<div class="banner-progress"><span id="share-countdown-' + idx + '">本轮剩余 ' + remainingTimeText(it.remaining_seconds) + '</span>'
+ '<span>' + escHtml(rideProgressText(it)) + '</span></div></div>'
+ '<button class="share-banner-btn" onclick="openShareReturnByIdx(' + idx + ')">还车</button>'
+ '</div>';
});
cont.innerHTML = html;
} catch (e) { console.error("[share] banners失败", e); }
}
function openShareReturnByIdx(idx) {
const it = shareActiveList[idx];
if (!it) return;
pendingShareReturn = it;
const isOwner = it.role === "owner";
const label = partnerLabel(it.partner_name, it.partner_email, it.remark);
const esc = escHtml(label);
const bike = escHtml(it.bike_code || "");
const box = document.getElementById("share-return-text");
box.innerHTML = isOwner
? ('你的共享电动车 <b>#' + bike + '</b> 正被 ' + esc + ' 使用,确认替他/她还车?')
: ('你正在使用 <b>' + esc + '</b> 的车 <b>#' + bike + '</b>,确认还车?');
document.getElementById("share-return-modal").classList.add("show");
}
function updateShareCountdowns() {
shareActiveList.forEach((it, idx) => {
const el = document.getElementById('share-countdown-' + idx);
if (!el) return;
const seconds = Math.max(0, Math.ceil((it._countdownDeadline - performance.now()) / 1000));
el.textContent = seconds > 0 ? '本轮剩余 ' + remainingTimeText(seconds) : '本轮到期 · 同步状态中';
});
}
setInterval(updateShareCountdowns, 1000);
// HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉)
function closeShareReturnModal() {
const modal = document.getElementById("share-return-modal");
if (modal) modal.classList.remove("show");
pendingShareReturn = null;
}
async function confirmShareReturn() {
if (!pendingShareReturn) return;
const it = pendingShareReturn;
const btn = document.querySelector("#share-return-modal .auth-submit");
if (btn) { btn.disabled = true; btn.textContent = "还车中..."; }
try {
let position = null;
if (navigator.geolocation) {
position = await new Promise(resolve => {
navigator.geolocation.getCurrentPosition(
pos => resolve(pos),
() => resolve(null),
{ timeout: 5000 });
});
}
const latitude = position?.coords?.latitude || 36.67;
const longitude = position?.coords?.longitude || 116.98;
const data = await shareApi("/api/share/return", "POST", {
order_id: it.order_id, latitude, longitude
});
showToast(data.message || (data.rtn_code === 0 ? "还车成功" : "还车失败"));
if (data.rtn_code === 0) {
closeShareReturnModal();
pendingShareReturn = null;
await Promise.all([refreshShareBanners(), checkOrderStatus(), refreshMap()]);
}
} catch (e) {
showToast("还车失败,请重试");
} finally {
if (btn) { btn.disabled = false; btn.textContent = "确认还车"; }
}
}
// ---------- 初始化(登录后/页面加载) ----------
function shareAfterLogin() {
refreshShareBanners();
setTimeout(() => checkPendingShareRequests(), 800);
}
document.addEventListener("DOMContentLoaded", () => {
if (authToken) shareAfterLogin();
setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000);
setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000);
setTimeout(maybeAutoShowVersion, 1200);
});
+96
View File
@@ -0,0 +1,96 @@
// ========== 订阅提醒(编辑、复制与最近执行结果) ==========
let subscribeLocations = [], subscribeRuleCache = [], subscribeEditId = null;
const SUB_WEEKDAYS = {0:"每天",1:"周一",2:"周二",3:"周三",4:"周四",5:"周五",6:"周六",7:"周日"};
async function openSubscribeModal() {
closeAllModals(); SettingsPages.open("subscribe-modal");
await loadSubscribeLocations(); resetSubscribeEditor(); await loadSubscribeRules();
}
function closeSubscribeModal() { SettingsPages.back(); }
async function loadSubscribeLocations() {
const select = document.getElementById("sub-location");
try {
const response = await apiFetch("/api/campus/locations"); const data = await response.json();
subscribeLocations = (data.data || []).filter(p => p.kind === "parking");
select.innerHTML = subscribeLocations.length ? subscribeLocations.map(p => `<option value="${p.id}">${escHtml(p.name)}</option>`).join("") : '<option value="">管理员尚未配置停车点</option>';
} catch (error) { select.innerHTML = '<option value="">加载失败,请返回后重试</option>'; }
}
function subRuleRowHtml(rule) {
const time = `${String(Math.floor(rule.minute_of_day / 60)).padStart(2,"0")}:${String(rule.minute_of_day % 60).padStart(2,"0")}`;
const status = {success:"执行成功", failed:"执行失败", no_match:"没有符合条件的车辆", running:"执行中"}[rule.last_run_status] || "尚未执行";
return `<article class="sub-rule"><div class="sub-rule-head"><strong>${escHtml(rule.location_name || "停车点已删除")}</strong><span>${SUB_WEEKDAYS[rule.weekday]} ${time}</span></div><div class="sub-rule-meta">${rule.enabled ? "已启用" : "已停用"} · ${(rule.kind_labels || []).join("/")} · 电量 ${rule.min_electric}-${rule.max_electric}% · ${rule.auto_unlock ? "自动开锁" : "仅提醒"}</div><div class="sub-rule-result">${status}${rule.last_run_at ? " · " + escHtml(rule.last_run_at) : ""}${rule.last_run_message ? "<br>" + escHtml(rule.last_run_message) : ""}</div><div class="sub-rule-actions"><button onclick="editSubscribeRule(${rule.id},false)">编辑</button><button onclick="editSubscribeRule(${rule.id},true)">复制</button><button onclick="toggleSubscribeRule(${rule.id},${rule.enabled ? 0 : 1})">${rule.enabled ? "停用" : "启用"}</button><button class="danger" onclick="deleteSubscribeRule(${rule.id})">删除</button></div></article>`;
}
async function loadSubscribeRules() {
const box = document.getElementById("subscribe-list");
box.innerHTML = '<div class="device-loading">正在加载订阅...</div>';
try {
const response = await apiFetch("/api/subscribe/rules", {headers:{Authorization:`Bearer ${authToken}`}}); const data = await response.json();
if (data.rtn_code !== 0) throw new Error(data.message || "加载失败");
subscribeRuleCache = data.data || [];
box.innerHTML = subscribeRuleCache.length ? subscribeRuleCache.map(subRuleRowHtml).join("") : '<div class="device-loading">暂无订阅,可以在下方添加停车点和用车时间。</div>';
} catch (error) { box.innerHTML = `<div class="device-loading">${escHtml(error.message)},请返回后重试。</div>`; }
}
function toggleSubAdvanced() { const box = document.getElementById("sub-advanced"); box.style.display = box.style.display === "none" ? "block" : "none"; }
function resetSubscribeEditor() {
subscribeEditId = null;
document.getElementById("sub-editor-title").textContent = "新增规则";
document.getElementById("sub-save").textContent = "添加规则";
document.getElementById("sub-cancel-edit").hidden = true;
document.getElementById("sub-weekday").value = "0";
document.getElementById("sub-time").value = "11:55";
document.getElementById("sub-notify").checked = true;
document.getElementById("sub-auto").checked = false;
document.getElementById("sub-min-e").value = 0;
document.getElementById("sub-max-e").value = 100;
document.getElementById("sub-sort").value = "electric_desc";
document.getElementById("sub-retry").value = 3;
document.querySelectorAll(".sub-kind").forEach(el => el.checked = true);
}
function editSubscribeRule(id, copy) {
const rule = subscribeRuleCache.find(r => r.id === id); if (!rule) return;
subscribeEditId = copy ? null : id;
document.getElementById("sub-editor-title").textContent = copy ? "复制规则(保存后新增)" : "编辑规则";
document.getElementById("sub-save").textContent = copy ? "添加副本" : "保存修改";
document.getElementById("sub-cancel-edit").hidden = false;
document.getElementById("sub-location").value = rule.location_id;
document.getElementById("sub-weekday").value = rule.weekday;
document.getElementById("sub-time").value = `${String(Math.floor(rule.minute_of_day / 60)).padStart(2,"0")}:${String(rule.minute_of_day % 60).padStart(2,"0")}`;
document.getElementById("sub-notify").checked = rule.notify_enabled;
document.getElementById("sub-auto").checked = rule.auto_unlock;
document.getElementById("sub-min-e").value = rule.min_electric;
document.getElementById("sub-max-e").value = rule.max_electric;
document.getElementById("sub-sort").value = rule.sort_by;
document.getElementById("sub-retry").value = rule.retry_times;
document.querySelectorAll(".sub-kind").forEach(el => el.checked = rule.kinds.includes(el.value));
document.getElementById("sub-advanced").style.display = "block";
document.getElementById("sub-time").focus({preventScroll:true});
document.getElementById("sub-editor-title").scrollIntoView({block:"nearest"});
}
async function addSubscribeRule() {
return AppAPI.run("subscription-save", document.getElementById("sub-save"), async () => {
const payload = {location_id:Number(document.getElementById("sub-location").value), weekday:Number(document.getElementById("sub-weekday").value), time:document.getElementById("sub-time").value,
notify_enabled:document.getElementById("sub-notify").checked, auto_unlock:document.getElementById("sub-auto").checked,
kinds:[...document.querySelectorAll(".sub-kind:checked")].map(el => el.value), min_electric:Number(document.getElementById("sub-min-e").value), max_electric:Number(document.getElementById("sub-max-e").value), sort_by:document.getElementById("sub-sort").value, retry_times:Number(document.getElementById("sub-retry").value)};
if (!payload.location_id || !payload.time || !payload.kinds.length) { showToast("请选择停车点、时间和至少一种车型"); return; }
if (payload.min_electric < 0 || payload.max_electric > 100 || payload.min_electric > payload.max_electric) { showToast("电量区间应在0-100且下限不高于上限"); return; }
if (!payload.notify_enabled && !payload.auto_unlock) { showToast("请至少开启邮件提醒或自动开锁"); return; }
if (payload.auto_unlock && !await appConfirm("命中规则后将使用当前账号真实开锁车辆。请核对停车点、时间与筛选条件。", {title:"确认自动开锁规则",okText:subscribeEditId ? "确认保存" : "确认添加"})) return;
try {
const response = await apiFetch(subscribeEditId ? `/api/subscribe/rules/${subscribeEditId}` : "/api/subscribe/rules", {method:subscribeEditId ? "PUT" : "POST", headers:{Authorization:`Bearer ${authToken}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});
const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message || "保存失败");
resetSubscribeEditor(); await loadSubscribeRules(); showToast("订阅规则已保存");
} catch (error) { showToast(error.message || "保存失败,请重试"); }
});
}
async function toggleSubscribeRule(id, enabled) {
return AppAPI.run(`subscription-${id}`, null, async () => {
try { const response = await apiFetch(`/api/subscribe/rules/${id}`, {method:"PUT",headers:{Authorization:`Bearer ${authToken}`,"Content-Type":"application/json"},body:JSON.stringify({enabled:!!enabled})}); const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message); await loadSubscribeRules(); }
catch (error) { showToast(error.message || "操作失败"); }
});
}
async function deleteSubscribeRule(id) {
if (!await appConfirm("确定删除这条订阅规则吗?", {title:"删除订阅",okText:"删除"})) return;
return AppAPI.run(`subscription-${id}`, null, async () => {
try { const response = await apiFetch(`/api/subscribe/rules/${id}`, {method:"DELETE",headers:{Authorization:`Bearer ${authToken}`}}); const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message); if (subscribeEditId === id) resetSubscribeEditor(); await loadSubscribeRules(); }
catch (error) { showToast(error.message || "删除失败"); }
});
}
+457
View File
@@ -0,0 +1,457 @@
// ========== 通用确认弹窗(替换 window.confirm) ==========
// 为什么不用 confirm:原生壳是 Android WebView,WebView 默认不弹 JS 原生对话框
// (Chromium 需要宿主实现 onJsConfirm,未实现时 confirm 直接返回 false,用户点不到"确认")。
// 这里用页面内弹窗,行为一致但任何环境都能用。
let _appConfirmResolve = null;
function appConfirm(message, opts) {
const o = opts || {};
const modal = document.getElementById("app-confirm-modal");
const titleEl = document.getElementById("app-confirm-title");
const textEl = document.getElementById("app-confirm-text");
const okBtn = document.getElementById("app-confirm-ok");
const cancelBtn = document.getElementById("app-confirm-cancel");
if (!modal || !textEl) { // 极老页面兜底
return Promise.resolve(window.confirm ? window.confirm(message) : true);
}
titleEl.textContent = o.title || "确认操作";
// 支持换行(保留 \n 的排版)
textEl.innerHTML = String(message || "")
.split("\n")
.map(line => escHtml(line))
.join("<br/>");
okBtn.textContent = o.okText || "确认";
cancelBtn.textContent = o.cancelText || "取消";
okBtn.classList.toggle("danger", !!o.danger);
return new Promise(resolve => {
_appConfirmResolve = resolve;
const finish = (val) => {
modal.classList.remove("show");
okBtn.onclick = null;
cancelBtn.onclick = null;
modal.onclick = null;
_appConfirmResolve = null;
resolve(val);
};
okBtn.onclick = (e) => { e.stopPropagation(); finish(true); };
cancelBtn.onclick = (e) => { e.stopPropagation(); finish(false); };
modal.onclick = (e) => { if (e.target === modal) finish(false); };
modal.classList.add("show");
});
}
function appConfirmClose() {
if (_appConfirmResolve) {
const r = _appConfirmResolve;
_appConfirmResolve = null;
document.getElementById("app-confirm-modal").classList.remove("show");
r(false);
}
}
function mapSnapshotNow() {
return renderedMapSnapshot
? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000
: Date.now() / 1000;
}
function updateMapFreshnessBadge() {
const el = document.getElementById("update-time");
if (!el) return;
const stamp = Number(renderedMapSnapshot?.fetched_at);
if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) {
el.textContent = new Date(stamp * 1000).toLocaleTimeString('zh-CN', {
timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit'
});
const expired = mapSnapshotNow() >= Number(renderedMapSnapshot.expires_at);
el.classList.toggle("stale", expired || mapRefreshFailed);
} else if (mapRefreshFailed) {
el.textContent = "更新失败";
el.classList.add("stale");
}
el.onclick = showFreshnessDetail;
el.style.cursor = "pointer";
}
function updateTime() {
if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; }
// Compatibility for a server without snapshot metadata; never show client time.
apiFetch(`/api/map/freshness?type=${encodeURIComponent(currentType)}`, { cache: "no-store" })
.then(r => r.json())
.then(result => {
if (result.rtn_code !== 0 || !result.data?.latest) return;
const el = document.getElementById("update-time");
if (!el) return;
el.textContent = String(result.data.latest).slice(11, 16);
el.classList.toggle("stale", result.data.status === "stale" || result.data.stale_seconds >= 60);
el.onclick = showFreshnessDetail;
el.style.cursor = "pointer";
})
.catch(() => {});
}
function showFreshnessDetail() {
if (renderedMapSnapshot && renderedMapSnapshot.fetched_at !== null) {
const seconds = Math.max(0, Math.floor(mapSnapshotNow() - renderedMapSnapshot.fetched_at));
const when = new Date(renderedMapSnapshot.fetched_at * 1000).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai' });
const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`;
showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ',更新暂时失败,正在自动重试' : ''}`);
return;
}
showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据");
}
function showToast(msg) {
const t = document.getElementById("toast");
t.textContent = msg;
t.classList.add("show");
setTimeout(() => t.classList.remove("show"), 2500);
}
// ========== 抓包工具下载 ==========
// 安装包是 Windows exe,任何手机/平板都跑不了;微信、QQ、支付宝等内置
// WebView 还会直接拦截 exe 下载。这两类情况都改为提示复制链接到电脑浏览器。
const CAPTURE_TOOL_PATH = "/download/capture-tool.exe";
// 鸿蒙 UA 有两种:老版 HarmonyOS + Android 兼容层,新版纯 OpenHarmony/ArkWeb;
// 微信鸿蒙版仍带 MicroMessenger,但部分版本 UA 精简后只剩 HarmonyOS。
function detectHarmony() {
const ua = navigator.userAgent || "";
return /OpenHarmony|HarmonyOS|ArkWeb|HMSCore/i.test(ua);
}
function detectMobile() {
const ua = navigator.userAgent || "";
const touchPoints = navigator.maxTouchPoints || 0;
// iPadOS 13+ 默认「请求桌面网站」,UA 伪装成 macOS;
// 靠触点数区分真正的 Mac(0)与 iPad(>1)
if (/Macintosh/.test(ua) && touchPoints > 1) return "iPad";
// 鸿蒙平板也常带 Tablet,先于手机判断
if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) {
return /Tablet/i.test(ua) ? "鸿蒙平板" : "鸿蒙手机";
}
if (/iPhone|iPod/.test(ua)) return "iPhone";
if (/iPad/.test(ua)) return "iPad";
if (/Android/.test(ua)) return /Tablet/i.test(ua) ? "安卓平板" : "安卓手机";
// 兜底:UA 明确标了 Mobile 但没给出具体平台
if (/Mobile/i.test(ua)) return "手机";
return null;
}
// 返回需要拦截的"环境名",null 表示可以直接下载
function detectInAppBrowser() {
const ua = navigator.userAgent || "";
// 原生壳优先判断:它是最外层容器,UA 里可能同时带 Android
if (/xbniu-native/i.test(ua)) return "APP";
if (/MicroMessenger/i.test(ua)) return detectHarmony() ? "鸿蒙微信" : "微信";
if (/\bQQ\/|QQBrowser/i.test(ua)) return "QQ";
if (/AlipayClient/i.test(ua)) return "支付宝";
if (/DingTalk/i.test(ua)) return "钉钉";
if (/Weibo/i.test(ua)) return "微博";
if (/aweme|ByteDance/i.test(ua)) return "抖音";
return null;
}
function captureToolUrl() {
return new URL(CAPTURE_TOOL_PATH, window.location.href).href;
}
// 返回 true 时放行 <a download> 的原生下载
function onDownloadCaptureTool(event) {
const app = detectInAppBrowser();
const mobile = app ? null : detectMobile(); // 内嵌环境优先,文案更具体
if (!app && !mobile) return true;
if (event) event.preventDefault();
showDownloadTipModal(app, mobile);
return false;
}
function showDownloadTipModal(appName, mobileName) {
const title = document.getElementById("download-tip-title");
const desc = document.getElementById("download-tip-desc");
const hint = document.getElementById("download-tip-hint");
title.textContent = "请在电脑上下载安装";
if (appName) {
desc.textContent = `${appName}内无法直接下载安装包。请复制下面的链接,在电脑浏览器中打开下载。`;
hint.textContent = "安装包为 Windows 程序,手机端下载后无法运行。";
} else {
// 普通移动端浏览器:能下载但装了也用不了,引导去电脑
desc.textContent = `当前是${mobileName || "移动设备"},安装包为 Windows 程序,在此设备上无法运行。请复制下面的链接,在电脑浏览器中打开下载。`;
hint.textContent = "";
}
hint.style.display = hint.textContent ? "block" : "none";
document.getElementById("download-tip-link").value = captureToolUrl();
document.getElementById("download-tip-modal").classList.add("show");
}
function closeDownloadTipModal() {
document.getElementById("download-tip-modal").classList.remove("show");
}
// ========== 数据导出(CSV 直链,1 小时有效) ==========
// 流程:POST /api/export/create(登录态)→ 拿到免登录直链。
// UA 复用 detectInAppBrowser:微信/QQ/支付宝/钉钉/微博/抖音/原生壳内无法直接下载,
// 弹「复制链接到外部浏览器」提示;普通浏览器直接触发下载。
function closeExportTipModal() {
document.getElementById("export-tip-modal").classList.remove("show");
}
async function copyExportLink() {
const url = document.getElementById("export-tip-link").value;
const input = document.getElementById("export-tip-link");
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(url);
showToast("链接已复制,请在浏览器中打开");
return;
}
throw new Error("clipboard unavailable");
} catch (e) {
try {
input.removeAttribute("readonly");
input.select();
document.execCommand("copy");
input.setAttribute("readonly", "");
showToast("链接已复制,请在浏览器中打开");
} catch (e2) {
showToast("复制失败,请长按链接手动复制");
}
}
}
async function exportHistoryCsv() {
if (!authToken) { showToast("请先登录"); return; }
showToast("正在生成导出链接...");
try {
const resp = await apiFetch("/api/export/create", {
method: "POST",
headers: { "Content-Type": "application/json",
"Authorization": `Bearer ${authToken}` },
body: JSON.stringify({ type: "history_csv" })
});
const data = await resp.json();
if (data.rtn_code !== 0) {
showToast(data.message || "生成导出链接失败");
return;
}
const url = new URL(data.data.url, window.location.href).href;
const app = detectInAppBrowser();
if (app) {
// 微信/原生壳等内嵌环境:给直链,复制到外部浏览器下载(直链免登录,1小时有效)
document.getElementById("export-tip-desc").textContent =
`${app}内无法直接下载文件。请复制下面的链接到系统浏览器打开(免登录,${data.data.ttl_hours} 小时内有效)。`;
document.getElementById("export-tip-link").value = url;
document.getElementById("export-tip-modal").classList.add("show");
return;
}
// 普通浏览器:直接下载,同时保留直链以便换浏览器使用
const a = document.createElement("a");
a.href = url;
a.download = "";
document.body.appendChild(a);
a.click();
a.remove();
showToast(`已开始下载(直链 ${data.data.ttl_hours} 小时内有效)`);
} catch (err) {
showToast("导出失败,请重试");
}
}
async function copyDownloadLink() {
const url = captureToolUrl();
const input = document.getElementById("download-tip-link");
// 微信等 WebView 常禁用 navigator.clipboard(非安全上下文或权限拒绝),
// 回退到选中 + execCommand 的老办法
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(url);
showToast("链接已复制");
return;
}
throw new Error("clipboard unavailable");
} catch (e) {
try {
input.removeAttribute("readonly");
input.select();
input.setSelectionRange(0, url.length);
const ok = document.execCommand("copy");
input.setAttribute("readonly", "readonly");
showToast(ok ? "链接已复制" : "复制失败,请长按链接手动复制");
} catch (e2) {
showToast("复制失败,请长按链接手动复制");
}
}
}
// 底层异常转用户提示:网关/错误页返回 HTML 时 resp.json() 会抛
// "Unexpected token '<' ... is not valid JSON",直接展示既难懂又含 token 字样易引起误解
function friendlyError(e) {
const msg = (e && e.message) || "";
if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) {
return "服务响应异常,请稍后重试";
}
return msg || "网络错误,请重试";
}
// ========== Token失效弹窗 ==========
// 仅在真正检测到微信凭据失效时调用;带冷却时间,避免轮询/刷新反复打扰
let _credInvalidLastShownAt = 0;
const CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1000; // 10 分钟内不重复弹出
function notifyCredentialInvalid(message) {
const modal = document.getElementById("token-expired-modal");
if (!modal || modal.classList.contains("show")) return;
if (Date.now() - _credInvalidLastShownAt < CRED_INVALID_MODAL_COOLDOWN) return;
_credInvalidLastShownAt = Date.now();
showTokenExpiredModal(null, message);
}
function showTokenExpiredModal(customTitle, customDesc) {
document.getElementById("token-expired-title").textContent = customTitle || "token已失效,请重新登录";
document.getElementById("token-expired-desc").textContent = customDesc || "您的微信凭据已过期,请重新抓包获取最新的 Token ID(及 AccessToken)";
document.getElementById("token-expired-modal").classList.add("show");
// 预填当前用户已有的token信息
loadExpiredTokenFields();
}
function closeTokenExpiredModal() {
document.getElementById("token-expired-modal").classList.remove("show");
document.getElementById("expired-tip").textContent = "";
}
async function loadExpiredTokenFields() {
if (!authToken) return;
try {
const resp = await apiFetch("/api/auth/profile", {
headers: { "Authorization": `Bearer ${authToken}` }
});
const data = await resp.json();
if (data.rtn_code === 0 && data.data) {
document.getElementById("expired-token-id").value = data.data.token_id || "";
document.getElementById("expired-signature").value = data.data.token || "";
}
} catch (e) { /* ignore */ }
}
async function saveExpiredToken() {
if (!authToken) {
document.getElementById("expired-tip").textContent = "请先登录";
return;
}
const token_id = document.getElementById("expired-token-id").value.trim();
const access_token = document.getElementById("expired-signature").value.trim();
const tip = document.getElementById("expired-tip");
if (!token_id) {
tip.textContent = "Token ID 必填;AccessToken 选填";
return;
}
tip.textContent = "验证中...";
try {
const verifyResp = await apiFetch("/api/auth/verify_token", {
method: "POST",
headers: { "Content-Type": "application/json",
"Authorization": `Bearer ${authToken}` },
body: JSON.stringify({ access_token, token_id })
});
const verifyData = await verifyResp.json();
if (!verifyData.valid) {
tip.textContent = verifyData.message || "凭据验证失败,请检查 Token ID 是否正确";
return;
}
} catch (err) {
tip.textContent = "验证失败";
return;
}
try {
const resp = await apiFetch("/api/auth/save_token", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authToken}`
},
body: JSON.stringify({ access_token, token_id })
});
const data = await resp.json();
if (data.rtn_code === 0) {
tip.textContent = "";
closeTokenExpiredModal();
showToast("凭证已更新 ✓");
} else {
tip.textContent = data.message || "保存失败";
}
} catch (err) {
tip.textContent = "保存失败";
}
}
// ================= 版本号 & 更新说明 =================
const VERSION_TAG = "v1.7.0-preview";
const VERSION_LOGS = [
{ v: "v1.7.0 预览", items: ["新增附近列表、车型与电量筛选、校园地点搜索和常用地点", "完善定位失败引导、订阅编辑与执行结果、历史订单筛选和分页", "统一车辆状态,支持5位和8位车牌,增加浅色、深色和跟随系统"] },
{ v: "v1.6.0", items: [
"新增用车设置:可独立开启或关闭邮件提醒,并多选到期前 10、5、3、2、1 分钟及到期时提醒",
"支持实时调整用车到期时间,当前订单也会立即按新时长更新;默认 19 分钟,月卡前 20 分钟免费并预留 1 分钟容错",
"新增自动还车开关;关闭后到期邮件只提醒手动还车,不再显示已自动还车或自动还车失败",
"共享用车按实际骑行人的到期与自动还车设置执行,车主和骑行人分别按各自设置接收美化后的 HTML 邮件及一键还车入口",
"修复共享车主重复显示订单横幅,并修复普通/共享车辆已锁车但接口响应异常时误报还车失败的问题"
] },
{ v: "v1.5.0", items: [
"新增共享电动车自定义昵称"
] },
{ v: "v1.4.0", items: [
"支持多设备同时登录:同一账号可在多台设备/多个浏览器同时在线,不再相互顶下线",
"个人中心新增“登录设备管理”:可查看当前账号各登录设备(记录系统/浏览器与最近活跃),随时下线其它设备或一键下线其它所有设备",
"统一个人中心/凭证/设备管理的深浅色模式适配"
] },
{ v: "v1.3.0", items: [
"新增「共享电动车」功能:向车主申请共享其电动车;接受后可设置每天可用次数、是否需要车主持有优惠卡、优惠卡剩余次数下限(低于则不能用)",
"开锁时可选择“用自己的账号”或“用共享者的账号”(附实时可用次数;今日次数用完的共享者默认隐藏)",
"用车横幅区分“共享中/使用XX的车中”,车主与被共享者都能还车",
"个人中心新增“共享电动车”入口,双Tab管理(可使用的/我共享的),双方都可解绑"
] },
{ v: "v1.2.0", items: [
"修复远程扫码被拦截:开锁上报车辆附近随机位置",
"请求头对齐当前版本微信环境"
] }
];
// 右下角版本徽标始终跟随 VERSION_TAG,避免与更新说明不一致
(function () {
var b = document.getElementById("version-badge");
if (b) b.textContent = VERSION_TAG;
})();
let versionModalInited = false;
let versionAutoTries = 0;
function openVersionModal() {
if (!versionModalInited) {
const el = document.getElementById("version-content");
el.innerHTML = VERSION_LOGS.map(l =>
`<h4>${l.v}</h4><ul>${l.items.map(i => `<li>${i}</li>`).join("")}</ul>`
).join("");
versionModalInited = true;
}
// 记录已查看当前版本,避免每次打开都弹
try { localStorage.setItem("version_seen", VERSION_TAG); } catch (e) {}
document.getElementById("version-modal").classList.add("show");
}
function closeVersionModal() {
document.getElementById("version-modal").classList.remove("show");
}
// 新版本/首次打开自动弹当前版本更新说明(每版本每浏览器只自动弹一次)
function maybeAutoShowVersion() {
// Update notes are available from Settings; first visits stay focused on finding a bike.
}
async function previewLogin() {
const button = document.querySelector(".preview-login") || document.getElementById("auth-btn");
await doLogin("demo@preview.local", "preview123", document.getElementById("gate-tip"), button);
}
async function createPreviewSession() {
return AppAPI.run("preview-session", null, async () => {
try {
let result = null;
const saved = localStorage.getItem("xbniu_preview_live_token");
if (saved) {
const status = await (await apiFetch("/api/auth/status", {headers:{Authorization:`Bearer ${saved}`}})).json();
if (status.data?.logged_in) result = {rtn_code:0,data:{token:saved,email:status.data.email}};
}
if (!result) result = await (await apiFetch("/api/preview/session", {method:"POST"})).json();
if (result.rtn_code !== 0) throw new Error(result.message || "创建失败");
if (currentUser?.email !== result.data.email) resetMapForAccount();
authToken = result.data.token; currentUser = {email:result.data.email}; localStorage.setItem("auth_token",authToken);
localStorage.setItem("xbniu_preview_live_token", authToken);
updateAuthButton(); hideLoginGate(); closeAllModals(); clearRentalState(); hideOrderBanner();
currentOrder = null;
if (map) loadMapData(currentType, false);
showToast("独立测试账号已创建,请填写微信凭证后测试真实接口");
openSettingsPage(); openAuthModal();
} catch (error) { showToast(error.message || "创建失败,请重试"); }
});
}
+60 -4074
View File
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
/* Modal visibility, keyboard containment and focus restoration. */
(function () {
'use strict';
const selector = '.auth-modal,.bell-modal,.return-modal,.qr-modal,.token-expired-modal,.return-confirm-modal,.unlock-confirm-modal,.lost-modal,#bike-card';
const focusable = 'button:not([disabled]),a[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex="0"]';
const previous = new WeakMap();
function containBackground() {
const open = [...document.querySelectorAll(selector)].filter(el => el.classList.contains('show'));
const modal = open.at(-1), settings = document.getElementById('settings-page');
const active = modal || (settings && !settings.hidden ? settings : null);
for (const child of document.body.children) {
if (['SCRIPT','STYLE','LINK'].includes(child.tagName)) continue;
if (active) child.inert = !(child === active || child.contains(active) || (modal?.id === 'bike-card' && child.matches('.card-overlay.show')));
else if (!child.matches(selector)) child.inert = false;
}
}
function sync(el) {
const open = el.classList.contains('show');
const activeElement = document.activeElement, hadFocus = el.contains(activeElement);
el.inert = !open;
el.setAttribute('aria-hidden', String(!open));
if (!el.hasAttribute('role')) el.setAttribute('role', 'dialog');
el.setAttribute('aria-modal', 'true');
if (!el.hasAttribute('aria-label') && !el.hasAttribute('aria-labelledby')) {
const title = el.querySelector('.auth-header,.unlock-confirm-title,.return-confirm-title,.bike-card-title,.qr-header');
el.setAttribute('aria-label', title?.textContent.trim().slice(0, 60) || '操作窗口');
}
if (open) {
previous.set(el, activeElement);
containBackground();
queueMicrotask(() => {
if (el.classList.contains('show')) [...el.querySelectorAll(focusable)].find(node => node.getClientRects().length)?.focus({ preventScroll: true });
});
} else if (hadFocus) {
containBackground();
const target = previous.get(el);
if (target?.isConnected) target.focus({ preventScroll: true });
else document.getElementById('auth-btn')?.focus({ preventScroll: true });
}
containBackground();
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll(selector).forEach(el => {
sync(el);
new MutationObserver(records => { if (records.some(r => r.attributeName === 'class')) sync(el); }).observe(el, { attributes: true, attributeFilter: ['class'] });
});
const settings = document.getElementById('settings-page');
if (settings) new MutationObserver(containBackground).observe(settings, { attributes:true, attributeFilter:['hidden'] });
containBackground();
document.addEventListener('keydown', event => {
const dialogs = [...document.querySelectorAll(selector)].filter(el => el.classList.contains('show'));
const el = dialogs.at(-1);
if (!el) return;
if (event.key === 'Escape') {
const close = el.querySelector('.auth-close,.bike-card-close,.qr-close,#app-confirm-cancel,.unlock-confirm-btn.cancel,.return-confirm-btn.cancel,.return-confirm-cancel,[data-dialog-close]');
if (close) { event.preventDefault(); close.click(); }
return;
}
if (event.key !== 'Tab') return;
const items = [...el.querySelectorAll(focusable)].filter(n => n.getClientRects().length);
if (!items.length) { event.preventDefault(); return; }
const first = items[0], last = items.at(-1);
if (event.shiftKey && (document.activeElement === first || !el.contains(document.activeElement))) { event.preventDefault(); last.focus({ preventScroll: true }); }
else if (!event.shiftKey && (document.activeElement === last || !el.contains(document.activeElement))) { event.preventDefault(); first.focus({ preventScroll: true }); }
});
});
})();
+19
View File
@@ -0,0 +1,19 @@
(function () {
'use strict';
const key = 'xbniu_theme', media = window.matchMedia('(prefers-color-scheme: dark)');
let preference = 'system';
try { preference = localStorage.getItem(key) || 'system'; } catch (_) {}
function apply(value, save) {
preference = ['light', 'dark', 'system'].includes(value) ? value : 'system';
document.documentElement.dataset.theme = preference === 'system' ? (media.matches ? 'dark' : 'light') : preference;
document.documentElement.style.colorScheme = document.documentElement.dataset.theme;
if (save) { try { localStorage.setItem(key, preference); } catch (_) {} }
document.querySelectorAll('[data-theme-choice]').forEach(el => el.setAttribute('aria-pressed', String(el.dataset.themeChoice === preference)));
window.dispatchEvent(new Event('xbniu-theme-change'));
}
window.UIPreferences = { set: value => apply(value, true), isDark: () => document.documentElement.dataset.theme === 'dark', get: () => preference };
apply(preference, false);
media.addEventListener('change', () => { if (preference === 'system') apply(preference, false); });
window.addEventListener('storage', e => { if (e.key === key) apply(e.newValue || 'system', false); });
document.addEventListener('DOMContentLoaded', () => apply(preference, false));
})();