- 卡片缩放:每次开卡片排一个不跟踪的 setTimeout(zoom+1) → 连点几辆车把地图 永久放大到最大级别。改为单实例 _cardZoomTimer + 上限 19 级 - 扫码补的临时 marker:刷新时不回收,车早被骑走了地图上还留一个能点开的旧点。 新增 scannedMarkers 集合,每次 renderMap(含刷新分支)先移除 - 共享横幅:每 20 秒整块重建 innerHTML,手指按在「还车」上时按钮被替换导致 点了没反应,入场动画也每 20 秒重播。内容不变就不写 DOM - 「一键开锁」坐标:开二维码弹窗时 closeCard() 会清空 selectedBike, 之后取坐标退化成硬编码 (36.67, 116.98)。改为按车牌从 markersData 取 - 临时锁车:等定位(最长 5 秒)期间订单轮询可能置空 currentOrder, 之后读 currentOrder.order_id 抛 TypeError 被吞成「临时锁车失败」。改为先快照 - 丢失模式:三处 `btn.querySelector` 写在 `if (btn)` 之前(判空是死代码), 按钮不在 DOM 时抛错导致复位/解绑全跳过。改为 `btn && btn.querySelector(...)` 浏览器实测(390px):map.__navBound=true,导航中模拟拖动 → follow=false、 「返回导航」浮条正常出现;JS 异常 0 测试:161 pytest + 32 node 全绿
5041 lines
216 KiB
JavaScript
5041 lines
216 KiB
JavaScript
// ========== 全局变量 ==========
|
||
let map = null;
|
||
let currentType = "3";
|
||
let currentUser = null; // 当前登录用户
|
||
let authKickToastShown = false; // 防重复提示“登录已失效”
|
||
let authMode = "login"; // login 或 register
|
||
let authToken = localStorage.getItem("auth_token") || null;
|
||
let currentMarkers = [];
|
||
let currentPolygons = [];
|
||
let selectedBike = null;
|
||
let markersData = {};
|
||
let currentMarkersById = {};
|
||
let scannedMarkers = {}; // 扫码查到但不在列表里的临时补点(每次渲染回收) // 用于刷新时快速定位
|
||
let myLocationMarker = null;
|
||
let autoLocationMarker = null; // 自动持续定位的标记
|
||
let autoLocationWatchId = null; // watchPosition 的 ID
|
||
let hasLocationPermission = false; // 是否已获取位置权限
|
||
let initialLocationCentered = false; // 是否已按用户位置完成首次居中(每页仅一次)
|
||
let nearestBikeId = null;
|
||
let isFirstLoad = true; // 标记首次加载
|
||
let highlightedBikeId = null; // 高亮的车辆ID
|
||
// A failed optional map asset must not abort order/return initialization.
|
||
let bikeClusteringEnabled = typeof BikeClusters !== "undefined"
|
||
? BikeClusters.readClusteringPreference(localStorage) : true;
|
||
// 百度地图 API Key(用于坐标转换)
|
||
const BAIDU_AK = "GzzqszczKmI7RNTclpLtOXZDTT4mq8a6";
|
||
|
||
// ========== 图标缓存(性能优化)==========
|
||
// 缓存: key = "电量|颜色|是否高亮" → BMapGL.Icon
|
||
const iconCache = new Map();
|
||
const ICON_CACHE_MAX = 500; // 最多缓存500个不同图标
|
||
|
||
// ========== 预创建完整图标(首次加载优化)==========
|
||
// 预创建各电量和颜色的完整图标(避免首次加载时大量 Canvas 绘制)
|
||
const BASE_ICON_COLORS = {
|
||
available: "#34C759", // 绿色-可用
|
||
inuse: "#FF2D55", // 红色-使用中
|
||
locked: "#FF9F0A", // 橙色-欠压
|
||
reserved: "#5856D6", // 紫色-损坏
|
||
lowbattery: "#8E8E93" // 灰色-低电量
|
||
};
|
||
|
||
// 预创建非高亮状态的完整图标(电量档位 0, 20, 40, 60, 80, 100)
|
||
const prebuiltIcons = new Map(); // key: "电量档位|颜色", value: BMapGL.Icon
|
||
|
||
function createFullIcon(size, color, electric, isHighlighted, bikeCode) {
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = size;
|
||
canvas.height = size;
|
||
const ctx = canvas.getContext("2d");
|
||
const r = size / 2 - (isHighlighted ? 12 : 8);
|
||
const lineWidth = isHighlighted ? 16 : 12;
|
||
const centerX = size / 2;
|
||
const centerY = size / 2;
|
||
|
||
// 高亮时加阴影
|
||
if (isHighlighted) {
|
||
ctx.shadowColor = color;
|
||
ctx.shadowBlur = 48;
|
||
}
|
||
|
||
// 白色背景
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||
ctx.fillStyle = "white";
|
||
ctx.fill();
|
||
|
||
// 边框
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||
ctx.strokeStyle = isHighlighted ? color : "rgba(200,200,200,0.5)";
|
||
ctx.lineWidth = isHighlighted ? 16 : lineWidth;
|
||
ctx.stroke();
|
||
ctx.shadowBlur = 0;
|
||
|
||
// 使用中:实心圆环
|
||
if (isHighlighted) {
|
||
// 高亮时只显示车牌号,没有进度环
|
||
} else {
|
||
// 非高亮:绘制电量进度环
|
||
const startAngle = -Math.PI / 2;
|
||
const endAngle = startAngle + (Math.PI * 2 * electric / 100);
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r, startAngle, endAngle);
|
||
ctx.strokeStyle = color;
|
||
ctx.lineWidth = lineWidth;
|
||
ctx.lineCap = "round";
|
||
ctx.stroke();
|
||
}
|
||
|
||
// 绘制数字
|
||
ctx.fillStyle = "#333";
|
||
ctx.font = isHighlighted ? "bold 60px Arial" : "bold 44px Arial";
|
||
ctx.textAlign = "center";
|
||
ctx.textBaseline = "middle";
|
||
ctx.fillText(isHighlighted ? (bikeCode + "") : (Math.round(electric) + ""), centerX, centerY);
|
||
|
||
return canvas.toDataURL("image/png");
|
||
}
|
||
|
||
// 预初始化完整图标(在地图加载前调用)
|
||
function preloadBaseIcons() {
|
||
const displaySize = 36;
|
||
const imageSize = displaySize * 4; // 高清4倍
|
||
const electricLevels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; // 21个电量档位(5%分度)
|
||
|
||
Object.values(BASE_ICON_COLORS).forEach(color => {
|
||
// 非高亮状态:每个电量档位创建一个
|
||
electricLevels.forEach(electric => {
|
||
const key = `${electric}|${color}`;
|
||
if (!prebuiltIcons.has(key)) {
|
||
// 存储 data URL 而不是 Icon 对象
|
||
const dataUrl = createFullIcon(imageSize, color, electric, false, null);
|
||
prebuiltIcons.set(key, dataUrl);
|
||
}
|
||
});
|
||
});
|
||
console.log("[预创建] 已预创建 " + prebuiltIcons.size + " 个图标");
|
||
}
|
||
|
||
// ========== 用车计时 ==========
|
||
let activeRental = null; // 当前活跃租车信息
|
||
let rentalCountdownTimer = null; // 倒计时定时器
|
||
const RENTAL_KEY = "xbniu_rental_key"; // localStorage key
|
||
|
||
// 手动坐标偏移(仅作为 coordtransform 未加载时的降级常量;正常走 gcj02tobd09 自动转换)
|
||
const COORD_OFFSET = {
|
||
lat: 0.00603, // 约610米(纬度)
|
||
lng: 0.00650, // 约600米-20米(经度,往西20米)
|
||
};
|
||
|
||
// 初始位置额外偏移(再往上30米)
|
||
const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北)
|
||
const INIT_OFFSET_EAST = 0.003; // 约300米(向东)
|
||
|
||
// 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform,无在线转换上限)。
|
||
// coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat]
|
||
function offsetCoord(lat, lng) {
|
||
lat = parseFloat(lat);
|
||
lng = parseFloat(lng);
|
||
if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) {
|
||
try {
|
||
const bd = coordtransform.gcj02tobd09(lng, lat); // [lng, lat]
|
||
return { lat: bd[1], lng: bd[0] };
|
||
} catch (e) {
|
||
console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e);
|
||
}
|
||
}
|
||
// 降级:coordtransform 未加载/出错时,沿用旧的手动常量偏移,避免点位整体偏差
|
||
return {
|
||
lat: lat + COORD_OFFSET.lat,
|
||
lng: lng + COORD_OFFSET.lng,
|
||
};
|
||
}
|
||
|
||
// 状态判断函数 - 基于 state + status 组合判断
|
||
// state=1 + status=0: 空闲可用
|
||
// state=1 + status=1: 使用中(被占用)
|
||
// state=10: 低电量车辆
|
||
// state=4: 欠压车辆
|
||
// state=2: 损坏车辆
|
||
function getBikeState(bike) {
|
||
const state = bike.state;
|
||
const status = bike.status;
|
||
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||
// 使用中:被占用
|
||
if (state === 1 && status === 1) return 'inuse';
|
||
// 低电量:state=10 或电量<20(与后端 _classify_bike_state 同序)
|
||
if (state === 10 || electric < 20) return 'lowbattery';
|
||
// 空闲可用
|
||
if (state === 1) return 'available';
|
||
// 欠压车辆
|
||
if (state === 4) return 'locked';
|
||
// 损坏车辆
|
||
if (state === 2) return 'reserved';
|
||
return 'unknown';
|
||
}
|
||
|
||
// ========== 电池绘制 ==========
|
||
function updateRingProgress(percent, color) {
|
||
const fill = document.getElementById("battery-fill");
|
||
if (fill) {
|
||
// 电量填充区域最大宽度 39px(外框内宽 = 43-4 left offset-2border=39)
|
||
const maxW = 39;
|
||
const w = Math.round((percent / 100) * maxW);
|
||
fill.setAttribute("width", w);
|
||
fill.setAttribute("fill", color);
|
||
}
|
||
}
|
||
|
||
// ========== Canvas 电量圆环图标 ==========
|
||
function makeIconDataURI(color, percent, isInUse, size = 36) {
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = size;
|
||
canvas.height = size;
|
||
const ctx = canvas.getContext("2d");
|
||
const r = size / 2 - 2;
|
||
const lineWidth = 3;
|
||
const centerX = size / 2;
|
||
const centerY = size / 2;
|
||
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r - lineWidth, 0, Math.PI * 2);
|
||
ctx.fillStyle = "rgba(255,255,255,0.9)";
|
||
ctx.fill();
|
||
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||
ctx.strokeStyle = "rgba(200,200,200,0.5)";
|
||
ctx.lineWidth = lineWidth;
|
||
ctx.stroke();
|
||
|
||
if (isInUse) {
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||
ctx.strokeStyle = color;
|
||
ctx.lineWidth = lineWidth;
|
||
ctx.stroke();
|
||
} else {
|
||
const startAngle = -Math.PI / 2;
|
||
const endAngle = startAngle + (Math.PI * 2 * percent / 100);
|
||
ctx.beginPath();
|
||
ctx.arc(centerX, centerY, r, startAngle, endAngle);
|
||
ctx.strokeStyle = color;
|
||
ctx.lineWidth = lineWidth;
|
||
ctx.lineCap = "round";
|
||
ctx.stroke();
|
||
}
|
||
|
||
ctx.fillStyle = "#333";
|
||
ctx.font = `bold ${size < 36 ? 10 : 11}px Arial`;
|
||
ctx.textAlign = "center";
|
||
ctx.textBaseline = "middle";
|
||
ctx.fillText(Math.round(percent) + "", centerX, centerY);
|
||
|
||
return canvas.toDataURL("image/png");
|
||
}
|
||
|
||
// ========== 车辆类型(编号规则,按实车号段)==========
|
||
// - 编号超过 5 位(如 30000193 / 30000033,共 8 位):新引进红色外观车 → 红车
|
||
// - 5 位编号取「前三位号段」:511 及以上=大车,510 及以下=小车
|
||
// (实测号段:503/504/505/510=小车,511/512/513=大车)
|
||
// 红车电量球统一用柔和砖红(不用"使用中"那种血红 #FF2D55,避免视觉惊扰)
|
||
const RED_BIKE_COLOR = "#B4615A"; // 柔和砖红
|
||
|
||
function getBikeKind(bike) {
|
||
const digits = String((bike && bike.code) || "").replace(/\D/g, "");
|
||
if (digits.length > 5) {
|
||
return { key: "red", label: "红车", color: RED_BIKE_COLOR };
|
||
}
|
||
const num = parseInt(digits, 10);
|
||
if (!isFinite(num)) {
|
||
return { key: "small", label: "小车", color: null };
|
||
}
|
||
// 5 位取前三位号段;不足 5 位直接用编号本身比较
|
||
const series = digits.length >= 5 ? Math.floor(num / Math.pow(10, digits.length - 3)) : num;
|
||
return series >= 511
|
||
? { key: "big", label: "大车", color: null }
|
||
: { key: "small", label: "小车", color: null };
|
||
}
|
||
|
||
function getBikeIcon(bike, isHighlighted = false) {
|
||
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||
const bikeState = getBikeState(bike);
|
||
// 车辆类型只影响弹起卡片上的标注,地图电量球保持原有「按状态配色」
|
||
|
||
let color = "#34C759"; // 默认绿色-可用
|
||
if (bikeState === 'inuse') {
|
||
color = "#FF2D55"; // 红色-使用中
|
||
} else if (bikeState === 'locked') {
|
||
color = "#FF9F0A"; // 橙色-欠压车辆
|
||
} else if (bikeState === 'reserved') {
|
||
color = "#5856D6"; // 紫色-损坏车辆
|
||
} else if (bikeState === 'lowbattery' || electric < 20) {
|
||
color = "#8E8E93"; // 灰色-低电量
|
||
}
|
||
|
||
// 生成缓存 key
|
||
const electricLevel = Math.floor(electric / 5) * 5;
|
||
const cacheKey = isHighlighted
|
||
? `${electricLevel}|${color}|1|${bike.code}`
|
||
: `${electricLevel}|${color}|0`;
|
||
|
||
// 检查缓存
|
||
if (iconCache.has(cacheKey)) {
|
||
return iconCache.get(cacheKey);
|
||
}
|
||
|
||
const renderSize = isHighlighted ? 192 : 144; // 内部渲染尺寸
|
||
const displaySize = isHighlighted ? 48 : 36; // 显示尺寸不变
|
||
|
||
// 非高亮模式:尝试使用预创建的图标
|
||
if (!isHighlighted && prebuiltIcons.size > 0) {
|
||
// 找到最接近的电量档位
|
||
const levels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
|
||
let closestLevel = levels[0];
|
||
let minDiff = Math.abs(electric - closestLevel);
|
||
for (const lvl of levels) {
|
||
const diff = Math.abs(electric - lvl);
|
||
if (diff < minDiff) {
|
||
minDiff = diff;
|
||
closestLevel = lvl;
|
||
}
|
||
}
|
||
const prebuiltKey = `${closestLevel}|${color}`;
|
||
if (prebuiltIcons.has(prebuiltKey)) {
|
||
// 找到预创建的 data URL,直接创建 Icon
|
||
const dataUrl = prebuiltIcons.get(prebuiltKey);
|
||
const icon = new BMapGL.Icon(
|
||
dataUrl,
|
||
new BMapGL.Size(displaySize, displaySize),
|
||
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||
);
|
||
icon.__xbniuAppearance = { url: dataUrl, size: displaySize };
|
||
iconCache.set(cacheKey, icon);
|
||
return icon;
|
||
}
|
||
}
|
||
|
||
// 如果没有预创建的图标,或者需要高亮状态:直接创建完整图标
|
||
// imageSize 用于渲染高清内容,displaySize 控制显示大小
|
||
const imageSize = renderSize * 4; // 高清4倍
|
||
const dataUrl = createFullIcon(imageSize, color, electric, isHighlighted, bike.code);
|
||
const icon = new BMapGL.Icon(
|
||
dataUrl,
|
||
new BMapGL.Size(displaySize, displaySize),
|
||
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||
);
|
||
icon.__xbniuAppearance = { url: dataUrl, size: displaySize };
|
||
|
||
// 缓存图标
|
||
if (iconCache.size >= ICON_CACHE_MAX) {
|
||
const keysToDelete = Array.from(iconCache.keys()).slice(0, Math.floor(ICON_CACHE_MAX * 0.2));
|
||
keysToDelete.forEach(k => iconCache.delete(k));
|
||
}
|
||
iconCache.set(cacheKey, icon);
|
||
|
||
return icon;
|
||
}
|
||
|
||
// ========== 高亮相关 ==========
|
||
// 稳健查找 marker:优先用索引,索引 miss(如批量渲染未完成/刷新过程中)时按 __animId 或标题扫描 currentMarkers 兜底
|
||
function findMarkerById(id) {
|
||
const key = String(id);
|
||
if (currentMarkersById && currentMarkersById[id]) return currentMarkersById[id];
|
||
if (Array.isArray(currentMarkers)) {
|
||
for (let i = currentMarkers.length - 1; i >= 0; i--) {
|
||
const m = currentMarkers[i];
|
||
if (m && m.__animId !== undefined && String(m.__animId) === key) return m;
|
||
}
|
||
for (let i = currentMarkers.length - 1; i >= 0; i--) {
|
||
const m = currentMarkers[i];
|
||
if (m && m.getTitle) {
|
||
const t = String(m.getTitle()).replace(/^#/, "");
|
||
if (t === key) return m;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// 让指定 marker 显示在最上层(放大高亮图标避免被其它普通 marker 遮住)
|
||
function bringMarkerToTop(marker) {
|
||
if (marker && marker.bringToTop) { marker.bringToTop(); return; }
|
||
if (marker && typeof map !== 'undefined' && map && typeof map.removeOverlay === 'function' && typeof map.addOverlay === 'function') {
|
||
try {
|
||
const markerId = marker.__animId;
|
||
map.removeOverlay(marker);
|
||
map.addOverlay(marker);
|
||
// removeOverlay/addOverlay 可能重建 marker 的 DOM,重绑一次原生 touch 兜底,避免点按失效
|
||
if (markerId !== undefined) bindMarkerDomTouch(marker);
|
||
} catch (e) { /* 忽略:个别情况下不允许重排 */ }
|
||
}
|
||
}
|
||
|
||
function setHighlight(id) {
|
||
// 清除之前的高亮
|
||
if (highlightedBikeId !== null) {
|
||
const prevMarker = findMarkerById(highlightedBikeId);
|
||
const prevBike = markersData[highlightedBikeId];
|
||
if (prevMarker && prevBike) {
|
||
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[setHighlight] 还原图标失败", e); }
|
||
}
|
||
}
|
||
|
||
// 设置新高亮
|
||
highlightedBikeId = id;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(id);
|
||
if (id === null || id === undefined) return;
|
||
const marker = findMarkerById(id);
|
||
const bike = markersData[id] || markersData[String(id)] || markersData[Number(id)];
|
||
if (marker && bike) {
|
||
try {
|
||
marker.setIcon(getBikeIcon(bike, true));
|
||
bringMarkerToTop(marker);
|
||
} catch (e) { console.warn("[setHighlight] 放大高亮失败", e); }
|
||
} else {
|
||
console.warn("[setHighlight] 未找到 marker 或 bike, id=", id);
|
||
}
|
||
}
|
||
|
||
function clearHighlight() {
|
||
if (highlightedBikeId !== null) {
|
||
const prevMarker = findMarkerById(highlightedBikeId);
|
||
const prevBike = markersData[highlightedBikeId];
|
||
if (prevMarker && prevBike) {
|
||
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[clearHighlight] 还原图标失败", e); }
|
||
}
|
||
}
|
||
highlightedBikeId = null;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(null);
|
||
}
|
||
|
||
// ========== Marker 点按绑定(统一入口)==========
|
||
// 背景:BMapGL 在拖动地图后会把紧接的一次对 marker 的 click 吞掉(当作拖拽延续),
|
||
// 导致“点了点但模态框弹不出”。因此这里不用单一 click,而是额外用
|
||
// mousedown/mouseup 与原生 touch 的“按下→抬起无位移”判定作为自控点击路径。
|
||
|
||
// 把原生 touch 兜底绑到 marker 的当前 DOM 元素上(幂等,可被重复调用,
|
||
// 用于 domElement 延迟就绪或 removeOverlay/addOverlay 重建 DOM 之后补绑)。
|
||
function bindMarkerDomTouch(marker) {
|
||
const tap = marker && marker.__xbniuTap;
|
||
if (!tap) return;
|
||
const el = marker.domElement;
|
||
if (!el) return;
|
||
if (el.__xbniuTapBound) return;
|
||
el.__xbniuTapBound = true;
|
||
try {
|
||
el.addEventListener('touchstart', (e) => {
|
||
const t = e.touches && e.touches[0];
|
||
if (t) tap._down(t.clientX, t.clientY);
|
||
}, { passive: true });
|
||
el.addEventListener('touchend', (e) => {
|
||
const t = e.changedTouches && e.changedTouches[0];
|
||
if (t) {
|
||
try { e.preventDefault(); } catch (err) {}
|
||
tap._up(t.clientX, t.clientY);
|
||
}
|
||
}, { passive: false });
|
||
} catch (e) { /* 忽略绑定失败 */ }
|
||
}
|
||
|
||
// 给单个 marker 绑定点按处理。marker 需已 __animId = id。
|
||
function bindMarkerTap(marker, id) {
|
||
const tap = {
|
||
lastFire: 0, // 防重入:同一 marker 短时间内只触发一次
|
||
downX: null, downY: null, downT: 0,
|
||
_fire() {
|
||
// 同一 marker 的 click / mouseup / touchend 都可能触发本路径,300ms 内只放行一次
|
||
const now = Date.now();
|
||
if (now - this.lastFire < 300) return;
|
||
this.lastFire = now;
|
||
clearHighlight();
|
||
showBikeDetail(id);
|
||
},
|
||
_down(x, y) { this.downX = x; this.downY = y; this.downT = Date.now(); },
|
||
_up(x, y) {
|
||
if (this.downX === null) return;
|
||
const dx = x - this.downX, dy = y - this.downY;
|
||
const moved = Math.sqrt(dx * dx + dy * dy);
|
||
const dt = Date.now() - this.downT;
|
||
this.downX = this.downY = null;
|
||
// 无位移(<10px)且按压短暂(<600ms) 判定为点按 → 即使 BMapGL 吞了 click 也能打开
|
||
if (moved < 10 && dt < 600) this._fire();
|
||
}
|
||
};
|
||
marker.__xbniuTap = tap;
|
||
|
||
// 1) BMapGL 对象级事件:click 为主路径,mousedown/mouseup 补偿“拖动后被吞的 click”
|
||
try {
|
||
marker.addEventListener('click', () => tap._fire());
|
||
marker.addEventListener('mousedown', (e) => tap._down(e.clientX, e.clientY));
|
||
marker.addEventListener('mouseup', (e) => tap._up(e.clientX, e.clientY));
|
||
} catch (e) { /* 个别事件类型不支持时忽略 */ }
|
||
|
||
// 2) 原生 touch 兜底(移动端最可靠)。domElement 可能延迟生成,故稍后补绑。
|
||
bindMarkerDomTouch(marker);
|
||
if (!marker.domElement) {
|
||
// domElement 尚未就绪:极轻量轮询补绑(最多约 1s),避免移动端兜底落空
|
||
let tries = 0;
|
||
const timer = setInterval(() => {
|
||
tries++;
|
||
if (marker.domElement) {
|
||
bindMarkerDomTouch(marker);
|
||
clearInterval(timer);
|
||
} else if (tries > 10) {
|
||
clearInterval(timer);
|
||
}
|
||
}, 100);
|
||
}
|
||
}
|
||
|
||
// ========== 初始化地图 ==========
|
||
let mapInitializationStarted = false;
|
||
function initMap() {
|
||
// 等待 BMapGL 对象加载完成
|
||
function waitForBMap(retries = 30) {
|
||
if (mapInitializationStarted) return;
|
||
if (typeof BMapGL !== 'undefined' && typeof BMapGL.Map === 'function') {
|
||
mapInitializationStarted = true;
|
||
initMapCore();
|
||
} else if (retries > 0) {
|
||
console.log(`等待百度地图GL API加载... (${retries})`);
|
||
setTimeout(() => waitForBMap(retries - 1), 500);
|
||
} else {
|
||
console.error("百度地图GL API加载失败");
|
||
showToast("地图API加载失败,请检查网络后刷新");
|
||
}
|
||
}
|
||
waitForBMap();
|
||
}
|
||
|
||
// ========== 登录认证 ==========
|
||
function handleAuthBtnClick() {
|
||
if (currentUser) {
|
||
// 已登录,显示个人中心
|
||
showProfileModal();
|
||
} else {
|
||
// 未登录,显示登录弹窗
|
||
showLoginModal();
|
||
}
|
||
}
|
||
|
||
function showLoginModal() {
|
||
closeAllModals();
|
||
document.getElementById("login-modal").classList.add("show");
|
||
document.getElementById("login-email").focus();
|
||
}
|
||
|
||
function closeLoginModal() {
|
||
document.getElementById("login-modal").classList.remove("show");
|
||
document.getElementById("login-tip").textContent = "";
|
||
}
|
||
|
||
function showRegisterModal() {
|
||
closeLoginModal();
|
||
closeRegisterModal();
|
||
document.getElementById("register-modal").classList.add("show");
|
||
document.getElementById("register-email").focus();
|
||
}
|
||
|
||
function closeRegisterModal() {
|
||
document.getElementById("register-modal").classList.remove("show");
|
||
document.getElementById("register-tip").textContent = "";
|
||
}
|
||
|
||
function openSettingsPage() {
|
||
closeAllModals();
|
||
document.getElementById("settings-clustering").checked = bikeClusteringEnabled;
|
||
document.getElementById("settings-save-status").textContent = "地图偏好自动保存在当前设备,即时生效。";
|
||
SettingsPages.open("settings-modal");
|
||
loadProfileData();
|
||
}
|
||
|
||
function closeSettingsPage() { SettingsPages.back(); }
|
||
|
||
function saveMapClusteringSetting(enabled) {
|
||
if (typeof BikeClusters === "undefined") {
|
||
showToast("地图组件未加载,请刷新页面后重试");
|
||
return;
|
||
}
|
||
bikeClusteringEnabled = !!enabled;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled);
|
||
const saved = BikeClusters.writeClusteringPreference(localStorage, bikeClusteringEnabled);
|
||
document.getElementById("settings-save-status").textContent = saved
|
||
? (bikeClusteringEnabled ? "已开启车辆聚类,设置已保存。" : "已关闭聚类,所有车辆单独显示。设置已保存。")
|
||
: "设置已生效,当前浏览器无法保存,刷新后会恢复默认。";
|
||
}
|
||
|
||
window.addEventListener("storage", event => {
|
||
if (typeof BikeClusters === "undefined") return;
|
||
if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return;
|
||
bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage);
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled);
|
||
document.getElementById("settings-clustering").checked = bikeClusteringEnabled;
|
||
});
|
||
|
||
function showProfileModal() { openSettingsPage(); }
|
||
|
||
function closeProfileModal() { SettingsPages.close(); }
|
||
|
||
function closeAllModals() {
|
||
if (typeof SettingsPages !== "undefined") SettingsPages.hide();
|
||
document.getElementById("login-modal").classList.remove("show");
|
||
document.getElementById("register-modal").classList.remove("show");
|
||
document.getElementById("settings-modal").classList.remove("show");
|
||
document.getElementById("rental-settings-modal").classList.remove("show");
|
||
document.getElementById("devices-modal").classList.remove("show");
|
||
document.getElementById("auth-modal").classList.remove("show");
|
||
document.getElementById("packages-modal").classList.remove("show");
|
||
const forgot = document.getElementById("forgot-modal");
|
||
if (forgot) forgot.classList.remove("show");
|
||
const orders = document.getElementById("orders-modal");
|
||
if (orders) orders.classList.remove("show");
|
||
const subscribe = document.getElementById("subscribe-modal");
|
||
if (subscribe) subscribe.classList.remove("show");
|
||
const traj = document.getElementById("order-traj-modal");
|
||
if (traj) traj.classList.remove("show");
|
||
const _armc = document.getElementById("add-round-modal");
|
||
if (_armc) _armc.classList.remove("show");
|
||
const _srm = document.getElementById("share-return-modal");
|
||
if (_srm) _srm.classList.remove("show");
|
||
appConfirmClose(); // 视为「取消」,避免 Promise 悬空
|
||
}
|
||
|
||
async function loadProfileData() {
|
||
if (!authToken) return;
|
||
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const email = data.data.email || "";
|
||
document.getElementById("profile-email").textContent = email;
|
||
const firstChar = email.charAt(0).toUpperCase();
|
||
document.getElementById("profile-avatar").textContent = firstChar;
|
||
|
||
maybeStrictGuide(data.data);
|
||
|
||
// 微信凭据(accessToken JWT)有效期,实时倒计时展示
|
||
_savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable
|
||
? { expireAt: data.data.access_token_expiry.expire_at,
|
||
source: data.data.access_token_expiry.source } : null;
|
||
updateTokenExpiryDisplays();
|
||
|
||
// 隐藏/显示消费统计和提示
|
||
const hasAuth = data.data.has_auth;
|
||
document.getElementById("profile-stats").style.display = hasAuth ? "flex" : "none";
|
||
document.getElementById("profile-auth-hint").style.display = hasAuth ? "none" : "flex";
|
||
document.getElementById("profile-name").textContent = "--";
|
||
document.getElementById("profile-out-money").textContent = "--";
|
||
document.getElementById("profile-save-money").textContent = "--";
|
||
}
|
||
} catch (err) {
|
||
console.error("加载用户信息失败:", err);
|
||
}
|
||
|
||
// 加载姓名和消费信息
|
||
loadUserInfo();
|
||
}
|
||
|
||
async function loadUserInfo() {
|
||
if (!authToken) return;
|
||
|
||
try {
|
||
const resp = await fetch("/api/auth/user_info", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const info = data.data;
|
||
|
||
// 显示姓名
|
||
if (info.true_name) {
|
||
document.getElementById("profile-name").textContent = info.true_name;
|
||
document.getElementById("profile-avatar").textContent = info.true_name.charAt(0);
|
||
}
|
||
|
||
// 显示消费统计
|
||
if (info.out_money !== null) {
|
||
document.getElementById("profile-out-money").textContent = (info.out_money || 0).toFixed(1);
|
||
}
|
||
if (info.save_money !== null) {
|
||
document.getElementById("profile-save-money").textContent = (info.save_money || 0).toFixed(1);
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error("加载用户详情失败:", err);
|
||
}
|
||
}
|
||
|
||
// ========== AccessToken 有效期解析 ==========
|
||
// accessToken 是上游登录响应中的 JWT(RS256),payload 带 iat/nbf/exp,
|
||
// 实测有效期 30 天。此处只解码展示,不做签名校验。
|
||
function parseJwtExpiry(token) {
|
||
token = (token || "").trim();
|
||
if (!token || token.indexOf(".") < 0) return null;
|
||
const parts = token.split(".");
|
||
if (parts.length !== 3 || parts[1].length < 8) return null;
|
||
try {
|
||
let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
||
while (b64.length % 4) b64 += "=";
|
||
const payload = JSON.parse(decodeURIComponent(escape(atob(b64))));
|
||
let exp = payload.exp ? parseInt(payload.exp) : null;
|
||
let iat = payload.iat ? parseInt(payload.iat) : null;
|
||
if (!exp && iat) exp = iat + 30 * 86400; // 与上游实测一致:30 天有效期
|
||
if (!exp) return null;
|
||
return { expireAt: exp, source: payload.exp ? "exp" : "iat+30d" };
|
||
} catch (e) { return null; }
|
||
}
|
||
function fmtLocalTime(ts) {
|
||
const d = new Date(ts * 1000);
|
||
const p = n => String(n).padStart(2, "0");
|
||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||
}
|
||
function describeTokenExpiry(expiry) {
|
||
const remain = expiry.expireAt - Math.floor(Date.now() / 1000);
|
||
const when = fmtLocalTime(expiry.expireAt);
|
||
const left = remain <= 0 ? "已过期" : `约剩 ${fmtRemainShort(remain)}`;
|
||
const note = expiry.source === "iat+30d" ? "(按签发时间 +30 天推算)" : "";
|
||
return { text: `该凭据(登录态)有效期至 ${when}${note},${left}`, remain };
|
||
}
|
||
function fmtRemainShort(remain) {
|
||
const dd = Math.floor(remain / 86400), hh = Math.floor((remain % 86400) / 3600),
|
||
mm = Math.floor((remain % 3600) / 60);
|
||
if (dd >= 1) return `${dd} 天${hh ? " " + hh + " 小时" : ""}`;
|
||
if (hh >= 1) return `${hh} 小时${mm ? " " + mm + " 分" : ""}`;
|
||
return `${Math.max(1, mm)} 分钟`;
|
||
}
|
||
function renderTokenExpiry(el, expiry) {
|
||
if (!el) return;
|
||
if (!expiry) { el.style.display = "none"; el.innerHTML = ""; return; }
|
||
const { text, remain } = describeTokenExpiry(expiry);
|
||
let color = "#34c759", bg = "#eafaf0";
|
||
if (remain <= 0) { color = "#e02020"; bg = "#fdecec"; }
|
||
else if (remain <= 259200) { color = "#e02020"; bg = "#fdecec"; } // ≤3 天
|
||
else if (remain <= 604800) { color = "#e67e22"; bg = "#fdf3e7"; } // ≤7 天
|
||
el.style.display = "block";
|
||
el.style.color = color;
|
||
el.style.background = bg;
|
||
el.textContent = text;
|
||
}
|
||
function updateTokenExpiryDisplays() {
|
||
// “填写凭证”弹窗:粘贴中的新 token 优先实时预览,否则显示已保存凭据
|
||
const authEl = document.getElementById("auth-token-expiry");
|
||
if (authEl) {
|
||
const pasted = document.getElementById("profile-token").value.trim();
|
||
if (pasted) {
|
||
const expiry = parseJwtExpiry(pasted);
|
||
if (expiry) {
|
||
renderTokenExpiry(authEl, expiry);
|
||
} else {
|
||
authEl.style.display = "block";
|
||
authEl.style.color = "#e67e22";
|
||
authEl.style.background = "#fdf3e7";
|
||
authEl.textContent = "无法解析该 AccessToken 的有效期(不是标准 JWT,仍可保存使用)";
|
||
}
|
||
} else {
|
||
renderTokenExpiry(authEl, _savedTokenExpiry);
|
||
}
|
||
}
|
||
// 个人中心:始终实时显示
|
||
const pEl = document.getElementById("profile-token-expiry");
|
||
if (pEl) renderTokenExpiry(pEl, _savedTokenExpiry);
|
||
renderAuthExpiryBanner();
|
||
}
|
||
let _savedTokenExpiry = null;
|
||
|
||
// ========== 登录态到期横幅 ==========
|
||
// 有效期不足 2 天时在主页面顶部常驻提醒,避免用户毫无预警地遇到上游凭据失效。
|
||
const AUTH_EXPIRY_BANNER_THRESHOLD = 2 * 86400; // 2 天
|
||
const AUTH_EXPIRY_BANNER_URGENT = 86400; // 不足 1 天转红
|
||
function renderAuthExpiryBanner() {
|
||
const banner = document.getElementById("auth-expiry-banner");
|
||
if (!banner) return;
|
||
const text = document.getElementById("auth-expiry-banner-text");
|
||
if (!authToken || !_savedTokenExpiry) {
|
||
banner.classList.remove("show", "urgent");
|
||
return;
|
||
}
|
||
const { remain } = describeTokenExpiry(_savedTokenExpiry);
|
||
if (remain > AUTH_EXPIRY_BANNER_THRESHOLD) {
|
||
banner.classList.remove("show", "urgent");
|
||
return;
|
||
}
|
||
const when = fmtLocalTime(_savedTokenExpiry.expireAt);
|
||
text.textContent = remain <= 0
|
||
? "登录态已过期,为不影响使用请尽快抓包"
|
||
: `登录态剩 ${fmtRemainShort(remain)},为不影响使用请尽快抓包`;
|
||
banner.title = `有效期至 ${when}`;
|
||
banner.classList.toggle("urgent", remain <= AUTH_EXPIRY_BANNER_URGENT);
|
||
banner.classList.add("show");
|
||
}
|
||
// 拉取服务端解析出的有效期(profile 接口),成功后刷新横幅
|
||
async function refreshAuthExpiry() {
|
||
if (!authToken) { _savedTokenExpiry = null; renderAuthExpiryBanner(); return; }
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const e = data.data.access_token_expiry;
|
||
_savedTokenExpiry = e && e.parseable
|
||
? { expireAt: e.expire_at, source: e.source } : null;
|
||
} else {
|
||
_savedTokenExpiry = null;
|
||
}
|
||
} catch (err) {
|
||
console.error("获取登录态有效期失败:", err);
|
||
}
|
||
updateTokenExpiryDisplays();
|
||
}
|
||
setInterval(updateTokenExpiryDisplays, 30000); // 实时倒计时:每 30 秒刷新
|
||
|
||
// 打开凭证填写弹窗
|
||
function openAuthModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("auth-modal");
|
||
// 填充现有值
|
||
fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
}).then(r => r.json()).then(data => {
|
||
if (data.rtn_code === 0 && data.data) {
|
||
document.getElementById("profile-token").value = data.data.token || "";
|
||
document.getElementById("profile-token-id").value = data.data.token_id || "";
|
||
const alertEl = document.getElementById("profile-alert-email");
|
||
if (alertEl) {
|
||
// 未自定义时显示账号邮箱占位(提交空串即回退账号邮箱)
|
||
alertEl.value = data.data.alert_email || "";
|
||
alertEl.placeholder = data.data.email || "留空则使用账号邮箱";
|
||
}
|
||
_savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable
|
||
? { expireAt: data.data.access_token_expiry.expire_at,
|
||
source: data.data.access_token_expiry.source } : null;
|
||
updateTokenExpiryDisplays();
|
||
}
|
||
});
|
||
}
|
||
|
||
function closeAuthModal() {
|
||
SettingsPages.back();
|
||
}
|
||
|
||
// ========== 强签名验证引导 ==========
|
||
let _strictGuideShown = false;
|
||
function maybeStrictGuide(info) {
|
||
if (info && info.strict_mode && info.has_access_token === false && !_strictGuideShown) {
|
||
_strictGuideShown = true;
|
||
showTokenExpiredModal(
|
||
"需要补充 AccessToken",
|
||
"管理员已开启强签名验证,您的账号尚未填写 AccessToken,填写前无法调用用车功能。请按教程抓包获取 accessToken(登录响应中的 JWT)并保存。"
|
||
);
|
||
}
|
||
}
|
||
async function checkStrictGuide() {
|
||
if (!authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0 && data.data) maybeStrictGuide(data.data);
|
||
} catch (err) { console.error("强验证检测失败:", err); }
|
||
}
|
||
|
||
// ========== 登录设备管理(多设备) ==========
|
||
// 生成本设备持久标识:同一浏览器/设备保持不变,用于区分不同登录设备
|
||
function getDeviceId() {
|
||
let id = localStorage.getItem("xbniu_device_id");
|
||
if (!id) {
|
||
id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
||
try { localStorage.setItem("xbniu_device_id", id); } catch (e) {}
|
||
}
|
||
return id;
|
||
}
|
||
function getDeviceName() {
|
||
const ua = navigator.userAgent || "";
|
||
// 与服务端 routes/auth.py _ua_label 保持同一套识别规则
|
||
if (/xbniu-native/i.test(ua)) return "Native App";
|
||
let os;
|
||
if (/Windows NT/.test(ua)) os = "Windows";
|
||
else if (/iPhone|iPad|iPod/.test(ua)) os = "iOS";
|
||
else if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) os = "鸿蒙";
|
||
else if (/Android/.test(ua)) os = "Android";
|
||
else if (/Mac OS X/.test(ua)) os = "macOS";
|
||
else if (/Linux/.test(ua)) os = "Linux";
|
||
else os = /Mobile/.test(ua) ? "移动设备" : "电脑";
|
||
let browser = "浏览器";
|
||
if (/MicroMessenger/i.test(ua)) browser = "微信";
|
||
else if (/HuaweiBrowser/.test(ua)) browser = "华为浏览器";
|
||
else if (/Edg\//.test(ua)) browser = "Edge";
|
||
else if (/QQBrowser/.test(ua)) browser = "QQ浏览器";
|
||
else if (/MiuiBrowser/.test(ua)) browser = "小米浏览器";
|
||
else if (/Chrome\//.test(ua)) browser = "Chrome";
|
||
else if (/Firefox\//.test(ua)) browser = "Firefox";
|
||
else if (/Safari\//.test(ua)) browser = "Safari";
|
||
let label = os + " · " + browser;
|
||
if (window.screen && screen.width) label += " · " + screen.width + "x" + screen.height;
|
||
return label;
|
||
}
|
||
function escHtml(s) {
|
||
return String(s == null ? "" : s).replace(/[&<>"']/g,
|
||
c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||
}
|
||
function fmtTime(t) {
|
||
if (!t) return "";
|
||
return escHtml(String(t).replace("T", " ").slice(0, 16));
|
||
}
|
||
function openDevicesModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("devices-modal");
|
||
loadDevicesList();
|
||
}
|
||
function closeDevicesModal() {
|
||
SettingsPages.back();
|
||
}
|
||
async function loadDevicesList() {
|
||
const box = document.getElementById("devices-list");
|
||
if (!authToken) { box.innerHTML = '<div class="devices-empty">请先登录</div>'; return; }
|
||
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||
try {
|
||
const resp = await fetch("/api/auth/sessions", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code !== 0) {
|
||
box.innerHTML = '<div class="devices-empty">' + escHtml(data.message || "加载失败") + '</div>';
|
||
return;
|
||
}
|
||
const list = data.data.sessions || [];
|
||
if (!list.length) {
|
||
box.innerHTML = '<div class="devices-empty">暂无其他登录设备</div>';
|
||
return;
|
||
}
|
||
box.innerHTML = list.map(s => {
|
||
const isCur = !!s.is_current;
|
||
const meta = "登录 " + fmtTime(s.created_at) +
|
||
(s.last_active ? " · 活跃 " + fmtTime(s.last_active) : "");
|
||
return `<div class="device-row">
|
||
<div class="device-main">
|
||
<div class="device-name">${escHtml(s.device_name || "未知设备")}${isCur ? ' <span class="device-badge">当前</span>' : ""}</div>
|
||
<div class="device-meta">${meta}</div>
|
||
</div>
|
||
${isCur ? "" : `<button class="device-kick" onclick="kickDevice(${Number(s.id)})">下线</button>`}
|
||
</div>`;
|
||
}).join("");
|
||
} catch (err) {
|
||
box.innerHTML = '<div class="devices-empty">加载失败</div>';
|
||
}
|
||
}
|
||
async function kickDevice(id) {
|
||
if (!(await appConfirm("确认将该设备下线?该设备需要重新登录。", { title: "下线设备", okText: "下线" }))) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/sessions/kick", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||
body: JSON.stringify({ session_id: id })
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) { showToast("已下线该设备"); loadDevicesList(); }
|
||
else showToast(data.message || "下线失败");
|
||
} catch (e) { showToast("网络错误"); }
|
||
}
|
||
async function logoutAllOtherDevices() {
|
||
if (!(await appConfirm("确认下线当前账号其他所有设备?\n本设备会保留登录。", { title: "下线其他设备", okText: "全部下线" }))) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/sessions/logout_all", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) { showToast("已下线其他所有设备"); loadDevicesList(); }
|
||
else showToast(data.message || "操作失败");
|
||
} catch (e) { showToast("网络错误"); }
|
||
}
|
||
|
||
// 打开卡包弹窗
|
||
function openPackagesModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("packages-modal");
|
||
loadPackagesList();
|
||
}
|
||
|
||
function closePackagesModal() {
|
||
SettingsPages.back();
|
||
}
|
||
|
||
// 加载卡包列表(用于卡包弹窗)
|
||
async function loadPackagesList() {
|
||
if (!authToken) {
|
||
document.getElementById("packages-list-2").innerHTML = '<div class="packages-empty">请先登录</div>';
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const resp = await fetch("/api/auth/packages", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
const container = document.getElementById("packages-list-2");
|
||
|
||
if (!data.data || !data.data.has_auth) {
|
||
container.innerHTML = '<div class="packages-empty">请先填写 Token ID(AccessToken 选填)</div>';
|
||
return;
|
||
}
|
||
|
||
const packages = data.data.packages || [];
|
||
if (packages.length === 0) {
|
||
container.innerHTML = '<div class="packages-empty">暂无优惠卡</div>';
|
||
return;
|
||
}
|
||
|
||
container.innerHTML = packages.map(pkg => `
|
||
<div class="package-card">
|
||
<div class="package-name">${pkg.name}</div>
|
||
<div class="package-info">${pkg.bikeTypeName || ''} · ${pkg.useTypeName || ''}</div>
|
||
<div class="package-time">有效期至 ${pkg.endTime || '无限'}</div>
|
||
<div class="package-times">剩余 ${pkg.remainTimes ?? '∞'} 次</div>
|
||
</div>
|
||
`).join('');
|
||
} catch (err) {
|
||
console.error("加载卡包失败:", err);
|
||
document.getElementById("packages-list-2").innerHTML = '<div class="packages-empty">加载失败</div>';
|
||
}
|
||
}
|
||
|
||
async function saveProfileToken() {
|
||
if (!authToken) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
|
||
const access_token = document.getElementById("profile-token").value.trim();
|
||
const token_id = document.getElementById("profile-token-id").value.trim();
|
||
const alertEmailEl = document.getElementById("profile-alert-email");
|
||
const alert_email = alertEmailEl ? alertEmailEl.value.trim().toLowerCase() : null;
|
||
|
||
// 如果填了任意一个字段,需要先验证
|
||
if (access_token || token_id) {
|
||
if (!token_id) {
|
||
showToast("Token ID 必填;AccessToken 选填");
|
||
return;
|
||
}
|
||
|
||
// 先验证(必须带登录态,否则 verify_token 返回 401)
|
||
try {
|
||
const verifyResp = await fetch("/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) {
|
||
showToast(verifyData.message || "凭据验证失败,请检查 Token ID 是否正确");
|
||
return;
|
||
}
|
||
} catch (err) {
|
||
showToast("验证失败");
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 验证通过或没填字段,直接保存
|
||
try {
|
||
const resp = await fetch("/api/auth/save_token", {
|
||
method: "POST",
|
||
headers: {
|
||
"Authorization": `Bearer ${authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify({ access_token, token_id })
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0) {
|
||
// 告警邮箱单独保存(可与凭据一起提交,失败不阻断)
|
||
if (alert_email !== null) {
|
||
fetch("/api/auth/alert_email", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json",
|
||
"Authorization": `Bearer ${authToken}` },
|
||
body: JSON.stringify({ email: alert_email })
|
||
}).catch(() => {});
|
||
}
|
||
showToast("保存成功");
|
||
closeAuthModal(); // 关闭凭证弹窗
|
||
loadProfileData(); // 刷新个人中心数据
|
||
refreshAuthExpiry(); // 新凭据可能已换有效期,重算顶部提醒
|
||
} else {
|
||
showToast(data.message || "保存失败");
|
||
}
|
||
} catch (err) {
|
||
showToast("保存失败");
|
||
}
|
||
}
|
||
|
||
// ========== 批量响铃相关状态 ==========
|
||
let currentBellTab = 'all'; // 当前选项卡
|
||
let selectedRadius = 200; // 选中的半径(米)
|
||
let selectedLocation = null; // 选中的地点 {lat, lng}
|
||
let selectedStatuses = {available: true, used: true, locked: true, low: true, reserved: true}; // 选中的状态
|
||
let rangeCircleOverlay = null; // 范围圆覆盖物
|
||
|
||
function showBellPasswordModal() {
|
||
if (!canUseBatchRing()) {
|
||
showToast("批量寻铃仅对指定用户开放");
|
||
return;
|
||
}
|
||
document.getElementById("bell-modal").classList.add("show");
|
||
// 重置所有输入
|
||
document.getElementById("bell-password").value = "";
|
||
document.getElementById("bell-password-range").value = "";
|
||
document.getElementById("bell-password-status").value = "";
|
||
document.getElementById("bell-error").textContent = "";
|
||
document.getElementById("bell-error-range").textContent = "";
|
||
document.getElementById("bell-error-status").textContent = "";
|
||
document.getElementById("bell-progress").textContent = "";
|
||
|
||
// 更新状态计数
|
||
updateStatusCounts();
|
||
|
||
// 重置范围相关
|
||
selectedLocation = null;
|
||
document.getElementById("range-point-text").textContent = "--";
|
||
document.getElementById("range-hint").classList.remove("active");
|
||
document.getElementById("range-hint").innerHTML = `
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
|
||
<circle cx="12" cy="12" r="10"/>
|
||
<path d="M12 8v4M12 16h.01"/>
|
||
</svg>
|
||
点击地图选择地点,或使用当前位置
|
||
`;
|
||
|
||
// 更新筛选信息
|
||
updateFilterInfo();
|
||
|
||
document.getElementById("bell-password").focus();
|
||
}
|
||
|
||
// 切换选项卡
|
||
function switchBellTab(tab) {
|
||
currentBellTab = tab;
|
||
|
||
// 更新选项卡样式
|
||
document.querySelectorAll('.bell-tab').forEach(t => {
|
||
t.classList.toggle('active', t.dataset.tab === tab);
|
||
});
|
||
|
||
// 更新内容区
|
||
document.querySelectorAll('.bell-section').forEach(s => {
|
||
s.classList.toggle('active', s.id === `bell-section-${tab}`);
|
||
});
|
||
|
||
// 切换到范围模式时清除之前的选择
|
||
if (tab !== 'range') {
|
||
if (rangeCircleOverlay) {
|
||
map.removeOverlay(rangeCircleOverlay);
|
||
rangeCircleOverlay = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 选择半径
|
||
function selectRadius(radius) {
|
||
selectedRadius = radius;
|
||
document.querySelectorAll('.radius-btn').forEach(btn => {
|
||
btn.classList.toggle('active', parseInt(btn.dataset.radius) === radius);
|
||
});
|
||
// 更新范围圆
|
||
updateRangeCircle();
|
||
updateFilterInfo();
|
||
}
|
||
|
||
// 使用当前位置
|
||
function useCurrentLocation() {
|
||
if (!autoLocationMarker) {
|
||
showToast("请先开启定位(点击底部定位按钮)");
|
||
return;
|
||
}
|
||
|
||
const point = autoLocationMarker.getPosition();
|
||
const lat = point.lat;
|
||
const lng = point.lng;
|
||
|
||
selectedLocation = { lat, lng };
|
||
|
||
document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||
document.getElementById("range-hint").classList.add("active");
|
||
document.getElementById("range-hint").innerHTML = `
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#34c759" stroke-width="2">
|
||
<path d="M20 6L9 17l-5-5"/>
|
||
</svg>
|
||
已选择:${lat.toFixed(5)}, ${lng.toFixed(5)}
|
||
`;
|
||
|
||
updateRangeCircle();
|
||
updateFilterInfo();
|
||
|
||
showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`);
|
||
}
|
||
|
||
// 使用地图中心
|
||
function useCenterLocation() {
|
||
const center = map.getCenter();
|
||
const lat = center.lat;
|
||
const lng = center.lng;
|
||
|
||
selectedLocation = { lat, lng };
|
||
|
||
document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||
document.getElementById("range-hint").classList.add("active");
|
||
document.getElementById("range-hint").innerHTML = `
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#34c759" stroke-width="2">
|
||
<path d="M20 6L9 17l-5-5"/>
|
||
</svg>
|
||
已选择:${lat.toFixed(5)}, ${lng.toFixed(5)}
|
||
`;
|
||
|
||
updateRangeCircle();
|
||
updateFilterInfo();
|
||
|
||
showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`);
|
||
}
|
||
|
||
// 更新范围圆覆盖物
|
||
function updateRangeCircle() {
|
||
if (!selectedLocation) return;
|
||
|
||
// 清除旧的
|
||
if (rangeCircleOverlay) {
|
||
map.removeOverlay(rangeCircleOverlay);
|
||
}
|
||
|
||
const point = new BMapGL.Point(selectedLocation.lng, selectedLocation.lat);
|
||
rangeCircleOverlay = new BMapGL.Circle(point, selectedRadius, {
|
||
strokeColor: "#007AFF",
|
||
strokeWeight: 2,
|
||
strokeOpacity: 0.6,
|
||
fillColor: "#007AFF",
|
||
fillOpacity: 0.1
|
||
});
|
||
map.addOverlay(rangeCircleOverlay);
|
||
}
|
||
|
||
// 切换状态筛选
|
||
function toggleStatusFilter(state) {
|
||
selectedStatuses[state] = !selectedStatuses[state];
|
||
|
||
const item = document.querySelector(`.bell-status-item[data-state="${state}"]`);
|
||
if (item) {
|
||
item.classList.toggle('selected', selectedStatuses[state]);
|
||
item.querySelector('.bell-status-check').textContent = selectedStatuses[state] ? '✓' : '';
|
||
}
|
||
|
||
updateFilterInfo();
|
||
}
|
||
|
||
// 更新状态计数
|
||
function updateStatusCounts() {
|
||
const bikes = Object.values(markersData);
|
||
const counts = {available: 0, used: 0, locked: 0, low: 0, reserved: 0};
|
||
|
||
bikes.forEach(bike => {
|
||
const state = getBikeState(bike);
|
||
if (state === 'available') counts.available++;
|
||
else if (state === 'inuse') counts.used++;
|
||
else if (state === 'locked') counts.locked++;
|
||
else if (state === 'lowbattery') counts.low++;
|
||
else if (state === 'reserved') counts.reserved++;
|
||
});
|
||
|
||
document.getElementById('count-available-filter').textContent = counts.available;
|
||
document.getElementById('count-used-filter').textContent = counts.used;
|
||
document.getElementById('count-locked-filter').textContent = counts.locked;
|
||
document.getElementById('count-low-filter').textContent = counts.low;
|
||
document.getElementById('count-reserved-filter').textContent = counts.reserved;
|
||
}
|
||
|
||
// 计算两点之间的距离(米)
|
||
function calcDistance(lat1, lng1, lat2, lng2) {
|
||
const R = 6371000; // 地球半径(米)
|
||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||
Math.sin(dLng/2) * Math.sin(dLng/2);
|
||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
||
return R * c;
|
||
}
|
||
|
||
// 导航相关已拆到 static/js/navigation.js
|
||
|
||
|
||
// 根据当前模式筛选车辆
|
||
function getFilteredBikes() {
|
||
const allBikes = Object.values(markersData);
|
||
|
||
if (currentBellTab === 'all') {
|
||
return allBikes;
|
||
}
|
||
|
||
if (currentBellTab === 'range') {
|
||
if (!selectedLocation) {
|
||
return []; // 没有选择地点
|
||
}
|
||
return allBikes.filter(bike => {
|
||
if (!bike.latitude || !bike.longitude) return false;
|
||
// 车辆在地图上显示的位置(偏移后)
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const dist = calcDistance(
|
||
selectedLocation.lat, selectedLocation.lng,
|
||
c.lat, c.lng
|
||
);
|
||
return dist <= selectedRadius;
|
||
});
|
||
}
|
||
|
||
if (currentBellTab === 'status') {
|
||
return allBikes.filter(bike => {
|
||
const state = getBikeState(bike);
|
||
if (state === 'available' && selectedStatuses.available) return true;
|
||
if (state === 'inuse' && selectedStatuses.used) return true;
|
||
if (state === 'locked' && selectedStatuses.locked) return true;
|
||
if (state === 'lowbattery' && selectedStatuses.low) return true;
|
||
if (state === 'reserved' && selectedStatuses.reserved) return true;
|
||
return false;
|
||
});
|
||
}
|
||
|
||
return allBikes;
|
||
}
|
||
|
||
// 更新筛选信息显示
|
||
function updateFilterInfo() {
|
||
const bikes = getFilteredBikes();
|
||
|
||
if (currentBellTab === 'range') {
|
||
const infoEl = document.getElementById('range-filter-info');
|
||
if (selectedLocation) {
|
||
infoEl.textContent = `范围内车辆:${bikes.length} 辆`;
|
||
} else {
|
||
infoEl.textContent = '';
|
||
}
|
||
}
|
||
|
||
if (currentBellTab === 'status') {
|
||
const infoEl = document.getElementById('status-filter-info');
|
||
const selectedCount = Object.values(selectedStatuses).filter(v => v).length;
|
||
infoEl.textContent = `已选 ${selectedCount} 种状态,共 ${bikes.length} 辆车`;
|
||
}
|
||
}
|
||
|
||
function closeBellModal() {
|
||
document.getElementById("bell-modal").classList.remove("show");
|
||
}
|
||
|
||
async function submitBellPassword() {
|
||
// 根据当前选项卡获取密码和错误元素
|
||
let pwd, errEl;
|
||
if (currentBellTab === 'all') {
|
||
pwd = document.getElementById("bell-password").value;
|
||
errEl = document.getElementById("bell-error");
|
||
} else if (currentBellTab === 'range') {
|
||
pwd = document.getElementById("bell-password-range").value;
|
||
errEl = document.getElementById("bell-error-range");
|
||
if (!selectedLocation) {
|
||
errEl.textContent = "请先选择地点(点击地图或使用当前位置/地图中心)";
|
||
return;
|
||
}
|
||
} else {
|
||
pwd = document.getElementById("bell-password-status").value;
|
||
errEl = document.getElementById("bell-error-status");
|
||
}
|
||
|
||
if (pwd !== "070517") {
|
||
errEl.textContent = "密码错误";
|
||
return;
|
||
}
|
||
|
||
// 根据模式筛选车辆
|
||
const bikes = getFilteredBikes();
|
||
|
||
if (bikes.length === 0) {
|
||
if (currentBellTab === 'range') {
|
||
errEl.textContent = "范围内没有车辆,请调整半径或选择其他地点";
|
||
} else if (currentBellTab === 'status') {
|
||
errEl.textContent = "没有符合条件的车,请调整状态筛选";
|
||
} else {
|
||
errEl.textContent = "暂无车辆数据,请先刷新地图";
|
||
}
|
||
return;
|
||
}
|
||
|
||
errEl.textContent = "启动中...";
|
||
|
||
try {
|
||
const res = await fetch("/api/ring_all", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${authToken}`
|
||
},
|
||
body: JSON.stringify({ codes: bikes.map(b => b.code) })
|
||
});
|
||
const data = await res.json();
|
||
if (data.rtn_code === 401) {
|
||
errEl.textContent = "登录已失效,请重新登录";
|
||
showLoginGate();
|
||
return;
|
||
}
|
||
if (data.rtn_code !== 0) {
|
||
errEl.textContent = data.message || "启动失败";
|
||
return;
|
||
}
|
||
|
||
closeBellModal();
|
||
|
||
// 清除范围圆
|
||
if (rangeCircleOverlay) {
|
||
map.removeOverlay(rangeCircleOverlay);
|
||
rangeCircleOverlay = null;
|
||
}
|
||
|
||
// 打开新窗口显示进度
|
||
const progressWin = window.open(
|
||
`/ring_progress.html?task_id=${data.task_id}&total=${data.total}`,
|
||
"ring_progress",
|
||
"width=450,height=520,menubar=no,toolbar=no,location=no,status=no"
|
||
);
|
||
if (!progressWin) {
|
||
showToast("请允许弹出窗口以查看进度");
|
||
}
|
||
} catch (e) {
|
||
errEl.textContent = "请求失败: " + friendlyError(e);
|
||
}
|
||
}
|
||
|
||
// ========== 全屏登录门 ==========
|
||
function showLoginGate() {
|
||
document.getElementById("login-gate").classList.add("show");
|
||
}
|
||
function hideLoginGate() {
|
||
document.getElementById("login-gate").classList.remove("show");
|
||
}
|
||
|
||
async function doLogin(email, password, tip, submitBtn) {
|
||
const btnText = submitBtn.textContent;
|
||
tip.textContent = "";
|
||
submitBtn.disabled = true;
|
||
submitBtn.textContent = "登录中...";
|
||
try {
|
||
const resp = await fetch("/api/auth/login", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email, password, device_id: getDeviceId(), device_name: getDeviceName() })
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0) {
|
||
authToken = data.data.token;
|
||
localStorage.setItem("auth_token", authToken);
|
||
currentUser = { email: data.data.email };
|
||
authKickToastShown = false;
|
||
updateAuthButton();
|
||
hideLoginGate();
|
||
closeLoginModal();
|
||
showToast("登录成功");
|
||
shareAfterLogin();
|
||
checkOrderStatus();
|
||
checkRentalStatus();
|
||
refreshAuthExpiry(); // 登录态有效期不足 2 天时挂顶部提醒
|
||
if (map) loadMapData(currentType, false);
|
||
} else {
|
||
tip.textContent = data.message || "登录失败";
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
} finally {
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = btnText;
|
||
}
|
||
}
|
||
|
||
async function handleLoginSubmit(e) {
|
||
e.preventDefault();
|
||
doLogin(
|
||
document.getElementById("login-email").value.trim().toLowerCase(),
|
||
document.getElementById("login-password").value,
|
||
document.getElementById("login-tip"),
|
||
e.target.querySelector("button[type='submit']")
|
||
);
|
||
}
|
||
|
||
document.getElementById("gate-login-form").addEventListener("submit", function (e) {
|
||
e.preventDefault();
|
||
doLogin(
|
||
document.getElementById("gate-email").value.trim().toLowerCase(),
|
||
document.getElementById("gate-password").value,
|
||
document.getElementById("gate-tip"),
|
||
this.querySelector("button[type='submit']")
|
||
);
|
||
});
|
||
|
||
let registerCodeCountdown = 0;
|
||
let registerCodeTimer = null;
|
||
function setRegisterCodeBtn(text, disabled) {
|
||
const btn = document.getElementById("register-code-btn");
|
||
if (!btn) return;
|
||
btn.disabled = disabled;
|
||
btn.textContent = text;
|
||
}
|
||
async function sendRegisterCode() {
|
||
const email = document.getElementById("register-email").value.trim().toLowerCase();
|
||
const tip = document.getElementById("register-tip");
|
||
if (!email) { tip.textContent = "请先填写邮箱"; return; }
|
||
if (registerCodeCountdown > 0) return;
|
||
setRegisterCodeBtn("发送中...", true);
|
||
try {
|
||
const resp = await fetch("/api/auth/send_code", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email })
|
||
});
|
||
const data = await resp.json();
|
||
tip.textContent = data.message || "";
|
||
if (data.rtn_code === 0) {
|
||
registerCodeCountdown = 60;
|
||
setRegisterCodeBtn(`${registerCodeCountdown}s`, true);
|
||
registerCodeTimer = setInterval(() => {
|
||
registerCodeCountdown--;
|
||
if (registerCodeCountdown <= 0) {
|
||
clearInterval(registerCodeTimer);
|
||
setRegisterCodeBtn("发送验证码", false);
|
||
} else {
|
||
setRegisterCodeBtn(`${registerCodeCountdown}s`, true);
|
||
}
|
||
}, 1000);
|
||
} else {
|
||
setRegisterCodeBtn("发送验证码", false);
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
setRegisterCodeBtn("发送验证码", false);
|
||
}
|
||
}
|
||
|
||
async function handleRegisterSubmit(e) {
|
||
e.preventDefault();
|
||
const email = document.getElementById("register-email").value.trim().toLowerCase();
|
||
const password = document.getElementById("register-password").value;
|
||
const code = document.getElementById("register-code").value.trim();
|
||
const invite_code = document.getElementById("register-invite").value.trim();
|
||
const token_id = document.getElementById("register-token-id").value.trim();
|
||
const access_token = document.getElementById("register-token").value.trim();
|
||
const tip = document.getElementById("register-tip");
|
||
const submitBtn = e.target.querySelector("button[type='submit']");
|
||
|
||
tip.textContent = "";
|
||
submitBtn.disabled = true;
|
||
submitBtn.textContent = "注册中...";
|
||
|
||
// 凭据字段的基础格式检查;上游有效性由 /api/auth/register 在服务端权威校验
|
||
// (注册时还没有登录态,verify_token 接口需要 Authorization,前端预检必然 401)
|
||
if (access_token || token_id) {
|
||
if (!token_id) {
|
||
tip.textContent = "Token ID 必填;AccessToken 选填";
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = "注册";
|
||
return;
|
||
}
|
||
}
|
||
|
||
try {
|
||
const resp = await fetch("/api/auth/register", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
email,
|
||
password,
|
||
code,
|
||
invite_code,
|
||
token_id: token_id || "",
|
||
access_token,
|
||
device_id: getDeviceId(),
|
||
device_name: getDeviceName()
|
||
})
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0) {
|
||
authToken = data.data.token;
|
||
localStorage.setItem("auth_token", authToken);
|
||
currentUser = { email: data.data.email };
|
||
authKickToastShown = false;
|
||
updateAuthButton();
|
||
closeRegisterModal();
|
||
hideLoginGate();
|
||
showToast("注册成功");
|
||
shareAfterLogin();
|
||
refreshAuthExpiry(); // 注册时可能已填凭证,立即评估有效期
|
||
if (map) loadMapData(currentType, false);
|
||
} else {
|
||
tip.textContent = data.message || "注册失败";
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
} finally {
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = "注册";
|
||
}
|
||
}
|
||
|
||
async function handleLogout() {
|
||
clearTimeout(mapRefreshTimer);
|
||
if (authToken) {
|
||
try {
|
||
await fetch("/api/auth/logout", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
} catch (err) {}
|
||
}
|
||
authToken = null;
|
||
currentUser = null;
|
||
localStorage.removeItem("auth_token");
|
||
authKickToastShown = false;
|
||
_savedTokenExpiry = null;
|
||
renderAuthExpiryBanner(); // 登出后隐藏登录态到期提醒
|
||
updateAuthButton();
|
||
closeProfileModal();
|
||
showToast("已登出");
|
||
showLoginGate();
|
||
const sb = document.getElementById("share-banners");
|
||
if (sb) sb.innerHTML = "";
|
||
shareAskQueue = [];
|
||
shareAskActive = false;
|
||
const askModal = document.getElementById("share-ask-modal");
|
||
if (askModal) askModal.classList.remove("show");
|
||
}
|
||
|
||
function updateAuthButton() {
|
||
const btn = document.getElementById("auth-btn");
|
||
const btnText = document.getElementById("auth-btn-text");
|
||
const avatar = document.getElementById("auth-avatar");
|
||
|
||
if (currentUser) {
|
||
btn.classList.add("logged-in");
|
||
btnText.style.display = "none";
|
||
avatar.style.display = "flex";
|
||
avatar.textContent = currentUser.email.charAt(0).toUpperCase();
|
||
} else {
|
||
btn.classList.remove("logged-in");
|
||
btnText.style.display = "inline";
|
||
avatar.style.display = "none";
|
||
btnText.textContent = "登录";
|
||
}
|
||
updateBellBtnVisibility();
|
||
}
|
||
|
||
// ========== 批量寻铃入口权限 ==========
|
||
// 仅指定用户可见/可用;服务端 /api/ring_all 同步校验
|
||
const BATCH_RING_ALLOWED_EMAILS = ["3146527494@qq.com"];
|
||
function canUseBatchRing() {
|
||
return !!(currentUser && BATCH_RING_ALLOWED_EMAILS.includes((currentUser.email || "").toLowerCase()));
|
||
}
|
||
function updateBellBtnVisibility() {
|
||
const btn = document.getElementById("bell-btn");
|
||
if (btn) btn.style.display = canUseBatchRing() ? "flex" : "none";
|
||
}
|
||
|
||
async function checkAuthStatus() {
|
||
if (!authToken) return;
|
||
|
||
try {
|
||
const resp = await fetch("/api/auth/status", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0 && data.data.logged_in) {
|
||
currentUser = { email: data.data.email };
|
||
updateAuthButton();
|
||
} else {
|
||
// token无效(可能被本设备或其他设备下线),清除登录状态
|
||
const hadToken = !!authToken;
|
||
authToken = null;
|
||
currentUser = null;
|
||
localStorage.removeItem("auth_token");
|
||
updateAuthButton();
|
||
if (hadToken && !authKickToastShown) {
|
||
authKickToastShown = true;
|
||
showToast("登录状态已失效,请重新登录");
|
||
showLoginGate();
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error("检查登录状态失败:", err);
|
||
}
|
||
}
|
||
|
||
// ========== 订单状态检测 ==========
|
||
let currentOrder = null; // 当前订单信息
|
||
|
||
async function checkOrderStatus() {
|
||
if (!authToken) {
|
||
hideOrderBanner();
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const resp = await fetch("/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;
|
||
|
||
fetch(`/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;
|
||
}
|
||
}
|
||
|
||
// 到期提醒:手机在兜里时页面横幅看不见,这里补一次震动 + 明确文案。
|
||
// 只在跨过阈值的瞬间触发,不会每秒抖。
|
||
let _orderLastAlertAt = 0;
|
||
function _alertOrderExpiring(remaining) {
|
||
const banner = document.getElementById("order-banner");
|
||
if (banner) banner.classList.add("expiring");
|
||
const el = document.getElementById("order-countdown");
|
||
if (el) el.textContent = `再骑 ${Math.max(0, remaining)} 秒就到期 · 超时要加钱`;
|
||
const now = Date.now();
|
||
if (now - _orderLastAlertAt < 25000) return; // 25 秒内只提醒一次
|
||
_orderLastAlertAt = now;
|
||
try {
|
||
if (navigator.vibrate) navigator.vibrate([200, 100, 200]);
|
||
} catch (e) { /* 不支持就算了 */ }
|
||
if (document.visibilityState === "visible") {
|
||
showToast("还有不到 1 分钟到期,就近停车还车");
|
||
}
|
||
}
|
||
function updateOrderCountdownText() {
|
||
const el = document.getElementById("order-countdown");
|
||
const remaining = Math.max(0, orderCountdownSeconds);
|
||
const mins = Math.floor(remaining / 60);
|
||
const secs = remaining % 60;
|
||
|
||
if (remaining > 0 && remaining <= 60) {
|
||
_alertOrderExpiring(remaining); // 内部会写文案/变色/震动
|
||
} else {
|
||
el.textContent = remaining > 0
|
||
? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}`
|
||
: "本轮到期 · 同步状态中";
|
||
}
|
||
|
||
// 变色提示
|
||
const banner = document.getElementById("order-banner");
|
||
if (remaining <= 60) {
|
||
el.style.color = "#ff3b30";
|
||
if (banner) banner.classList.add("expiring");
|
||
} else if (remaining <= 300) {
|
||
el.style.color = "#ffcc00";
|
||
if (banner) banner.classList.remove("expiring");
|
||
} else {
|
||
el.style.color = "white";
|
||
if (banner) banner.classList.remove("expiring");
|
||
}
|
||
}
|
||
|
||
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 fetch(
|
||
`/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 fetch("/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 fetch("/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;
|
||
// 先快照:等定位(最长 5 秒)期间 20 秒轮询可能把 currentOrder 置空,
|
||
// 之后再读 currentOrder.order_id 会抛 TypeError 并被吞成「临时锁车失败」。
|
||
const order = currentOrder;
|
||
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 fetch("/api/order/temp_lock", {
|
||
method: "POST",
|
||
headers: {
|
||
"Authorization": `Bearer ${authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify({
|
||
order_id: order.order_id,
|
||
code: order.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 fetch("/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,不依赖用户真实定位)
|
||
// 注意:开二维码弹窗时 startRental 会 closeCard() 把 selectedBike 清空,
|
||
// 所以坐标优先从 markersData 按车牌取,避免退化成硬编码的 (36.67, 116.98)。
|
||
const bikeForCoord = markersData[parseInt(code)] || markersData[code] || selectedBike;
|
||
const baseLat = parseFloat(bikeForCoord && bikeForCoord.latitude) || 36.67;
|
||
const baseLng = parseFloat(bikeForCoord && bikeForCoord.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; }
|
||
fetch("/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;
|
||
fetch("/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 fetch(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() 会把 unlockPendingCode 清空,先把车牌存到局部变量,
|
||
// 否则后面 startRentalFromServer 会把 null 写进 activeRental/localStorage。
|
||
const code = unlockPendingCode;
|
||
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, code, 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 fetch("/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);
|
||
}
|
||
|
||
// ========== 忘记密码 ==========
|
||
// 忘记密码可从两处打开:弹窗登录(login-modal)与全屏登录门(login-gate)。
|
||
// 用 _forgotFromGate 记住入口,重置成功后回到原处,避免用户被"换页面"。
|
||
let _forgotFromGate = false;
|
||
function showForgotModal() {
|
||
_forgotFromGate = false;
|
||
closeAllModals();
|
||
document.getElementById("forgot-modal").classList.add("show");
|
||
}
|
||
function showForgotFromGate() {
|
||
_forgotFromGate = true;
|
||
closeAllModals();
|
||
// 带上登录门里已填的邮箱,省去用户重复输入
|
||
const field = document.getElementById("gate-email");
|
||
const emailInput = document.getElementById("forgot-email");
|
||
if (field && emailInput && field.value.trim() && !emailInput.value.trim()) {
|
||
emailInput.value = field.value.trim();
|
||
}
|
||
document.getElementById("forgot-modal").classList.add("show");
|
||
}
|
||
function closeForgotModal() {
|
||
document.getElementById("forgot-modal").classList.remove("show");
|
||
document.getElementById("forgot-tip").textContent = "";
|
||
_forgotFromGate = false;
|
||
}
|
||
function backToLoginFromForgot() {
|
||
const fromGate = _forgotFromGate;
|
||
closeForgotModal();
|
||
if (fromGate) showLoginGate();
|
||
else showLoginModal();
|
||
}
|
||
let forgotTimer = null;
|
||
function setForgotCodeBtn(seconds) {
|
||
const btn = document.getElementById("forgot-code-btn");
|
||
if (forgotTimer) { clearInterval(forgotTimer); forgotTimer = null; }
|
||
if (seconds > 0) {
|
||
btn.disabled = true;
|
||
btn.textContent = `${seconds}s 后重发`;
|
||
forgotTimer = setInterval(() => {
|
||
seconds--;
|
||
if (seconds <= 0) {
|
||
clearInterval(forgotTimer); forgotTimer = null;
|
||
btn.disabled = false; btn.textContent = "发送验证码";
|
||
} else {
|
||
btn.textContent = `${seconds}s 后重发`;
|
||
}
|
||
}, 1000);
|
||
} else {
|
||
btn.disabled = false; btn.textContent = "发送验证码";
|
||
}
|
||
}
|
||
async function sendForgotCode() {
|
||
const email = document.getElementById("forgot-email").value.trim();
|
||
const tip = document.getElementById("forgot-tip");
|
||
if (!email) { tip.textContent = "请先填写注册邮箱"; return; }
|
||
tip.textContent = "发送中...";
|
||
try {
|
||
const resp = await fetch("/api/auth/send_code", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email: email, purpose: "reset" })
|
||
});
|
||
const data = await resp.json();
|
||
tip.textContent = data.message || "";
|
||
if (data.rtn_code === 0) setForgotCodeBtn(60);
|
||
} catch (err) {
|
||
tip.textContent = "发送失败,请检查网络";
|
||
}
|
||
}
|
||
async function handleForgotSubmit(event) {
|
||
event.preventDefault();
|
||
const email = document.getElementById("forgot-email").value.trim();
|
||
const code = document.getElementById("forgot-code").value.trim();
|
||
const password = document.getElementById("forgot-password").value;
|
||
const tip = document.getElementById("forgot-tip");
|
||
if (password.length < 6) { tip.textContent = "新密码至少 6 位"; return; }
|
||
tip.textContent = "提交中...";
|
||
try {
|
||
const resp = await fetch("/api/auth/reset_password", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email: email, code: code, password: password })
|
||
});
|
||
const data = await resp.json();
|
||
tip.textContent = data.message || "";
|
||
if (data.rtn_code === 0) {
|
||
// 回到用户进来的那个登录界面:登录门 → 回登录门;弹窗 → 回登录弹窗
|
||
const fromGate = _forgotFromGate;
|
||
setTimeout(() => {
|
||
closeForgotModal();
|
||
if (fromGate) {
|
||
showLoginGate();
|
||
const gateEmail = document.getElementById("gate-email");
|
||
const gatePwd = document.getElementById("gate-password");
|
||
if (gateEmail) gateEmail.value = email;
|
||
if (gatePwd) { gatePwd.value = ""; gatePwd.focus(); }
|
||
} else {
|
||
showLoginModal();
|
||
document.getElementById("login-email").value = email;
|
||
}
|
||
}, 900);
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "提交失败,请检查网络";
|
||
}
|
||
}
|
||
|
||
// ========== 订单历史(我的 → 订单历史) ==========
|
||
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:#ececf1;color:#6e6e73;">已完成</span>'
|
||
: '<span class="badge" style="padding:2px 8px;border-radius:8px;font-size:11px;background:#e8f5e9;color:#2e7d32;">进行中</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:#005bbf;">共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}</div>` : "";
|
||
const timeRow = `${fmtOrderTime(o.start_time)} ${fmtClock(o.start_time)} → ${fmtOrderTime(o.end_time)} ${fmtClock(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:#005bbf;"
|
||
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 fetch(`/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(会把 & 显示成 &)
|
||
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 {
|
||
fetch("/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);
|
||
}
|
||
async function openOrdersModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("orders-modal");
|
||
const box = document.getElementById("orders-list");
|
||
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||
try {
|
||
const resp = await fetch("/api/user/orders?limit=50", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code !== 0) {
|
||
box.innerHTML = `<div class="device-loading">${escHtml(data.message || "加载失败")}</div>`;
|
||
return;
|
||
}
|
||
const orders = data.data || [];
|
||
document.getElementById("orders-summary").textContent =
|
||
orders.length ? `最近 ${orders.length} 条用车记录(含共享)` : "还没有用车记录";
|
||
box.innerHTML = orders.length
|
||
? orders.map(orderCardHtml).join("")
|
||
: '<div class="device-loading">暂无订单</div>';
|
||
} catch (err) {
|
||
box.innerHTML = '<div class="device-loading">网络错误,请重试</div>';
|
||
}
|
||
}
|
||
function closeOrdersModal() {
|
||
SettingsPages.back();
|
||
}
|
||
|
||
// 订阅提醒已拆到 static/js/subscribe.js
|
||
|
||
// ========== 开锁前预览(月卡余量 + 轮次预估) ==========
|
||
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 fetch(`/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 =
|
||
`加 1 轮会<b>消耗 1 次优惠卡次数</b>(没有卡就按单次计费)。<br/>` +
|
||
`当前这一轮还剩约 <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 fetch("/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 天在主页面挂提醒横幅
|
||
}
|
||
});
|
||
|
||
function initMapCore() {
|
||
// 预加载基础图标(在请求地图数据之前就开始)
|
||
preloadBaseIcons();
|
||
|
||
fetch("/api/config")
|
||
.then(r => r.json())
|
||
.then(cfg => {
|
||
document.getElementById("school-name").textContent = cfg.school_name || "山东管理学院";
|
||
// 初始位置:整体偏移 + 额外上移30米 + 东移200米
|
||
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
|
||
c.lat += INIT_OFFSET_EXTRA;
|
||
c.lng += INIT_OFFSET_EAST;
|
||
|
||
// 初始化百度地图 GL
|
||
map = new BMapGL.Map("baidu_map");
|
||
// 地图实例刚建好:立刻把导航模块的拖动监听绑上(浏览器里唯一可靠的时机,
|
||
// 之前 navigation.js 只靠 setTimeout(0),那时 map 还是 null,监听从未生效)
|
||
try { if (typeof bindNavMapEvents === "function") bindNavMapEvents(); } catch (e) {}
|
||
map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
|
||
map.enableScrollWheelZoom(true);
|
||
map.enableDragging(true);
|
||
map.enableInertialDragging(true);
|
||
// 不加 NavigationControl:它带出的左上角方向键/缩放滑杆(以及其中的“定位失败”钮)
|
||
// 业务里用不到,双指缩放与拖拽手势不依赖该控件。
|
||
map.addControl(new BMapGL.ScaleControl());
|
||
|
||
updateMapStyle();
|
||
loadMapData(currentType);
|
||
|
||
// 启动自动持续定位(地图加载后立即开始)
|
||
startAutoLocation();
|
||
})
|
||
.catch(err => {
|
||
console.error("初始化失败:", err);
|
||
showToast("地图初始化失败,请刷新重试");
|
||
});
|
||
}
|
||
|
||
// ========== 深色模式适配 ==========
|
||
function updateMapStyle() {
|
||
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||
if (isDark) {
|
||
// Only filter the basemap canvas; native DOM overlays retain their colours.
|
||
const mapEl = document.getElementById("baidu_map");
|
||
mapEl.style.filter = "";
|
||
mapEl.style.setProperty("--basemap-filter", "invert(90%) hue-rotate(180deg) brightness(95%) contrast(90%)");
|
||
mapEl.style.background = "#1c1c1e";
|
||
} else {
|
||
// 浅色模式 - 移除滤镜
|
||
const mapEl = document.getElementById("baidu_map");
|
||
mapEl.style.filter = "";
|
||
mapEl.style.setProperty("--basemap-filter", "none");
|
||
mapEl.style.background = "";
|
||
}
|
||
}
|
||
|
||
// 监听系统颜色变化
|
||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
|
||
updateMapStyle();
|
||
});
|
||
|
||
// ========== 加载地图数据 ==========
|
||
let mapRequest = null;
|
||
let mapRefreshTimer = null;
|
||
let renderedMapSnapshot = null;
|
||
let mapRefreshFailed = false;
|
||
|
||
function scheduleMapRefresh(snapshot, serverTime, retrySeconds = 5) {
|
||
clearTimeout(mapRefreshTimer);
|
||
const expires = Number(snapshot?.expires_at);
|
||
const delay = Number.isFinite(expires) && Number.isFinite(serverTime)
|
||
? Math.max(500, (expires - serverTime) * 1000 + 150)
|
||
: Math.max(1000, retrySeconds * 1000);
|
||
mapRefreshTimer = setTimeout(() => {
|
||
if (authToken && map && document.visibilityState === "visible") {
|
||
loadMapData(currentType, false, true);
|
||
}
|
||
}, Math.min(delay, 60000));
|
||
}
|
||
|
||
function loadMapData(type, showLoading = true, quiet = false) {
|
||
if (!authToken) { showLoginGate(); return Promise.resolve(); }
|
||
if (!map) return Promise.resolve();
|
||
if (mapRequest && mapRequest.type === String(type)) return mapRequest.promise;
|
||
const requestToken = authToken;
|
||
const loading = document.getElementById("loading");
|
||
if (isFirstLoad && showLoading) loading.classList.remove("hidden");
|
||
const pending = { type: String(type), promise: null };
|
||
mapRequest = pending;
|
||
pending.promise = fetch(`/api/map?type=${encodeURIComponent(type)}`, {
|
||
headers: { "Authorization": `Bearer ${requestToken}` },
|
||
cache: "no-store"
|
||
})
|
||
.then(async response => {
|
||
const result = await response.json();
|
||
const stamp = response.headers.get("X-Map-Server-Time");
|
||
const serverTime = stamp !== null ? Number(stamp) : Date.now() / 1000;
|
||
return { result, serverTime };
|
||
})
|
||
.then(({ result, serverTime }) => {
|
||
if (authToken !== requestToken || String(type) !== String(currentType)) return;
|
||
loading.classList.add("hidden");
|
||
if (result.rtn_code === 401) { showLoginGate(); return; }
|
||
scheduleMapRefresh(result.map_snapshot, serverTime, result.retry_after || 5);
|
||
if (result.rtn_code !== 0) {
|
||
mapRefreshFailed = true;
|
||
updateMapFreshnessBadge();
|
||
if (!quiet) showToast(result.message || "车辆数据更新失败,正在自动重试");
|
||
return;
|
||
}
|
||
renderMap([result], !isFirstLoad);
|
||
isFirstLoad = false;
|
||
mapRefreshFailed = false;
|
||
if (result.map_snapshot) {
|
||
renderedMapSnapshot = { ...result.map_snapshot, serverTime, receivedAt: performance.now() };
|
||
updateMapFreshnessBadge();
|
||
} else updateTime();
|
||
if (map) setupClusterListener();
|
||
})
|
||
.catch(err => {
|
||
if (authToken !== requestToken || String(type) !== String(currentType)) return;
|
||
loading.classList.add("hidden");
|
||
mapRefreshFailed = true;
|
||
updateMapFreshnessBadge();
|
||
scheduleMapRefresh(null, null);
|
||
if (!quiet) showToast("加载失败: " + friendlyError(err));
|
||
})
|
||
.finally(() => { if (mapRequest === pending) mapRequest = null; });
|
||
return pending.promise;
|
||
}
|
||
|
||
// ========== 手动刷新 ==========
|
||
function refreshMap() {
|
||
const btn = document.getElementById("refresh-btn");
|
||
btn.classList.add("spinning");
|
||
loadMapData(currentType, false);
|
||
setTimeout(() => btn.classList.remove("spinning"), 1000);
|
||
}
|
||
|
||
// ========== 渲染地图(坐标归一化 + 增量气泡图层)==========
|
||
|
||
function renderMap(results, isRefresh = false) {
|
||
if (typeof BikeClusters === "undefined") {
|
||
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
|
||
}
|
||
// 扫码补的临时点每次渲染都回收:它们不在快照数据里,
|
||
// 不清理的话车早被骑走了地图上还留着一个能点开的旧点。
|
||
Object.keys(scannedMarkers).forEach((key) => {
|
||
try { map.removeOverlay(scannedMarkers[key]); } catch (e) {}
|
||
delete scannedMarkers[key];
|
||
delete currentMarkersById[key];
|
||
});
|
||
|
||
// 刷新时不清除边界和停车区(首次加载才绘制)
|
||
if (!isRefresh) {
|
||
// 保存自动定位标记的位置
|
||
const autoPoint = autoLocationMarker ? autoLocationMarker.getPosition() : null;
|
||
|
||
// 清除所有覆盖物
|
||
map.clearOverlays();
|
||
if (bikeBubbleLayer) {
|
||
bikeBubbleLayer.destroy();
|
||
bikeBubbleLayer = null;
|
||
}
|
||
|
||
// 清理旧的标记变量引用
|
||
autoLocationMarker = null;
|
||
myLocationMarker = null;
|
||
currentMarkers = [];
|
||
|
||
// 重新添加自动定位标记
|
||
if (autoPoint) {
|
||
const iconUrl = createAutoLocationIcon();
|
||
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||
autoLocationMarker = new BMapGL.Marker(autoPoint, { icon });
|
||
map.addOverlay(autoLocationMarker);
|
||
}
|
||
|
||
currentPolygons = [];
|
||
currentMarkersById = {};
|
||
markersData = {};
|
||
nearestBikeId = null;
|
||
}
|
||
|
||
const nextBikes = [];
|
||
let availableCount = 0;
|
||
let usedCount = 0;
|
||
let lockedCount = 0;
|
||
let reservedCount = 0;
|
||
let lowCount = 0;
|
||
|
||
results.forEach(result => {
|
||
if (result.rtn_code !== 0 || !result.data) return;
|
||
const data = result.data;
|
||
|
||
// 首次加载:绘制骑行区域边界
|
||
if (!isRefresh && data.driverArea && data.driverArea.length > 0) {
|
||
const boundaryPoints = data.driverArea.map(p => {
|
||
const c = offsetCoord(p.latitude, p.longitude);
|
||
return new BMapGL.Point(c.lng, c.lat);
|
||
});
|
||
const boundaryPolygon = new BMapGL.Polygon(boundaryPoints, {
|
||
strokeColor: "#007AFF",
|
||
strokeWeight: 2,
|
||
strokeOpacity: 0.8,
|
||
fillColor: "#007AFF",
|
||
fillOpacity: 0.05,
|
||
});
|
||
map.addOverlay(boundaryPolygon);
|
||
currentPolygons.push(boundaryPolygon);
|
||
}
|
||
|
||
// 首次加载:绘制停车区(只画启用的:is_disable=2 是停用区,
|
||
// 上游 /record/checkLocation 会直接拒绝,画出来只会误导人)
|
||
if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) {
|
||
data.parkeArea.forEach(area => {
|
||
if (!area.points || area.points.length < 3) return;
|
||
if (String(area.is_disable) === "2") return;
|
||
|
||
const parkingPoints = area.points.map(p => {
|
||
const c = offsetCoord(p.latitude, p.longitude);
|
||
return new BMapGL.Point(c.lng, c.lat);
|
||
});
|
||
const parkingPolygon = new BMapGL.Polygon(parkingPoints, {
|
||
strokeColor: "#34C759",
|
||
strokeWeight: 2,
|
||
strokeOpacity: 0.8,
|
||
fillColor: "#34C759",
|
||
fillOpacity: 0.1,
|
||
});
|
||
map.addOverlay(parkingPolygon);
|
||
currentPolygons.push(parkingPolygon);
|
||
});
|
||
}
|
||
|
||
// 收集所有车辆数据用于批量处理
|
||
const allBikes = BikeClusters.normalizeBikes(data.bicycleStation);
|
||
|
||
// 统计数量(所有车辆)
|
||
// 分类顺序必须与后端 app.py::_classify_bike_state 一致:
|
||
// state=10 或 电量<20 优先判低电量,其次欠压/损坏,最后 state=1 分使用中/可用。
|
||
// 注意电量字段是 electric_quantity(上游字段名),不存在 bike.electric。
|
||
allBikes.forEach(bike => {
|
||
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||
if (bike.state === 10 || electric < 20) {
|
||
lowCount++;
|
||
} else if (bike.state === 1 && bike.status === 1) {
|
||
usedCount++;
|
||
} else if (bike.state === 1) {
|
||
availableCount++;
|
||
} else if (bike.state === 4) {
|
||
lockedCount++;
|
||
} else if (bike.state === 2) {
|
||
reservedCount++;
|
||
}
|
||
});
|
||
|
||
nextBikes.push(...allBikes);
|
||
});
|
||
|
||
// A response is a complete snapshot: remove vanished cars and honour empty results.
|
||
markersData = {};
|
||
nextBikes.forEach(bike => { markersData[BikeClusters.bikeId(bike)] = bike; });
|
||
document.getElementById("count-available").textContent = availableCount;
|
||
document.getElementById("count-used").textContent = usedCount;
|
||
document.getElementById("count-locked").textContent = lockedCount;
|
||
document.getElementById("count-reserved").textContent = reservedCount;
|
||
document.getElementById("count-low").textContent = lowCount;
|
||
rebuildMarkersForZoom(nextBikes);
|
||
}
|
||
|
||
// Native overlay coordinates keep markers aligned during reverse zooming.
|
||
// Recomposition cross-fades at the real coordinates instead of moving centroids.
|
||
let bikeBubbleLayer = null;
|
||
function setupClusterListener() {
|
||
if (!map || bikeBubbleLayer || typeof BikeClusters === "undefined") return;
|
||
bikeBubbleLayer = BikeClusters.createLayer({
|
||
map,
|
||
enabled: bikeClusteringEnabled,
|
||
getPoint: bike => offsetCoord(bike.latitude, bike.longitude),
|
||
getState: getBikeState,
|
||
getIcon: getBikeIcon,
|
||
onBikeClick: id => { clearHighlight(); showBikeDetail(id); },
|
||
onMarkersChanged: markers => {
|
||
currentMarkers = markers;
|
||
currentMarkersById = {};
|
||
markers.forEach(marker => { currentMarkersById[marker.__animId] = marker; });
|
||
}
|
||
});
|
||
bikeBubbleLayer.setSelected(highlightedBikeId);
|
||
}
|
||
|
||
function rebuildMarkersForZoom(bikes) {
|
||
setupClusterListener();
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setData(bikes ?? Object.values(markersData));
|
||
}
|
||
|
||
// ========== 车辆详情 ==========
|
||
// 卡片顶部按钮是否收成纯图标:不按屏宽猜,直接量车牌有没有被截断。
|
||
// 车牌越长越早收;收起后再量一次,仍截断就保持(空间真不够了)。
|
||
function _fitCardActions() {
|
||
const card = document.getElementById("bike-card");
|
||
const codeEl = document.getElementById("card-code");
|
||
const title = card && card.querySelector(".bike-card-title");
|
||
if (!card || !codeEl) return;
|
||
card.classList.remove("compact-actions");
|
||
// 读一次布局,看车牌是否被 ellipsis 截断
|
||
const truncated = (title && title.scrollWidth > title.clientWidth + 1)
|
||
|| (codeEl.scrollWidth > codeEl.clientWidth + 1);
|
||
if (truncated) card.classList.add("compact-actions");
|
||
}
|
||
let _fitCardTimer = null;
|
||
window.addEventListener("resize", () => {
|
||
clearTimeout(_fitCardTimer);
|
||
_fitCardTimer = setTimeout(() => {
|
||
if (document.getElementById("bike-card"))
|
||
_fitCardActions();
|
||
}, 120);
|
||
});
|
||
|
||
function showBikeDetail(id) {
|
||
let bike = markersData[id];
|
||
// 多格式尝试查找
|
||
if (!bike) bike = markersData[String(id)];
|
||
if (!bike) bike = markersData[Number(id)];
|
||
// 按 code 遍历查找
|
||
if (!bike) {
|
||
for (const key in markersData) {
|
||
if (markersData[key] && String(markersData[key].code) === String(id)) {
|
||
bike = markersData[key];
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if (!bike) {
|
||
console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(markersData).slice(0, 5));
|
||
return;
|
||
}
|
||
// 换了另一辆车:先把上一辆的导航停掉,避免路线残留在图上
|
||
if (typeof _nav !== "undefined" && _nav && String(_nav.destCode) !== String(bike.code)) {
|
||
try { stopNavigation(); } catch (e) {}
|
||
}
|
||
selectedBike = bike;
|
||
|
||
// 设置高亮
|
||
setHighlight(id);
|
||
|
||
document.getElementById("card-code").textContent = `#${bike.code || id}`;
|
||
|
||
// 正在导航的就是这辆车 -> 按钮显示「结束」
|
||
_navBtnText((_nav && String(_nav.destCode) === String(bike.code)) ? "结束" : "导航");
|
||
|
||
// 距离/步行时间:取自动定位留下的标记点(BD09),没开定位就整格隐藏。
|
||
// 注意别引用 watchPosition 回调里的局部 myPoint —— 那是函数内变量。
|
||
const metaLeft = document.getElementById("card-meta-left");
|
||
const distEl = document.getElementById("card-distance");
|
||
const walkEl = document.getElementById("card-walk");
|
||
let distMeters = null; // 直线距离(BD09 平面对比),用于决定是否显示导航按钮
|
||
if (metaLeft && distEl && walkEl) {
|
||
let distText = "";
|
||
let walkText = "";
|
||
try {
|
||
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||
? autoLocationMarker.getPosition() : null;
|
||
if (me && bike.latitude && bike.longitude) {
|
||
const c = offsetCoord(bike.latitude, bike.longitude); // GCJ02 -> BD09
|
||
const meters = calcDistance(me.lat, me.lng, c.lat, c.lng);
|
||
distMeters = meters;
|
||
if (Number.isFinite(meters) && meters < MAX_WALK_DISTANCE_M) {
|
||
distText = meters < 1000
|
||
? `距你 ${Math.round(meters)} 米`
|
||
: `距你 ${(meters / 1000).toFixed(1)} 公里`;
|
||
walkText = `步行 ${Math.max(1, Math.round(meters / 80))} 分钟`;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
distText = "";
|
||
walkText = "";
|
||
}
|
||
distEl.textContent = distText;
|
||
walkEl.textContent = walkText;
|
||
metaLeft.hidden = !distText;
|
||
}
|
||
|
||
// 太远就不给「导航」按钮(百度步行路线超过 200km 会直接报错,
|
||
// 而且现实中也没人会走 20 公里去取车)。正在导航这辆车时始终保留「结束」。
|
||
const navBtnEl2 = document.getElementById("bike-nav-btn");
|
||
if (navBtnEl2) {
|
||
const navigatingThis = _nav && String(_nav.destCode) === String(bike.code);
|
||
const tooFar = !navigatingThis && Number.isFinite(distMeters)
|
||
&& distMeters >= MAX_WALK_DISTANCE_M;
|
||
navBtnEl2.style.display = tooFar ? "none" : "";
|
||
}
|
||
// 车牌长短 + 屏宽一起决定按钮是否收成纯图标
|
||
_fitCardActions();
|
||
|
||
// 异步换成「真实道路距离 + 步行耗时」:先问后端(百度轻量级路线规划),
|
||
// 后端没配 AK 就退到浏览器端 JS API,两者都失败则保留上面的直线估算。
|
||
refineWalkRoute(bike);
|
||
|
||
// 车辆类型角标(红车 / 大车 / 小车)
|
||
const kind = getBikeKind(bike);
|
||
const kindEl = document.getElementById("card-kind");
|
||
if (kindEl) {
|
||
kindEl.textContent = kind.label;
|
||
kindEl.classList.remove("kind-red", "kind-big", "kind-small");
|
||
kindEl.classList.add("kind-" + kind.key);
|
||
}
|
||
|
||
const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0);
|
||
document.getElementById("card-electric").textContent = Math.round(electric);
|
||
|
||
let ringColor = "#34c759";
|
||
const bikeState = getBikeState(bike);
|
||
if (bikeState === 'inuse') {
|
||
ringColor = "#ff2d55";
|
||
} else if (bikeState === 'locked') {
|
||
ringColor = "#ff9f0a";
|
||
} else if (bikeState === 'reserved') {
|
||
ringColor = "#5856D6";
|
||
} else if (bikeState === 'lowbattery' || electric < 20) {
|
||
ringColor = "#8e8e93";
|
||
}
|
||
try {
|
||
updateRingProgress(electric, ringColor);
|
||
} catch (e) {
|
||
console.error("[showBikeDetail] updateRingProgress 错误:", e);
|
||
}
|
||
|
||
// 状态文本:结合 state 和 status 判断
|
||
let stateText = "--";
|
||
if (bike.state === 1 && bike.status === 1) {
|
||
stateText = "使用中";
|
||
} else if (bike.state === 1) {
|
||
stateText = "空闲";
|
||
} else if (bike.state === 10) {
|
||
stateText = "低电量";
|
||
} else if (bike.state === 4) {
|
||
stateText = "欠压车辆";
|
||
} else if (bike.state === 2) {
|
||
stateText = "损坏车辆";
|
||
} else {
|
||
stateText = "未知";
|
||
}
|
||
document.getElementById("card-state").textContent = stateText;
|
||
document.getElementById("card-state").className = "bike-status-value" +
|
||
(stateText === "使用中" ? " warning" : stateText === "空闲" ? " highlight" : "");
|
||
|
||
document.getElementById("bike-card").classList.add("show");
|
||
const overlay = document.getElementById("card-overlay");
|
||
if (overlay) overlay.classList.add("show");
|
||
|
||
if (bike.latitude && bike.longitude) {
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
||
map.panTo(bikePoint);
|
||
// 单实例定时器 + 放大上限:以前每开一次卡片就排一个不跟踪的 setTimeout,
|
||
// 连点几辆车会把地图永久放大到最大级别。
|
||
clearTimeout(_cardZoomTimer);
|
||
_cardZoomTimer = setTimeout(() => {
|
||
if (map.getZoom() < 19) map.setZoom(map.getZoom() + 1);
|
||
}, 300);
|
||
}
|
||
}
|
||
let _cardZoomTimer = null;
|
||
|
||
function closeCard() {
|
||
// 关卡片**不**结束导航(导航条上有单独的「结束导航」按钮)
|
||
const card = document.getElementById("bike-card");
|
||
const overlay = document.getElementById("card-overlay");
|
||
card.classList.remove("show");
|
||
card.style.transform = "";
|
||
if (overlay) overlay.classList.remove("show");
|
||
selectedBike = null;
|
||
// 关闭卡片时清除高亮,让车辆图标还原为普通大小(不再保持放大带车牌)
|
||
clearHighlight();
|
||
// 关闭卡片时同步停止丢失模式
|
||
if (typeof disableLostMode === "function") disableLostMode();
|
||
}
|
||
|
||
// ========== 下滑关闭手势 ==========
|
||
(function initSwipeClose() {
|
||
const card = document.getElementById("bike-card");
|
||
let startY = 0, startTime = 0, dragging = false;
|
||
|
||
card.addEventListener("touchstart", (e) => {
|
||
// 只响应从 card-handle 或卡片顶部区域发起的手势
|
||
startY = e.touches[0].clientY;
|
||
startTime = Date.now();
|
||
dragging = true;
|
||
card.style.transition = "none";
|
||
}, { passive: true });
|
||
|
||
card.addEventListener("touchmove", (e) => {
|
||
if (!dragging) return;
|
||
const dy = e.touches[0].clientY - startY;
|
||
if (dy > 0) {
|
||
card.style.transform = `translateY(${dy}px)`;
|
||
}
|
||
}, { passive: true });
|
||
|
||
card.addEventListener("touchend", (e) => {
|
||
if (!dragging) return;
|
||
dragging = false;
|
||
card.style.transition = "";
|
||
const dy = e.changedTouches[0].clientY - startY;
|
||
const dt = Date.now() - startTime;
|
||
// 快速下划(速度 > 0.5px/ms)或位移超过120px则关闭
|
||
if (dy > 120 || (dy > 40 && dt < 250)) {
|
||
closeCard();
|
||
} else {
|
||
card.style.transform = "";
|
||
}
|
||
}, { passive: true });
|
||
})();
|
||
|
||
// ========== 扫码查询 ==========
|
||
function scanCode() {
|
||
const code = document.getElementById("scan-input").value.trim();
|
||
if (!code) { showToast("请输入车牌号"); return; }
|
||
|
||
showToast("正在查询...");
|
||
fetch("/api/bicycle", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${authToken}` },
|
||
body: JSON.stringify({ code })
|
||
})
|
||
.then(r => r.json())
|
||
.then(data => {
|
||
const codeNum = parseInt(code);
|
||
if (data.rtn_code === 401) { showLoginGate(); return; }
|
||
|
||
// 成功查询:正常处理
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const bike = data.data;
|
||
bike.code = code;
|
||
|
||
// 优先用 markersData 的实时位置,其次用 API 返回的位置
|
||
const mapBike = markersData[codeNum] || markersData[code];
|
||
let hasLocation = false;
|
||
|
||
if (mapBike && mapBike.latitude && mapBike.longitude) {
|
||
bike.latitude = mapBike.latitude;
|
||
bike.longitude = mapBike.longitude;
|
||
bike.state = mapBike.state;
|
||
bike.electric_quantity = mapBike.electric_quantity;
|
||
hasLocation = true;
|
||
} else if (bike.latitude && bike.longitude) {
|
||
hasLocation = true;
|
||
}
|
||
|
||
if (hasLocation) {
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
map.panTo(new BMapGL.Point(c.lng, c.lat));
|
||
setTimeout(() => map.setZoom(map.getZoom() + 1), 300);
|
||
} else {
|
||
showToast("该车暂无实时位置,请在地图上查看");
|
||
}
|
||
|
||
// 如果车辆在使用中,额外提示
|
||
if (bike.state === 1 && bike.status === 1) {
|
||
showToast("该车正在使用中");
|
||
}
|
||
|
||
markersData[codeNum] = bike;
|
||
|
||
// 地图上可能还没有这辆车(已被骑走 / 不在当前车型里):
|
||
// 补一个高亮标记,否则「查到了但地图上什么都没有」
|
||
if (hasLocation && !currentMarkersById[codeNum]) {
|
||
try {
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const marker = new BMapGL.Marker(
|
||
new BMapGL.Point(c.lng, c.lat),
|
||
{ icon: getBikeIcon(bike, true) }
|
||
);
|
||
map.addOverlay(marker);
|
||
currentMarkers.push(marker);
|
||
currentMarkersById[codeNum] = marker;
|
||
scannedMarkers[codeNum] = marker;
|
||
bindMarkerTap(marker, codeNum);
|
||
} catch (e) {
|
||
console.warn("[扫码] 补标记失败:", e);
|
||
}
|
||
}
|
||
|
||
showBikeDetail(codeNum);
|
||
}
|
||
// success=false 时,也尝试用 markersData 显示详情和定位
|
||
else if (data.success === false) {
|
||
const mapBike = markersData[codeNum] || markersData[code];
|
||
if (mapBike && mapBike.latitude && mapBike.longitude) {
|
||
// 跳转并放大
|
||
const c = offsetCoord(mapBike.latitude, mapBike.longitude);
|
||
map.panTo(new BMapGL.Point(c.lng, c.lat));
|
||
setTimeout(() => map.setZoom(map.getZoom() + 1), 300);
|
||
// 弹详情窗口
|
||
mapBike.code = code;
|
||
markersData[codeNum] = mapBike;
|
||
showBikeDetail(codeNum);
|
||
// toast 提示
|
||
showToast(data.message || "该车辆已被使用");
|
||
} else {
|
||
showToast(data.message || "查询失败");
|
||
}
|
||
}
|
||
else {
|
||
showToast(data.message || "查询失败");
|
||
}
|
||
})
|
||
.catch(err => showToast("请求失败: " + friendlyError(err)));
|
||
}
|
||
|
||
// ========== 寻车功能 ==========
|
||
|
||
// ----- 丢失模式状态 -----
|
||
let _lostModeActive = false; // 是否处于丢失模式
|
||
let _lostModeTimer = null; // setInterval 句柄
|
||
let _findClickCount = 0; // 连续点击次数计数
|
||
let _findClickTimer = null; // 连续点击重置计时器
|
||
let _findLongPressTimer = null; // 长按计时器
|
||
const LOST_TRIGGER_CLICKS = 3; // 连续点击 N 次触发
|
||
const LOST_TRIGGER_LONG = 700; // 长按毫秒数触发
|
||
const LOST_INTERVAL = 3000; // 丢失模式下每次寻车间隔(ms)
|
||
|
||
/** 发送单次寻车请求(内部使用,不操作按钮状态) */
|
||
function _doFindBikeRequest(code) {
|
||
return fetch("/api/find_bike", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${authToken}`
|
||
},
|
||
body: JSON.stringify({ code: code, school_id: 10 })
|
||
}).then(r => r.json()).catch(() => null);
|
||
}
|
||
|
||
/** 打开丢失模式确认弹窗 */
|
||
function showLostModal() {
|
||
document.getElementById("lost-modal").classList.add("show");
|
||
}
|
||
|
||
/** 关闭丢失模式确认弹窗(不启用) */
|
||
function closeLostModal() {
|
||
document.getElementById("lost-modal").classList.remove("show");
|
||
}
|
||
|
||
/** 启用丢失模式(弹窗确认后调用) */
|
||
function enableLostMode() {
|
||
closeLostModal();
|
||
if (!selectedBike) return;
|
||
_lostModeActive = true;
|
||
|
||
const btn = document.getElementById("bike-find-btn-header");
|
||
const span = btn && btn.querySelector("span");
|
||
btn.classList.add("lost-mode");
|
||
btn.title = "丢失模式(点击退出)";
|
||
if (span) span.textContent = "丢失模式";
|
||
|
||
showToast("丢失模式已开启,持续帮你寻车");
|
||
|
||
// 立即发一次
|
||
_doFindBikeRequest(selectedBike.code);
|
||
|
||
// 持续循环
|
||
_lostModeTimer = setInterval(() => {
|
||
if (!_lostModeActive || !selectedBike) {
|
||
disableLostMode();
|
||
return;
|
||
}
|
||
_doFindBikeRequest(selectedBike.code);
|
||
}, LOST_INTERVAL);
|
||
|
||
// 页面隐藏或关闭时自动停止
|
||
window.addEventListener("beforeunload", _onPageUnload);
|
||
document.addEventListener("visibilitychange", _onVisibilityChange);
|
||
}
|
||
|
||
/** 停止丢失模式 */
|
||
function disableLostMode() {
|
||
if (!_lostModeActive) return;
|
||
_lostModeActive = false;
|
||
clearInterval(_lostModeTimer);
|
||
_lostModeTimer = null;
|
||
_findClickCount = 0;
|
||
|
||
const btn = document.getElementById("bike-find-btn-header");
|
||
const span = btn && btn.querySelector("span");
|
||
if (btn) {
|
||
btn.classList.remove("lost-mode");
|
||
btn.disabled = false;
|
||
btn.title = "寻车";
|
||
}
|
||
if (span) span.textContent = "寻车";
|
||
|
||
window.removeEventListener("beforeunload", _onPageUnload);
|
||
document.removeEventListener("visibilitychange", _onVisibilityChange);
|
||
|
||
showToast("丢失模式已关闭");
|
||
}
|
||
|
||
function _onPageUnload() { disableLostMode(); }
|
||
function _onVisibilityChange() {
|
||
if (document.visibilityState === "hidden") disableLostMode();
|
||
}
|
||
|
||
/**
|
||
* 主寻车入口(绑定到按钮 onclick)
|
||
* - 丢失模式激活时:点击直接关闭丢失模式
|
||
* - 连续点击 LOST_TRIGGER_CLICKS 次:触发丢失模式弹窗
|
||
* - 否则:正常寻车
|
||
*/
|
||
function findBike() {
|
||
if (!selectedBike) return;
|
||
|
||
// 如果已是丢失模式,点击退出
|
||
if (_lostModeActive) {
|
||
disableLostMode();
|
||
return;
|
||
}
|
||
|
||
// 连续点击计数
|
||
_findClickCount++;
|
||
clearTimeout(_findClickTimer);
|
||
_findClickTimer = setTimeout(() => { _findClickCount = 0; }, 1200);
|
||
|
||
if (_findClickCount >= LOST_TRIGGER_CLICKS) {
|
||
_findClickCount = 0;
|
||
clearTimeout(_findClickTimer);
|
||
showLostModal();
|
||
return;
|
||
}
|
||
|
||
// 正常寻车
|
||
const code = selectedBike.code;
|
||
const btn = document.getElementById("bike-find-btn-header");
|
||
const span = btn && btn.querySelector("span");
|
||
|
||
btn.disabled = true;
|
||
btn.title = "发送中...";
|
||
if (span) span.textContent = "发送中...";
|
||
|
||
_doFindBikeRequest(code)
|
||
.then(data => {
|
||
if (data && (data.rtn_code === 0 || data.success)) {
|
||
showToast("寻车指令已发送,请听声音");
|
||
} else {
|
||
showToast((data && data.message) || "寻车失败");
|
||
}
|
||
})
|
||
.catch(err => {
|
||
showToast("请求失败: " + friendlyError(err));
|
||
})
|
||
.finally(() => {
|
||
if (!_lostModeActive) {
|
||
btn.disabled = false;
|
||
btn.title = "寻车";
|
||
if (span) span.textContent = "寻车";
|
||
}
|
||
});
|
||
}
|
||
|
||
// ===== 长按触发丢失模式 =====
|
||
(function initFindBtnLongPress() {
|
||
const btn = document.getElementById("bike-find-btn-header");
|
||
if (!btn) return;
|
||
|
||
function startLongPress(e) {
|
||
// 丢失模式下不需要长按(单击退出即可)
|
||
if (_lostModeActive) return;
|
||
clearTimeout(_findLongPressTimer);
|
||
_findLongPressTimer = setTimeout(() => {
|
||
// 长按成功,阻止后续 click 事件触发普通寻车
|
||
_findClickCount = 0;
|
||
clearTimeout(_findClickTimer);
|
||
showLostModal();
|
||
}, LOST_TRIGGER_LONG);
|
||
}
|
||
|
||
function cancelLongPress() {
|
||
clearTimeout(_findLongPressTimer);
|
||
}
|
||
|
||
btn.addEventListener("mousedown", startLongPress);
|
||
btn.addEventListener("touchstart", startLongPress, { passive: true });
|
||
btn.addEventListener("mouseup", cancelLongPress);
|
||
btn.addEventListener("mouseleave", cancelLongPress);
|
||
btn.addEventListener("touchend", cancelLongPress);
|
||
btn.addEventListener("touchcancel", cancelLongPress);
|
||
})();
|
||
|
||
// ========== 用车计时相关 ==========
|
||
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 fetch("/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 fetch("/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 fetch("/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;
|
||
}
|
||
console.log("[checkRentalStatus] 发送请求, authToken:", authToken);
|
||
fetch("/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;
|
||
}
|
||
|
||
// 调后端开启计时
|
||
fetch("/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 fetch("/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("该车已损坏,无法使用"); // 上游 state=2 表示损坏,不是被预约
|
||
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 = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||
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();
|
||
});
|
||
|
||
// ========== 通用确认弹窗(替换 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.
|
||
fetch(`/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 fetch("/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 fetch("/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 fetch("/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 fetch("/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 = "保存失败";
|
||
}
|
||
}
|
||
|
||
// ========== 定位最近车辆(手动找车)==========
|
||
function locateMe() {
|
||
if (!navigator.geolocation) {
|
||
showToast("您的浏览器不支持定位");
|
||
return;
|
||
}
|
||
|
||
// 启动自动持续定位(页面启动时调用一次即可)
|
||
startAutoLocation();
|
||
}
|
||
|
||
// 手动找最近的车(基于当前自动定位的位置)
|
||
function findNearestBikeManual() {
|
||
if (!autoLocationMarker) {
|
||
showToast("请先开启定位");
|
||
return;
|
||
}
|
||
|
||
const point = autoLocationMarker.getPosition();
|
||
findNearestBike(point);
|
||
}
|
||
|
||
// 显示我的位置(手动定位模式,带 panTo)
|
||
function showMyLocation(point) {
|
||
if (myLocationMarker) {
|
||
map.removeOverlay(myLocationMarker);
|
||
}
|
||
// 蓝色脉冲点
|
||
const size = 24;
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = size;
|
||
canvas.height = size;
|
||
const ctx = canvas.getContext("2d");
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2);
|
||
ctx.fillStyle = "#007AFF";
|
||
ctx.fill();
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, 6, 0, Math.PI * 2);
|
||
ctx.fillStyle = "white";
|
||
ctx.fill();
|
||
|
||
const icon = new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(size, size), new BMapGL.Size(size/2, size/2));
|
||
myLocationMarker = new BMapGL.Marker(point, { icon });
|
||
map.addOverlay(myLocationMarker);
|
||
map.panTo(point);
|
||
}
|
||
|
||
// 绘制自动定位标记(带外圈脉冲效果,灰色调)
|
||
function createAutoLocationIcon() {
|
||
const size = 28;
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = size;
|
||
canvas.height = size;
|
||
const ctx = canvas.getContext("2d");
|
||
|
||
// 外圈(浅蓝色,脉冲感)
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2);
|
||
ctx.strokeStyle = "rgba(0, 122, 255, 0.3)";
|
||
ctx.lineWidth = 3;
|
||
ctx.stroke();
|
||
|
||
// 中圈
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, 8, 0, Math.PI * 2);
|
||
ctx.strokeStyle = "rgba(0, 122, 255, 0.6)";
|
||
ctx.lineWidth = 2;
|
||
ctx.stroke();
|
||
|
||
// 中心点
|
||
ctx.beginPath();
|
||
ctx.arc(size/2, size/2, 4, 0, Math.PI * 2);
|
||
ctx.fillStyle = "#007AFF";
|
||
ctx.fill();
|
||
|
||
return canvas.toDataURL("image/png");
|
||
}
|
||
|
||
// 更新自动定位标记位置(不 panTo)
|
||
function updateAutoLocation(point) {
|
||
if (!autoLocationMarker) {
|
||
// 首次创建
|
||
const iconUrl = createAutoLocationIcon();
|
||
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||
autoLocationMarker = new BMapGL.Marker(point, { icon });
|
||
map.addOverlay(autoLocationMarker);
|
||
} else {
|
||
// 更新位置
|
||
autoLocationMarker.setPosition(point);
|
||
}
|
||
}
|
||
|
||
// 启动自动持续定位
|
||
function startAutoLocation() {
|
||
if (!navigator.geolocation) {
|
||
console.log("[自动定位] 浏览器不支持定位");
|
||
return;
|
||
}
|
||
|
||
// 如果已经在监听,先停止
|
||
if (autoLocationWatchId !== null) {
|
||
navigator.geolocation.clearWatch(autoLocationWatchId);
|
||
}
|
||
|
||
showToast("正在获取您的位置...");
|
||
autoLocationWatchId = navigator.geolocation.watchPosition(
|
||
(pos) => {
|
||
const gpsLat = pos.coords.latitude;
|
||
const gpsLng = pos.coords.longitude;
|
||
|
||
// GPS(WGS84) -> 百度 BD09,本地用 coordtransform 同步转换,
|
||
// 替代原 BMapGL.Convertor 在线接口(无网络/异步依赖)。
|
||
// coordtransform.wgs84tobd09(lng, lat) 返回 [bd09_lng, bd09_lat]
|
||
let myPoint = null;
|
||
if (typeof coordtransform !== "undefined" && coordtransform.wgs84tobd09) {
|
||
try {
|
||
const bd09 = coordtransform.wgs84tobd09(gpsLng, gpsLat);
|
||
myPoint = new BMapGL.Point(bd09[0], bd09[1]);
|
||
} catch (e) {
|
||
console.warn("[自动定位] 坐标转换失败,使用原始坐标:", e);
|
||
myPoint = null;
|
||
}
|
||
}
|
||
// 库未加载或转换失败时,直接使用原始坐标兜底
|
||
if (!myPoint) {
|
||
myPoint = new BMapGL.Point(gpsLng, gpsLat);
|
||
}
|
||
updateAutoLocation(myPoint);
|
||
hasLocationPermission = true;
|
||
|
||
// 用户授权定位时:本页首次拿到位置后,把地图居中到用户位置(仅一次)
|
||
if (!initialLocationCentered) {
|
||
initialLocationCentered = true;
|
||
if (map) {
|
||
map.setCenter(myPoint);
|
||
}
|
||
}
|
||
},
|
||
(err) => {
|
||
console.log("[自动定位] 定位失败:", err.message);
|
||
hasLocationPermission = false;
|
||
},
|
||
{ enableHighAccuracy: false, maximumAge: 5000, timeout: 10000 }
|
||
);
|
||
}
|
||
|
||
// 停止自动定位
|
||
function stopAutoLocation() {
|
||
if (autoLocationWatchId !== null) {
|
||
navigator.geolocation.clearWatch(autoLocationWatchId);
|
||
autoLocationWatchId = null;
|
||
}
|
||
if (autoLocationMarker) {
|
||
map.removeOverlay(autoLocationMarker);
|
||
autoLocationMarker = null;
|
||
}
|
||
}
|
||
|
||
// 计算距离并找最近可用车辆(智能电量匹配)
|
||
function findNearestBike(myPoint) {
|
||
// Haversine公式计算两点距离(米)
|
||
function calcDistance(lat1, lng1, lat2, lng2) {
|
||
const R = 6371000;
|
||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||
Math.sin(dLng/2) * Math.sin(dLng/2);
|
||
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
||
}
|
||
|
||
const myLat = myPoint.lat;
|
||
const myLng = myPoint.lng;
|
||
const NEARBY_THRESHOLD = 200; // 附近范围(米)
|
||
const LOW_BATTERY = 20; // 低电量阈值
|
||
|
||
// 收集所有可用车(电量>20%,非使用中)
|
||
const available = [];
|
||
for (const id in markersData) {
|
||
const bike = markersData[id];
|
||
if (!bike.latitude || !bike.longitude) continue;
|
||
// 只把「空闲可用」的车推荐给用户:分类规则与 getBikeState / 后端一致
|
||
// (使用中 state=1&status=1 / 低电量 state=10 或 电量<20 / 欠压 4 / 损坏 2)
|
||
const bs = getBikeState(bike);
|
||
if (bs !== 'available') continue;
|
||
const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0);
|
||
if (electric <= LOW_BATTERY) continue; // 过滤低电量
|
||
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const dist = calcDistance(myLat, myLng, c.lat, c.lng);
|
||
available.push({ id, bike, dist, electric });
|
||
}
|
||
|
||
// 过滤:只选电量 > 40% 的车
|
||
const enoughElec = available.filter(v => v.electric > 40);
|
||
|
||
if (enoughElec.length === 0) {
|
||
showToast("附近没有电量足够的车辆(需要>40%)");
|
||
return;
|
||
}
|
||
|
||
// 直接选距离最近的
|
||
enoughElec.sort((a, b) => a.dist - b.dist);
|
||
const selected = enoughElec[0];
|
||
const matchType = "最近可用";
|
||
|
||
|
||
nearestBikeId = selected.id;
|
||
const bike = selected.bike;
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
||
|
||
// 飞到这个车并放大一级
|
||
map.panTo(bikePoint);
|
||
setTimeout(() => {
|
||
map.setZoom(map.getZoom() + 1);
|
||
}, 300);
|
||
|
||
// 文案与 getBikeState 的分类一一对应(推荐出来的车一定是 available,正常走「空闲」)
|
||
const stateLabel = {
|
||
inuse: "使用中", available: "空闲", lowbattery: "低电量",
|
||
locked: "欠压车辆", reserved: "损坏车辆", unknown: "未知",
|
||
}[getBikeState(bike)] || "未知";
|
||
const distText = selected.dist < 1000 ? `${Math.round(selected.dist)}米` : `${(selected.dist/1000).toFixed(1)}公里`;
|
||
showToast(`${matchType}:#${bike.code}(${stateLabel} ${selected.electric}%),${distText}`);
|
||
|
||
setTimeout(() => showBikeDetail(selected.id), 500);
|
||
}
|
||
|
||
// ========== 启动 ==========
|
||
// 启动时检查登录状态,然后检查租车
|
||
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);
|
||
}
|
||
});
|
||
}
|
||
});
|
||
|
||
// ================= 版本号 & 更新说明 =================
|
||
const VERSION_TAG = "v1.6.0";
|
||
const VERSION_LOGS = [
|
||
{ 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() {
|
||
if (typeof SettingsPages !== "undefined" && SettingsPages.isOpen()) return;
|
||
let seen = "";
|
||
try { seen = localStorage.getItem("version_seen") || ""; } catch (e) {}
|
||
if (seen === VERSION_TAG) return;
|
||
const askM = document.getElementById("share-ask-modal");
|
||
const cfgM = document.getElementById("share-config-modal");
|
||
const busy = (askM && askM.classList.contains("show")) ||
|
||
(cfgM && cfgM.classList.contains("show"));
|
||
if (busy) {
|
||
versionAutoTries++;
|
||
if (versionAutoTries < 8) setTimeout(maybeAutoShowVersion, 4000);
|
||
return;
|
||
}
|
||
openVersionModal();
|
||
}
|
||
|
||
// ================= 共享电动车 =================
|
||
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 fetch(url, opts).then(r => r.json());
|
||
// 共享电动车已拆到 static/js/share.js
|
||
|
||
}
|
||
|
||
// ---------- 初始化(登录后/页面加载) ----------
|
||
function shareAfterLogin() {
|
||
refreshShareBanners();
|
||
setTimeout(() => checkPendingShareRequests(), 800);
|
||
}
|
||
document.addEventListener("DOMContentLoaded", () => {
|
||
if (authToken) shareAfterLogin();
|
||
setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000);
|
||
setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000);
|
||
// 版本更新说明不再自动弹(右下角版本徽标也已去掉);
|
||
// 需要看历史更新时可以从控制台 openVersionModal() 调出来
|
||
});
|
||
|
||
// 共享电动车已拆到 static/js/share.js
|