根因:_fitCardActions() 在 showBikeDetail 早期就被调用,而此时卡片还是隐藏的
(classList.add("show") 在更后面),clientWidth 为 0 → 量不出「是否被 ellipsis 截断」,
所以 compact-actions 没加上,按钮继续显示「导航/寻车」文字;等卡片上屏后没有再量一次。
因为是异步渲染 + 打开时机不同,表现就是"有时候正常、有时候不收"。
改法
- _fitCardActions 增加可见性判断:卡片不可见(offsetParent 为 null / clientWidth 为 0)
时用 requestAnimationFrame 重试最多 4 帧,仍不可见就交给观察者
- 卡片上屏后(classList.add("show") 之后)再量一次,并补一帧 rAF
- 新增 installCardFitObservers():ResizeObserver 监听 #bike-card 尺寸变化(60ms 防抖)
+ document.fonts.ready 后重量(字体回退会改变文字宽度),只安装一次
实测(390px)
- 长车牌 300001234567890123:compact-actions=true,按钮文字 display=none,图标保留
- 短车牌 51287:compact-actions=false,文字正常显示
- JS 异常 0
测试:169 pytest + 32 node 全绿
5949 lines
228 KiB
JavaScript
5949 lines
228 KiB
JavaScript
/*! 小白超人地图前端 bundle —— 由 src-ts/ 经 esbuild 打包(IIFE)。
|
||
* 源码:src-ts/** (逐块搬自 static/js/{map,navigation,share,subscribe}.js)
|
||
* 构建:node esbuild.config.mjs
|
||
* 回滚:把 templates/map.html 里的 app.js 换回原 static/js/map.js 等脚本即可。
|
||
*/
|
||
(() => {
|
||
// src-ts/core/geo.ts
|
||
var COORD_OFFSET = {
|
||
lat: 603e-5,
|
||
// 约 610 米(纬度)
|
||
lng: 65e-4
|
||
// 约 600 米 - 20 米(经度,往西 20 米)
|
||
};
|
||
function offsetCoord(lat, lng) {
|
||
lat = parseFloat(lat);
|
||
lng = parseFloat(lng);
|
||
if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) {
|
||
try {
|
||
const bd = coordtransform.gcj02tobd09(lng, lat);
|
||
return { lat: bd[1], lng: bd[0] };
|
||
} catch (e) {
|
||
console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e);
|
||
}
|
||
}
|
||
return {
|
||
lat: lat + COORD_OFFSET.lat,
|
||
lng: lng + COORD_OFFSET.lng
|
||
};
|
||
}
|
||
function calcDistance(lat1, lng1, lat2, lng2) {
|
||
const R = 6371e3;
|
||
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));
|
||
}
|
||
var Geo = { COORD_OFFSET, offsetCoord, calcDistance };
|
||
|
||
// src-ts/core/state.ts
|
||
var S = {
|
||
// static/js/share.js:208
|
||
shareAskQueue: [],
|
||
// static/js/share.js:209
|
||
shareAskActive: false,
|
||
// static/js/map.js:2
|
||
map: null,
|
||
// static/js/map.js:3
|
||
currentType: "3",
|
||
// static/js/map.js:4
|
||
currentUser: null,
|
||
// static/js/map.js:5
|
||
authKickToastShown: false,
|
||
// static/js/map.js:6
|
||
authMode: "login",
|
||
// static/js/map.js:7
|
||
authToken: localStorage.getItem("auth_token") || null,
|
||
// static/js/map.js:8
|
||
currentMarkers: [],
|
||
// static/js/map.js:9
|
||
currentPolygons: [],
|
||
// static/js/map.js:10
|
||
selectedBike: null,
|
||
// static/js/map.js:11
|
||
markersData: {},
|
||
// static/js/map.js:12
|
||
currentMarkersById: {},
|
||
// static/js/map.js:13
|
||
scannedMarkers: {},
|
||
// static/js/map.js:14
|
||
myLocationMarker: null,
|
||
// static/js/map.js:15
|
||
autoLocationMarker: null,
|
||
// static/js/map.js:16
|
||
autoLocationWatchId: null,
|
||
// static/js/map.js:17
|
||
hasLocationPermission: false,
|
||
// static/js/map.js:18
|
||
initialLocationCentered: false,
|
||
// static/js/map.js:19
|
||
nearestBikeId: null,
|
||
// static/js/map.js:20
|
||
isFirstLoad: true,
|
||
// static/js/map.js:21
|
||
highlightedBikeId: null,
|
||
// static/js/map.js:23
|
||
bikeClusteringEnabled: typeof BikeClusters !== "undefined" ? BikeClusters.readClusteringPreference(localStorage) : true,
|
||
// static/js/map.js:122
|
||
activeRental: null,
|
||
// static/js/map.js:123
|
||
rentalCountdownTimer: null,
|
||
// static/js/map.js:1658
|
||
currentOrder: null,
|
||
// static/js/map.js:3276
|
||
_fitCardTimer: null,
|
||
// static/js/map.js:3582
|
||
_findClickCount: 0,
|
||
// static/js/map.js:3584
|
||
_findLongPressTimer: null
|
||
};
|
||
var RENTAL_KEY = "xbniu_rental_key";
|
||
|
||
// src-ts/map/icons.ts
|
||
var iconCache = /* @__PURE__ */ new Map();
|
||
var ICON_CACHE_MAX = 500;
|
||
var BASE_ICON_COLORS = {
|
||
available: "#34C759",
|
||
// 绿色-可用
|
||
inuse: "#FF2D55",
|
||
// 红色-使用中
|
||
locked: "#FF9F0A",
|
||
// 橙色-欠压
|
||
reserved: "#5856D6",
|
||
// 紫色-损坏
|
||
lowbattery: "#8E8E93"
|
||
// 灰色-低电量
|
||
};
|
||
var prebuiltIcons = /* @__PURE__ */ new Map();
|
||
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;
|
||
const electricLevels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
|
||
Object.values(BASE_ICON_COLORS).forEach((color) => {
|
||
electricLevels.forEach((electric) => {
|
||
const key = `${electric}|${color}`;
|
||
if (!prebuiltIcons.has(key)) {
|
||
const dataUrl = createFullIcon(imageSize, color, electric, false, null);
|
||
prebuiltIcons.set(key, dataUrl);
|
||
}
|
||
});
|
||
});
|
||
console.log("[预创建] 已预创建 " + prebuiltIcons.size + " 个图标");
|
||
}
|
||
function getBikeState(bike) {
|
||
var _a, _b;
|
||
const state = bike.state;
|
||
const status = bike.status;
|
||
const electric = Number((_b = (_a = bike.electric_quantity) != null ? _a : bike.electricQuantity) != null ? _b : 100);
|
||
if (state === 1 && status === 1) return "inuse";
|
||
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 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");
|
||
}
|
||
var 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 };
|
||
}
|
||
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) {
|
||
var _a, _b;
|
||
const electric = Number((_b = (_a = bike.electric_quantity) != null ? _a : bike.electricQuantity) != null ? _b : 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";
|
||
}
|
||
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)) {
|
||
const dataUrl2 = prebuiltIcons.get(prebuiltKey);
|
||
const icon2 = new BMapGL.Icon(
|
||
dataUrl2,
|
||
new BMapGL.Size(displaySize, displaySize),
|
||
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||
);
|
||
icon2.__xbniuAppearance = { url: dataUrl2, size: displaySize };
|
||
iconCache.set(cacheKey, icon2);
|
||
return icon2;
|
||
}
|
||
}
|
||
const imageSize = renderSize * 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;
|
||
}
|
||
|
||
// src-ts/core/format.ts
|
||
function fmtLocalTime(ts) {
|
||
const d = new Date(ts * 1e3);
|
||
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() / 1e3);
|
||
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 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 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 fmtDuration(seconds) {
|
||
if (seconds === null || seconds === void 0) 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);
|
||
}
|
||
function fmtClock(s) {
|
||
if (!s) return "--";
|
||
return String(s).slice(11, 16);
|
||
}
|
||
function friendlyError(e) {
|
||
const msg = e && e.message || "";
|
||
if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) {
|
||
return "服务响应异常,请稍后重试";
|
||
}
|
||
return msg || "网络错误,请重试";
|
||
}
|
||
|
||
// src-ts/nav/walk-route.ts
|
||
var _walkRouteCache = /* @__PURE__ */ new Map();
|
||
var MAX_WALK_DISTANCE_M = 2e4;
|
||
function parseWalkDistance(text) {
|
||
const s = String(text || "");
|
||
const km = s.match(/([\d.]+)\s*公里/);
|
||
if (km) return Math.round(parseFloat(km[1]) * 1e3);
|
||
const m = s.match(/([\d.]+)\s*米/);
|
||
return m ? Math.round(parseFloat(m[1])) : 0;
|
||
}
|
||
function parseWalkDuration(text) {
|
||
const s = String(text || "");
|
||
let sec = 0;
|
||
const h = s.match(/([\d.]+)\s*小时/);
|
||
const min = s.match(/([\d.]+)\s*分钟/);
|
||
if (h) sec += Math.round(parseFloat(h[1]) * 3600);
|
||
if (min) sec += Math.round(parseFloat(min[1]) * 60);
|
||
return sec;
|
||
}
|
||
async function refineWalkRoute(bike) {
|
||
const bikeCode = String(bike && bike.code || "");
|
||
if (!bikeCode) return;
|
||
const me = typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||
if (!me || !bike.latitude || !bike.longitude) return;
|
||
const c0 = offsetCoord(bike.latitude, bike.longitude);
|
||
if (calcDistance(me.lat, me.lng, c0.lat, c0.lng) > MAX_WALK_DISTANCE_M) return;
|
||
const key = bikeCode + "|" + me.lat.toFixed(4) + "," + me.lng.toFixed(4);
|
||
const apply = (distanceM, seconds) => {
|
||
if (!S.selectedBike || String(S.selectedBike.code) !== bikeCode) return;
|
||
const distEl = document.getElementById("card-distance");
|
||
const walkEl = document.getElementById("card-walk");
|
||
const metaLeft = document.getElementById("card-meta-left");
|
||
if (!distEl || !walkEl || !metaLeft) return;
|
||
distEl.textContent = distanceM < 1e3 ? `步行 ${Math.round(distanceM)} 米` : `步行 ${(distanceM / 1e3).toFixed(1)} 公里`;
|
||
walkEl.textContent = `约 ${Math.max(1, Math.round(seconds / 60))} 分钟`;
|
||
metaLeft.hidden = false;
|
||
};
|
||
const cached = _walkRouteCache.get(key);
|
||
if (cached) {
|
||
apply(cached.d, cached.t);
|
||
return;
|
||
}
|
||
try {
|
||
const gcj = typeof coordtransform !== "undefined" && coordtransform.bd09togcj02 ? coordtransform.bd09togcj02(me.lng, me.lat) : null;
|
||
if (gcj) {
|
||
const url = "/api/walk_route?origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0] + "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude;
|
||
const resp = await fetch(url, {
|
||
headers: { "Authorization": "Bearer " + S.authToken }
|
||
});
|
||
const data = await resp.json();
|
||
const d = data && data.data;
|
||
if (data.rtn_code === 0 && d && d.distance > 0 && d.duration > 0 && (d.source === "baidu" || d.source === "cache")) {
|
||
_walkRouteCache.set(key, { d: d.distance, t: d.duration });
|
||
apply(d.distance, d.duration);
|
||
return;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
}
|
||
try {
|
||
if (typeof BMapGL !== "undefined" && BMapGL.WalkingRoute && S.map) {
|
||
const plan = await new Promise((resolve) => {
|
||
let done = false;
|
||
const finish = (v) => {
|
||
if (!done) {
|
||
done = true;
|
||
resolve(v);
|
||
}
|
||
};
|
||
const walk = new BMapGL.WalkingRoute(S.map, {
|
||
renderOptions: { map: null, panel: null },
|
||
onSearchComplete: (res) => {
|
||
let status = -1;
|
||
try {
|
||
status = res && typeof res.getStatus === "function" ? res.getStatus() : -1;
|
||
} catch (e) {
|
||
status = -1;
|
||
}
|
||
if (status !== 0) return finish(null);
|
||
try {
|
||
const p = res.getPlan(0);
|
||
const d = parseWalkDistance(p.getDistance());
|
||
const t = parseWalkDuration(p.getDuration());
|
||
finish(d > 0 && t > 0 ? { d, t } : null);
|
||
} catch (err) {
|
||
finish(null);
|
||
}
|
||
}
|
||
});
|
||
walk.search(me, new BMapGL.Point(bike.longitude, bike.latitude));
|
||
setTimeout(() => finish(null), 8e3);
|
||
});
|
||
if (plan) {
|
||
_walkRouteCache.set(key, plan);
|
||
apply(plan.d, plan.t);
|
||
}
|
||
}
|
||
} catch (e) {
|
||
}
|
||
}
|
||
|
||
// src-ts/core/http.ts
|
||
function shareApi(url, method, body) {
|
||
const opts = { method: method || "GET", headers: {} };
|
||
if (S.authToken) opts.headers["Authorization"] = `Bearer ${S.authToken}`;
|
||
if (body !== void 0) {
|
||
opts.headers["Content-Type"] = "application/json";
|
||
opts.body = JSON.stringify(body);
|
||
}
|
||
return fetch(url, opts).then((r) => r.json());
|
||
}
|
||
|
||
// src-ts/share/share.ts
|
||
function partnerLabel(name, email, remark) {
|
||
return remark && String(remark).trim() || name || email || "";
|
||
}
|
||
var shareRec = {};
|
||
var shareTabNow = "usable";
|
||
function openShareModal() {
|
||
if (!S.authToken || !S.currentUser) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
SettingsPages.open("share-modal");
|
||
switchShareTab(shareTabNow);
|
||
}
|
||
function closeShareModal() {
|
||
SettingsPages.back();
|
||
}
|
||
function switchShareTab(tab) {
|
||
shareTabNow = tab;
|
||
document.getElementById("share-tab-usable").classList.toggle("active", tab === "usable");
|
||
document.getElementById("share-tab-mine").classList.toggle("active", tab === "mine");
|
||
document.getElementById("share-list-usable").style.display = tab === "usable" ? "flex" : "none";
|
||
document.getElementById("share-list-mine").style.display = tab === "mine" ? "flex" : "none";
|
||
loadShareData();
|
||
}
|
||
function sharePendingHtml(pending) {
|
||
if (!pending || !pending.length) {
|
||
document.getElementById("share-pending-box").style.display = "none";
|
||
return;
|
||
}
|
||
const rows = pending.map((p) => `<div class="prow"><span>等待接受:<b>${escHtml(p.from_email || "")}</b></span>
|
||
<span style="display:flex;gap:6px;flex-shrink:0">
|
||
<button class="share-mini-btn danger" onclick="rejectShareRequest(${p.id})">拒绝</button>
|
||
<button class="share-mini-btn primary" onclick="acceptShareRequest(${p.id}, '${(p.from_email || "").replace(/'/g, "")}')">接受</button>
|
||
</span></div>`).join("");
|
||
const box = document.getElementById("share-pending-box");
|
||
box.innerHTML = `<div style="font-weight:600;margin-bottom:2px;">待处理的共享申请</div>${rows}`;
|
||
box.style.display = "block";
|
||
}
|
||
async function loadShareData() {
|
||
if (!S.authToken) return;
|
||
try {
|
||
const data = await shareApi("/api/share/list");
|
||
if (data.rtn_code !== 0) {
|
||
showToast(data.message || "加载失败");
|
||
return;
|
||
}
|
||
const d = data.data || { usable: [], shared: [] };
|
||
shareRec = {};
|
||
document.getElementById("share-list-usable").innerHTML = d.usable.map((u) => {
|
||
const uLabel = partnerLabel(u.owner_name, u.owner_email, u.remark);
|
||
shareRec[u.share_id] = { email: u.owner_email || "", name: u.owner_name || "", remark: u.remark || "" };
|
||
const state = u.can_use ? '<div class="share-row-state ok">今日可用 ' + u.remaining_today + "/" + u.daily_limit + " 次 · 对方需有优惠卡" + (u.require_card ? "是" : "否") + "</div>" : '<div class="share-row-state err">不可用:' + (u.reasons && u.reasons.length ? u.reasons.join(";") : "今日次数已用完") + "</div>";
|
||
return '<div class="share-row"><div class="share-row-top"><span class="share-row-email">' + escHtml(uLabel) + "</span></div>" + state + '<div class="share-row-btns"><button class="share-mini-btn primary" onclick="openShareRemark(' + u.share_id + ')">备注</button><button class="share-mini-btn danger" onclick="unbindShare(' + u.share_id + ')">解绑</button></div></div>';
|
||
}).join("");
|
||
document.getElementById("share-list-mine").innerHTML = d.shared.map((sr) => {
|
||
const sLabel = partnerLabel(sr.rider_name, sr.rider_email, sr.remark);
|
||
shareRec[sr.share_id] = { email: sr.rider_email || "", name: sr.rider_name || "", remark: sr.remark || "" };
|
||
return '<div class="share-row"><div class="share-row-top"><span class="share-row-email">' + escHtml(sLabel) + '</span><span style="font-size:12px;color:var(--text-secondary);flex-shrink:0;">今日已用 ' + sr.rider_used_today + "/" + sr.daily_limit + '</span></div><div class="share-row-state">每天 ' + sr.daily_limit + " 次" + (sr.require_card ? " · 需我有优惠卡且剩余 ≥ " + sr.card_min_times : " · 无卡要求") + '</div><div class="share-row-btns"><button class="share-mini-btn primary" onclick="openShareRemark(' + sr.share_id + ')">备注</button><button class="share-mini-btn primary" onclick="openShareConfig(' + sr.share_id + ", " + sr.daily_limit + ", " + (sr.require_card ? 1 : 0) + ", " + sr.card_min_times + ", '" + String(sr.rider_email || "").replace(/'/g, "") + `')">修改权限</button><button class="share-mini-btn danger" onclick="unbindShare(` + sr.share_id + ')">解绑</button></div></div>';
|
||
}).join("");
|
||
const pending = await shareApi("/api/share/pending");
|
||
if (pending.rtn_code === 0) sharePendingHtml(pending.data || []);
|
||
} catch (e) {
|
||
console.error("[share] load失败", e);
|
||
}
|
||
}
|
||
async function sendShareRequest() {
|
||
if (!S.authToken) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
const email = document.getElementById("share-req-email").value.trim();
|
||
if (!email) {
|
||
showToast("请输入对方邮箱");
|
||
return;
|
||
}
|
||
const btn = document.querySelector(".share-req-row button");
|
||
if (btn) {
|
||
btn.disabled = true;
|
||
}
|
||
try {
|
||
const data = await shareApi("/api/share/request", "POST", { to_email: email });
|
||
showToast(data.message || (data.rtn_code === 0 ? "已发送" : "发送失败"));
|
||
if (data.rtn_code === 0) document.getElementById("share-req-email").value = "";
|
||
} finally {
|
||
if (btn) {
|
||
btn.disabled = false;
|
||
}
|
||
}
|
||
}
|
||
async function acceptShareRequest(reqId, fromEmail) {
|
||
const askM = document.getElementById("share-ask-modal");
|
||
if (askM) askM.classList.remove("show");
|
||
S.shareAskActive = false;
|
||
try {
|
||
const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: true });
|
||
if (data.rtn_code === 0 && data.data) {
|
||
showToast("已接受,请设置权限");
|
||
openShareConfig(data.data.share_id, data.data.daily_limit, data.data.require_card, data.data.card_min_times, data.data.rider_email);
|
||
} else {
|
||
showToast(data.message || "操作失败");
|
||
}
|
||
} finally {
|
||
loadShareData();
|
||
checkPendingShareRequests();
|
||
}
|
||
}
|
||
async function rejectShareRequest(reqId) {
|
||
const askM = document.getElementById("share-ask-modal");
|
||
if (askM) askM.classList.remove("show");
|
||
S.shareAskActive = false;
|
||
try {
|
||
const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: false });
|
||
showToast(data.message || "已拒绝");
|
||
} finally {
|
||
loadShareData();
|
||
checkPendingShareRequests();
|
||
}
|
||
}
|
||
var shareCfg = { share_id: null };
|
||
function openShareConfig(shareId, daily, requireCard, minTimes, email) {
|
||
shareCfg = { share_id: shareId };
|
||
document.getElementById("share-config-title").textContent = email ? `为 ${email} 设置共享权限` : "";
|
||
document.getElementById("sharecfg-daily").value = daily != null ? daily : 3;
|
||
document.getElementById("sharecfg-card").checked = !!requireCard;
|
||
document.getElementById("sharecfg-mintimes").value = minTimes != null ? minTimes : 0;
|
||
SettingsPages.open("share-config-modal");
|
||
}
|
||
function closeShareConfig() {
|
||
SettingsPages.back();
|
||
setTimeout(() => checkPendingShareRequests(), 0);
|
||
}
|
||
async function saveShareConfig() {
|
||
if (!shareCfg.share_id) return;
|
||
const daily = parseInt(document.getElementById("sharecfg-daily").value, 10) || 0;
|
||
const require_card = document.getElementById("sharecfg-card").checked ? 1 : 0;
|
||
const minTimes = parseInt(document.getElementById("sharecfg-mintimes").value, 10) || 0;
|
||
const data = await shareApi("/api/share/config", "POST", {
|
||
share_id: shareCfg.share_id,
|
||
daily_limit: daily,
|
||
require_card,
|
||
card_min_times: minTimes
|
||
});
|
||
showToast(data.message || (data.rtn_code === 0 ? "权限已保存" : "保存失败"));
|
||
if (data.rtn_code === 0) closeShareConfig();
|
||
loadShareData();
|
||
checkPendingShareRequests();
|
||
}
|
||
async function unbindShare(shareId) {
|
||
if (!await appConfirm("解绑后对方将无法再用你的共享额度开锁,可随时重新申请。", { title: "解绑共享关系", okText: "解绑", danger: true })) return;
|
||
const data = await shareApi("/api/share/unbind", "POST", { share_id: shareId });
|
||
showToast(data.message || "已解绑");
|
||
loadShareData();
|
||
refreshShareBanners();
|
||
}
|
||
var shareRemarkCfg = { share_id: null };
|
||
function openShareRemark(shareId) {
|
||
const rec = shareRec[shareId];
|
||
if (!rec) return;
|
||
shareRemarkCfg.share_id = shareId;
|
||
document.getElementById("share-remark-input").value = rec.remark || "";
|
||
const shown = partnerLabel(rec.name, rec.email, rec.remark);
|
||
document.getElementById("share-remark-desc").innerHTML = "给 <b>" + escHtml(shown) + "</b> 起一个昵称备注,仅自己可见;未设置时对 TA 的显示退回邮箱 (<b>" + escHtml(rec.email || "") + "</b>)。";
|
||
SettingsPages.open("share-remark-modal");
|
||
}
|
||
function closeShareRemark() {
|
||
SettingsPages.back();
|
||
shareRemarkCfg.share_id = null;
|
||
}
|
||
async function saveShareRemark() {
|
||
if (!shareRemarkCfg.share_id) return;
|
||
const remark = document.getElementById("share-remark-input").value.trim();
|
||
const btn = document.querySelector("#share-remark-modal .auth-submit");
|
||
if (btn) btn.disabled = true;
|
||
try {
|
||
const data = await shareApi("/api/share/remark", "POST", { share_id: shareRemarkCfg.share_id, remark });
|
||
showToast(data.message || (data.rtn_code === 0 ? "备注已保存" : "保存失败"));
|
||
if (data.rtn_code === 0) closeShareRemark();
|
||
loadShareData();
|
||
refreshShareBanners();
|
||
} catch (e) {
|
||
console.error("[share] remark失败", e);
|
||
showToast("保存失败");
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
var shareAskCur = null;
|
||
async function checkPendingShareRequests() {
|
||
if (!S.authToken || S.shareAskActive) return;
|
||
try {
|
||
const data = await shareApi("/api/share/pending");
|
||
if (data.rtn_code === 0 && data.data && data.data.length) {
|
||
S.shareAskQueue = data.data.slice();
|
||
nextShareAskIfQueue();
|
||
}
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function nextShareAskIfQueue() {
|
||
if (S.shareAskQueue.length > 0) {
|
||
shareAskCur = S.shareAskQueue.shift();
|
||
S.shareAskActive = true;
|
||
document.getElementById("share-ask-from").textContent = shareAskCur.from_email || "";
|
||
document.getElementById("share-ask-modal").classList.add("show");
|
||
} else if (S.shareAskActive) {
|
||
S.shareAskActive = false;
|
||
document.getElementById("share-ask-modal").classList.remove("show");
|
||
}
|
||
}
|
||
async function acceptCurrentShareAsk() {
|
||
if (!shareAskCur) return;
|
||
await acceptShareRequest(shareAskCur.id, shareAskCur.from_email);
|
||
}
|
||
async function rejectCurrentShareAsk() {
|
||
if (!shareAskCur) return;
|
||
await rejectShareRequest(shareAskCur.id);
|
||
}
|
||
var shareActiveList = [];
|
||
var pendingShareReturn = null;
|
||
async function refreshShareBanners() {
|
||
const cont = document.getElementById("share-banners");
|
||
if (!cont) return;
|
||
if (!S.authToken || !S.currentUser) {
|
||
cont.innerHTML = "";
|
||
return;
|
||
}
|
||
try {
|
||
const data = await shareApi("/api/share/active");
|
||
if (data.rtn_code !== 0) return;
|
||
shareActiveList = Array.isArray(data.data) ? data.data : [];
|
||
shareActiveList.forEach((it) => {
|
||
it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1e3;
|
||
});
|
||
let html = "";
|
||
shareActiveList.forEach((it, idx) => {
|
||
const isOwner = it.role === "owner";
|
||
const label = partnerLabel(it.partner_name, it.partner_email, it.remark);
|
||
const esc = escHtml(label);
|
||
const bike = escHtml(it.bike_code || "");
|
||
let text;
|
||
if (isOwner) {
|
||
text = '<span>共享中</span><b style="margin:0 4px;">#' + bike + '</b><span style="opacity:.85;">' + esc + " 使用中</span>";
|
||
} else {
|
||
text = "<span>使用 " + esc + ' 的车中</span><b style="margin:0 4px;">#' + bike + "</b>";
|
||
}
|
||
html += '<div class="share-banner show ' + (isOwner ? "" : "rider") + '"><div class="share-banner-copy"><div class="share-banner-title">' + text + '</div><div class="banner-progress"><span id="share-countdown-' + idx + '">本轮剩余 ' + remainingTimeText(it.remaining_seconds) + "</span><span>" + escHtml(rideProgressText(it)) + '</span></div></div><button class="share-banner-btn" onclick="openShareReturnByIdx(' + idx + ')">还车</button></div>';
|
||
});
|
||
if (cont.__lastHtml !== html) {
|
||
cont.innerHTML = html;
|
||
cont.__lastHtml = html;
|
||
}
|
||
} catch (e) {
|
||
console.error("[share] banners失败", e);
|
||
}
|
||
}
|
||
function openShareReturnByIdx(idx) {
|
||
const it = shareActiveList[idx];
|
||
if (!it) return;
|
||
pendingShareReturn = it;
|
||
const isOwner = it.role === "owner";
|
||
const label = partnerLabel(it.partner_name, it.partner_email, it.remark);
|
||
const esc = escHtml(label);
|
||
const bike = escHtml(it.bike_code || "");
|
||
const box = document.getElementById("share-return-text");
|
||
box.innerHTML = isOwner ? "你的共享电动车 <b>#" + bike + "</b> 正被 " + esc + " 使用,确认替他/她还车?" : "你正在使用 <b>" + esc + "</b> 的车 <b>#" + bike + "</b>,确认还车?";
|
||
document.getElementById("share-return-modal").classList.add("show");
|
||
}
|
||
function updateShareCountdowns() {
|
||
if (!Array.isArray(shareActiveList)) return;
|
||
shareActiveList.forEach((it, idx) => {
|
||
const el = document.getElementById("share-countdown-" + idx);
|
||
if (!el) return;
|
||
const seconds = Math.max(0, Math.ceil((it._countdownDeadline - performance.now()) / 1e3));
|
||
el.textContent = seconds > 0 ? "本轮剩余 " + remainingTimeText(seconds) : "本轮到期 · 同步状态中";
|
||
});
|
||
}
|
||
function closeShareReturnModal() {
|
||
const modal = document.getElementById("share-return-modal");
|
||
if (modal) modal.classList.remove("show");
|
||
pendingShareReturn = null;
|
||
}
|
||
async function confirmShareReturn() {
|
||
var _a, _b;
|
||
if (!pendingShareReturn) return;
|
||
const it = pendingShareReturn;
|
||
const btn = document.querySelector("#share-return-modal .auth-submit");
|
||
if (btn) {
|
||
btn.disabled = true;
|
||
btn.textContent = "还车中...";
|
||
}
|
||
try {
|
||
let position = null;
|
||
if (navigator.geolocation) {
|
||
position = await new Promise((resolve) => {
|
||
navigator.geolocation.getCurrentPosition(
|
||
(pos) => resolve(pos),
|
||
() => resolve(null),
|
||
{ timeout: 5e3 }
|
||
);
|
||
});
|
||
}
|
||
const latitude = ((_a = position == null ? void 0 : position.coords) == null ? void 0 : _a.latitude) || 36.67;
|
||
const longitude = ((_b = position == null ? void 0 : position.coords) == null ? void 0 : _b.longitude) || 116.98;
|
||
const data = await shareApi("/api/share/return", "POST", {
|
||
order_id: it.order_id,
|
||
latitude,
|
||
longitude
|
||
});
|
||
showToast(data.message || (data.rtn_code === 0 ? "还车成功" : "还车失败"));
|
||
if (data.rtn_code === 0) {
|
||
closeShareReturnModal();
|
||
pendingShareReturn = null;
|
||
await Promise.all([refreshShareBanners(), checkOrderStatus(), refreshMap()]);
|
||
}
|
||
} catch (e) {
|
||
showToast("还车失败,请重试");
|
||
} finally {
|
||
if (btn) {
|
||
btn.disabled = false;
|
||
btn.textContent = "确认还车";
|
||
}
|
||
}
|
||
}
|
||
|
||
// src-ts/order/status.ts
|
||
async function checkOrderStatus() {
|
||
if (!S.authToken) {
|
||
hideOrderBanner();
|
||
return;
|
||
}
|
||
try {
|
||
const resp = await fetch("/api/order/status", {
|
||
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) {
|
||
if (!data.has_credentials) {
|
||
hideOrderBanner();
|
||
return;
|
||
}
|
||
if (data.has_order && data.order) {
|
||
S.currentOrder = data.order;
|
||
if (data.order.shared) {
|
||
hideOrderBanner();
|
||
} else {
|
||
showOrderBanner(data.order);
|
||
}
|
||
} else {
|
||
S.currentOrder = null;
|
||
hideOrderBanner();
|
||
}
|
||
} else if (data.rtn_code === 102001 || data.token_invalid) {
|
||
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");
|
||
}
|
||
var orderCountdownTimer = null;
|
||
var orderCountdownSeconds = 0;
|
||
var orderCountdownDeadline = null;
|
||
var orderCountdownOrderId = null;
|
||
function fetchOrderCountdown(orderId) {
|
||
if (!S.authToken || !orderId) return;
|
||
fetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, {
|
||
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||
}).then((r) => r.json()).then((data) => {
|
||
if (!S.currentOrder || String(S.currentOrder.order_id) !== String(orderId) || Number(S.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 * 1e3;
|
||
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) {
|
||
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;
|
||
}
|
||
}
|
||
var _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 < 25e3) return;
|
||
_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()) / 1e3));
|
||
updateOrderCountdownText();
|
||
if (orderCountdownSeconds <= 0) {
|
||
clearInterval(orderCountdownTimer);
|
||
checkOrderStatus();
|
||
}
|
||
}, 1e3);
|
||
}
|
||
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(S.currentOrder)) return;
|
||
showOrderActionsModal();
|
||
}
|
||
function showOrderActionsModal() {
|
||
if (!isOrderActionEligible(S.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 = S.currentOrder.code || S.currentOrder.order_id || "未知";
|
||
const pending = Number(S.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(() => {
|
||
var _a;
|
||
return (_a = document.getElementById("order-actions-close")) == null ? void 0 : _a.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");
|
||
}
|
||
async function findCurrentOrderBike() {
|
||
if (!isOrderActionEligible(S.currentOrder)) return;
|
||
const code = (S.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 (!S.currentOrder) {
|
||
showToast("订单状态已变化,正在刷新,请稍后重试");
|
||
checkOrderStatus();
|
||
return;
|
||
}
|
||
if (Number(S.currentOrder.status) === 1) {
|
||
tryCardPayOrRedirect();
|
||
} else if (Number(S.currentOrder.status) === 2) {
|
||
showReturnConfirm();
|
||
} else {
|
||
showToast("订单状态已变化,正在刷新,请稍后重试");
|
||
checkOrderStatus();
|
||
}
|
||
}
|
||
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>` : "";
|
||
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>`;
|
||
}
|
||
|
||
// src-ts/ui/settings.ts
|
||
function handleAuthBtnClick() {
|
||
if (S.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 = S.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;
|
||
}
|
||
S.bikeClusteringEnabled = !!enabled;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(S.bikeClusteringEnabled);
|
||
const saved = BikeClusters.writeClusteringPreference(localStorage, S.bikeClusteringEnabled);
|
||
document.getElementById("settings-save-status").textContent = saved ? S.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();
|
||
}
|
||
async function loadProfileData() {
|
||
if (!S.authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${S.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);
|
||
_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 (!S.authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/user_info", {
|
||
headers: { "Authorization": `Bearer ${S.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);
|
||
}
|
||
}
|
||
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;
|
||
if (!exp) return null;
|
||
return { expireAt: exp, source: payload.exp ? "exp" : "iat+30d" };
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
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";
|
||
} else if (remain <= 604800) {
|
||
color = "#e67e22";
|
||
bg = "#fdf3e7";
|
||
}
|
||
el.style.display = "block";
|
||
el.style.color = color;
|
||
el.style.background = bg;
|
||
el.textContent = text;
|
||
}
|
||
function updateTokenExpiryDisplays() {
|
||
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();
|
||
}
|
||
var _savedTokenExpiry = null;
|
||
var AUTH_EXPIRY_BANNER_THRESHOLD = 2 * 86400;
|
||
var AUTH_EXPIRY_BANNER_URGENT = 86400;
|
||
function renderAuthExpiryBanner() {
|
||
const banner = document.getElementById("auth-expiry-banner");
|
||
if (!banner) return;
|
||
const text = document.getElementById("auth-expiry-banner-text");
|
||
if (!S.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");
|
||
}
|
||
async function refreshAuthExpiry() {
|
||
if (!S.authToken) {
|
||
_savedTokenExpiry = null;
|
||
renderAuthExpiryBanner();
|
||
return;
|
||
}
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${S.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();
|
||
}
|
||
function openAuthModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("auth-modal");
|
||
fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${S.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();
|
||
}
|
||
var _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 (!S.authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${S.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 || "";
|
||
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 openDevicesModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("devices-modal");
|
||
loadDevicesList();
|
||
}
|
||
function closeDevicesModal() {
|
||
SettingsPages.back();
|
||
}
|
||
async function loadDevicesList() {
|
||
const box = document.getElementById("devices-list");
|
||
if (!S.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 ${S.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 ${S.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 ${S.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 (!S.authToken) {
|
||
document.getElementById("packages-list-2").innerHTML = '<div class="packages-empty">请先登录</div>';
|
||
return;
|
||
}
|
||
try {
|
||
const resp = await fetch("/api/auth/packages", {
|
||
headers: { "Authorization": `Bearer ${S.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) => {
|
||
var _a;
|
||
return `
|
||
<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">剩余 ${(_a = pkg.remainTimes) != null ? _a : "∞"} 次</div>
|
||
</div>
|
||
`;
|
||
}).join("");
|
||
} catch (err) {
|
||
console.error("加载卡包失败:", err);
|
||
document.getElementById("packages-list-2").innerHTML = '<div class="packages-empty">加载失败</div>';
|
||
}
|
||
}
|
||
async function saveProfileToken() {
|
||
if (!S.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;
|
||
}
|
||
try {
|
||
const verifyResp = await fetch("/api/auth/verify_token", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${S.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 ${S.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 ${S.authToken}`
|
||
},
|
||
body: JSON.stringify({ email: alert_email })
|
||
}).catch(() => {
|
||
});
|
||
}
|
||
showToast("保存成功");
|
||
closeAuthModal();
|
||
loadProfileData();
|
||
refreshAuthExpiry();
|
||
} else {
|
||
showToast(data.message || "保存失败");
|
||
}
|
||
} catch (err) {
|
||
showToast("保存失败");
|
||
}
|
||
}
|
||
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) {
|
||
S.authToken = data.data.token;
|
||
localStorage.setItem("auth_token", S.authToken);
|
||
S.currentUser = { email: data.data.email };
|
||
S.authKickToastShown = false;
|
||
updateAuthButton();
|
||
hideLoginGate();
|
||
closeLoginModal();
|
||
showToast("登录成功");
|
||
shareAfterLogin();
|
||
checkOrderStatus();
|
||
checkRentalStatus();
|
||
refreshAuthExpiry();
|
||
if (S.map) loadMapData(S.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']")
|
||
);
|
||
}
|
||
var registerCodeCountdown = 0;
|
||
var 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);
|
||
}
|
||
}, 1e3);
|
||
} 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 = "注册中...";
|
||
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) {
|
||
S.authToken = data.data.token;
|
||
localStorage.setItem("auth_token", S.authToken);
|
||
S.currentUser = { email: data.data.email };
|
||
S.authKickToastShown = false;
|
||
updateAuthButton();
|
||
closeRegisterModal();
|
||
hideLoginGate();
|
||
showToast("注册成功");
|
||
shareAfterLogin();
|
||
refreshAuthExpiry();
|
||
if (S.map) loadMapData(S.currentType, false);
|
||
} else {
|
||
tip.textContent = data.message || "注册失败";
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
} finally {
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = "注册";
|
||
}
|
||
}
|
||
async function handleLogout() {
|
||
clearTimeout(mapRefreshTimer);
|
||
if (S.authToken) {
|
||
try {
|
||
await fetch("/api/auth/logout", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||
});
|
||
} catch (err) {
|
||
}
|
||
}
|
||
S.authToken = null;
|
||
S.currentUser = null;
|
||
localStorage.removeItem("auth_token");
|
||
S.authKickToastShown = false;
|
||
_savedTokenExpiry = null;
|
||
renderAuthExpiryBanner();
|
||
updateAuthButton();
|
||
closeProfileModal();
|
||
showToast("已登出");
|
||
showLoginGate();
|
||
const sb = document.getElementById("share-banners");
|
||
if (sb) sb.innerHTML = "";
|
||
S.shareAskQueue = [];
|
||
S.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 (S.currentUser) {
|
||
btn.classList.add("logged-in");
|
||
btnText.style.display = "none";
|
||
avatar.style.display = "flex";
|
||
avatar.textContent = S.currentUser.email.charAt(0).toUpperCase();
|
||
} else {
|
||
btn.classList.remove("logged-in");
|
||
btnText.style.display = "inline";
|
||
avatar.style.display = "none";
|
||
btnText.textContent = "登录";
|
||
}
|
||
updateBellBtnVisibility();
|
||
}
|
||
var BATCH_RING_ALLOWED_EMAILS = ["3146527494@qq.com"];
|
||
function canUseBatchRing() {
|
||
return !!(S.currentUser && BATCH_RING_ALLOWED_EMAILS.includes((S.currentUser.email || "").toLowerCase()));
|
||
}
|
||
function updateBellBtnVisibility() {
|
||
const btn = document.getElementById("bell-btn");
|
||
if (btn) btn.style.display = canUseBatchRing() ? "flex" : "none";
|
||
}
|
||
async function checkAuthStatus() {
|
||
if (!S.authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/status", {
|
||
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0 && data.data.logged_in) {
|
||
S.currentUser = { email: data.data.email };
|
||
updateAuthButton();
|
||
} else {
|
||
const hadToken = !!S.authToken;
|
||
S.authToken = null;
|
||
S.currentUser = null;
|
||
localStorage.removeItem("auth_token");
|
||
updateAuthButton();
|
||
if (hadToken && !S.authKickToastShown) {
|
||
S.authKickToastShown = true;
|
||
showToast("登录状态已失效,请重新登录");
|
||
showLoginGate();
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error("检查登录状态失败:", err);
|
||
}
|
||
}
|
||
var _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();
|
||
}
|
||
var 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 后重发`;
|
||
}
|
||
}, 1e3);
|
||
} 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, 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, code, 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 = "提交失败,请检查网络";
|
||
}
|
||
}
|
||
var VERSION_TAG = "v1.6.0";
|
||
var 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: [
|
||
"修复远程扫码被拦截:开锁上报车辆附近随机位置",
|
||
"请求头对齐当前版本微信环境"
|
||
] }
|
||
];
|
||
var versionModalInited = false;
|
||
var 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, 4e3);
|
||
return;
|
||
}
|
||
openVersionModal();
|
||
}
|
||
|
||
// src-ts/order/actions.ts
|
||
var currentBellTab = "all";
|
||
var selectedRadius = 200;
|
||
var selectedLocation = null;
|
||
var selectedStatuses = { available: true, used: true, locked: true, low: true, reserved: true };
|
||
var 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) {
|
||
S.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 (!S.autoLocationMarker) {
|
||
showToast("请先开启定位(点击底部定位按钮)");
|
||
return;
|
||
}
|
||
const point = S.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 = S.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) {
|
||
S.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
|
||
});
|
||
S.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(S.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 = String(counts.available);
|
||
document.getElementById("count-used-filter").textContent = String(counts.used);
|
||
document.getElementById("count-locked-filter").textContent = String(counts.locked);
|
||
document.getElementById("count-low-filter").textContent = String(counts.low);
|
||
document.getElementById("count-reserved-filter").textContent = String(counts.reserved);
|
||
}
|
||
function getFilteredBikes() {
|
||
const allBikes = Object.values(S.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 ${S.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) {
|
||
S.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);
|
||
}
|
||
}
|
||
var cardPayLoading = false;
|
||
async function tryCardPayOrRedirect() {
|
||
var _a, _b, _c;
|
||
if (cardPayLoading || !S.currentOrder) return;
|
||
const btn = document.getElementById("order-banner-btn");
|
||
cardPayLoading = true;
|
||
btn.textContent = "检测中…";
|
||
btn.disabled = true;
|
||
try {
|
||
const methodsResp = await fetch(
|
||
`/api/order/pay_methods?code=${encodeURIComponent(S.currentOrder.code || "")}`,
|
||
{ headers: { "Authorization": `Bearer ${S.authToken}` } }
|
||
);
|
||
const methodsData = await methodsResp.json();
|
||
if (methodsData.rtn_code !== 0) {
|
||
showToast("请到小白超人小程序支付订单");
|
||
return;
|
||
}
|
||
const cardMethods = ((_a = methodsData.data) == null ? void 0 : _a.card_methods) || [];
|
||
if (cardMethods.length === 0) {
|
||
showToast("未找到月卡,请到小白超人小程序支付");
|
||
return;
|
||
}
|
||
const preferred = cardMethods.find((m) => m.get_type === 2) || cardMethods[0];
|
||
const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡";
|
||
btn.textContent = `${cardTypeName}支付中…`;
|
||
const payResp = await fetch("/api/order/pay_with_card", {
|
||
method: "POST",
|
||
headers: {
|
||
"Authorization": `Bearer ${S.authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify({
|
||
order_id: S.currentOrder.order_id,
|
||
code: S.currentOrder.code || "",
|
||
type: String(preferred.type),
|
||
package_id: String(preferred.package_id)
|
||
})
|
||
});
|
||
const payData = await payResp.json();
|
||
if (payData.rtn_code === 0 && ((_b = payData.data) == null ? void 0 : _b.paid)) {
|
||
showToast(`${cardTypeName}支付成功 ✓`);
|
||
S.currentOrder = null;
|
||
hideOrderBanner();
|
||
refreshMap();
|
||
} else if (payData.rtn_code === 0 && ((_c = payData.data) == null ? void 0 : _c.need_wechat_pay)) {
|
||
showToast("月卡余额不足,请到小白超人小程序完成支付");
|
||
} else {
|
||
showToast(payData.message || "支付失败,请到小白超人小程序支付");
|
||
}
|
||
} catch (err) {
|
||
console.error("月卡支付失败:", err);
|
||
showToast("请到小白超人小程序支付订单");
|
||
} finally {
|
||
cardPayLoading = false;
|
||
btn.textContent = "去支付";
|
||
btn.disabled = false;
|
||
}
|
||
}
|
||
var returnLoading = false;
|
||
var pendingReturnOrder = null;
|
||
async function getOrderOperationLocation() {
|
||
var _a, _b;
|
||
let position = null;
|
||
if (navigator.geolocation) {
|
||
position = await new Promise((resolve) => {
|
||
navigator.geolocation.getCurrentPosition(
|
||
(pos) => resolve(pos),
|
||
(err) => {
|
||
console.error("获取位置失败:", err);
|
||
resolve(null);
|
||
},
|
||
{ timeout: 5e3 }
|
||
);
|
||
});
|
||
}
|
||
const latitude = Number.isFinite((_a = position == null ? void 0 : position.coords) == null ? void 0 : _a.latitude) ? position.coords.latitude : 36.67;
|
||
const longitude = Number.isFinite((_b = position == null ? void 0 : position.coords) == null ? void 0 : _b.longitude) ? position.coords.longitude : 116.98;
|
||
return { latitude, longitude };
|
||
}
|
||
function showReturnConfirm() {
|
||
if (returnLoading) return;
|
||
if (!S.currentOrder || Number(S.currentOrder.status) !== 2) {
|
||
showToast("当前没有可还车的进行中订单,正在刷新");
|
||
checkOrderStatus();
|
||
return;
|
||
}
|
||
pendingReturnOrder = { ...S.currentOrder };
|
||
document.getElementById("return-confirm-text").textContent = `车辆 #${S.currentOrder.code || S.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 ${S.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) {
|
||
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 (!S.currentOrder || String(S.currentOrder.order_id) === String(order.order_id)) {
|
||
S.currentOrder = null;
|
||
hideOrderBanner();
|
||
}
|
||
refreshMap();
|
||
refreshShareBanners();
|
||
} else {
|
||
showToast(data.message || "还车失败");
|
||
}
|
||
} catch (err) {
|
||
showToast("还车失败,请重试");
|
||
} finally {
|
||
returnLoading = false;
|
||
btn.disabled = false;
|
||
btn.textContent = "确认还车";
|
||
}
|
||
}
|
||
var orderTempActionLoading = false;
|
||
async function tempLockCurrentOrder() {
|
||
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
||
const order = S.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 ${S.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(S.currentOrder) || Number(S.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 ${S.authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify({ order_id: S.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 = "临时开车";
|
||
}
|
||
}
|
||
}
|
||
var unlockPendingCode = null;
|
||
var unlockPendingPosition = null;
|
||
function handleQuickUnlock() {
|
||
const qrBox = document.getElementById("qrcode-box");
|
||
const code = qrBox.dataset.bikeCode;
|
||
if (!code) {
|
||
showToast("无法获取车辆编码");
|
||
return;
|
||
}
|
||
if (!S.currentUser) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
const bikeForCoord = S.markersData[parseInt(code)] || S.markersData[code] || S.selectedBike;
|
||
const baseLat = parseFloat(bikeForCoord && bikeForCoord.latitude) || 36.67;
|
||
const baseLng = parseFloat(bikeForCoord && bikeForCoord.longitude) || 116.98;
|
||
const jit = 1e-4;
|
||
unlockPendingCode = code;
|
||
unlockPendingPosition = {
|
||
lat: baseLat + (Math.random() * 2 - 1) * jit,
|
||
lng: baseLng + (Math.random() * 2 - 1) * jit
|
||
};
|
||
openUnlockAccountChooser();
|
||
}
|
||
var unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
|
||
var unlockSrcList = [];
|
||
var unlockSrcShowAll = false;
|
||
function openUnlockAccountChooser() {
|
||
unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
|
||
unlockSrcShowAll = false;
|
||
if (!S.authToken || !S.currentUser) {
|
||
proceedToUnlockConfirm();
|
||
return;
|
||
}
|
||
fetch("/api/share/sources", { headers: { "Authorization": "Bearer " + S.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 " + S.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 || !S.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 ${S.authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify(payload)
|
||
});
|
||
const data = await resp.json();
|
||
console.log("[开锁] 响应:", data);
|
||
const code = unlockPendingCode;
|
||
closeUnlockConfirm();
|
||
if (data.rtn_code === 0) {
|
||
showToast(data.message || "开锁成功!");
|
||
closeQrModal();
|
||
if (isShared) {
|
||
refreshShareBanners();
|
||
checkOrderStatus();
|
||
} else {
|
||
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 (!S.authToken) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
try {
|
||
const resp = await fetch("/api/order/unlock", {
|
||
method: "POST",
|
||
headers: {
|
||
"Authorization": `Bearer ${S.authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify({
|
||
code,
|
||
latitude,
|
||
longitude
|
||
})
|
||
});
|
||
const data = await resp.json();
|
||
console.log("[开锁] 响应:", data);
|
||
if (data.rtn_code === 0) {
|
||
showToast(data.message || "开锁成功!");
|
||
closeQrModal();
|
||
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;
|
||
S.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(S.activeRental));
|
||
if (S.rentalCountdownTimer) clearInterval(S.rentalCountdownTimer);
|
||
S.rentalCountdownTimer = setInterval(() => {
|
||
if (S.activeRental && S.activeRental.remaining_seconds > 0) {
|
||
S.activeRental.remaining_seconds--;
|
||
localStorage.setItem(RENTAL_KEY, JSON.stringify(S.activeRental));
|
||
}
|
||
}, 1e3);
|
||
}
|
||
var orderTrajMap = null;
|
||
var 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 ${S.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 || [];
|
||
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 initMap3 = () => {
|
||
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);
|
||
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 分钟),已用订单起终点示意";
|
||
};
|
||
setTimeout(initMap3, 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 ${S.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();
|
||
}
|
||
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 ${S.authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
renderUnlockPreview(data.rtn_code === 0 ? data.data : null);
|
||
} catch (err) {
|
||
renderUnlockPreview(null);
|
||
}
|
||
}
|
||
var _addRoundTarget = null;
|
||
function showAddRoundConfirm(target) {
|
||
_addRoundTarget = target;
|
||
const remainSec = target.kind === "rental" ? S.activeRental && S.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 || !S.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 ${S.authToken}`, "Content-Type": "application/json" },
|
||
body: JSON.stringify(payload)
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) {
|
||
showToast(data.message || "已加 1 轮");
|
||
if (S.activeRental) {
|
||
S.activeRental.total_rounds = data.data.total_rounds;
|
||
S.activeRental.final_end_time = data.data.final_end_time;
|
||
localStorage.setItem(RENTAL_KEY, JSON.stringify(S.activeRental));
|
||
updateRentalFinalTime();
|
||
}
|
||
if (S.currentOrder && S.currentOrder.order_id) fetchOrderCountdown(S.currentOrder.order_id);
|
||
checkOrderStatus();
|
||
} else {
|
||
showToast(data.message || "加轮失败");
|
||
}
|
||
} catch (err) {
|
||
showToast("网络错误,请重试");
|
||
} finally {
|
||
closeAddRoundModal();
|
||
}
|
||
}
|
||
function addRoundForCurrent() {
|
||
if (!S.activeRental || !S.authToken) {
|
||
showToast("当前没有进行中的订单");
|
||
return;
|
||
}
|
||
showAddRoundConfirm({ kind: "rental", value: S.activeRental.rental_id });
|
||
}
|
||
function addRoundFromBanner() {
|
||
if (!S.currentOrder || !S.currentOrder.order_id) {
|
||
showToast("当前没有进行中的订单");
|
||
return;
|
||
}
|
||
showAddRoundConfirm({ kind: "order", value: S.currentOrder.order_id });
|
||
}
|
||
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 ${S.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;
|
||
const mapBike = S.markersData[codeNum] || S.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);
|
||
S.map.panTo(new BMapGL.Point(c.lng, c.lat));
|
||
setTimeout(() => S.map.setZoom(S.map.getZoom() + 1), 300);
|
||
} else {
|
||
showToast("该车暂无实时位置,请在地图上查看");
|
||
}
|
||
if (bike.state === 1 && bike.status === 1) {
|
||
showToast("该车正在使用中");
|
||
}
|
||
S.markersData[codeNum] = bike;
|
||
if (hasLocation && !S.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) }
|
||
);
|
||
S.map.addOverlay(marker);
|
||
S.currentMarkers.push(marker);
|
||
S.currentMarkersById[codeNum] = marker;
|
||
S.scannedMarkers[codeNum] = marker;
|
||
bindMarkerTap(marker, codeNum);
|
||
} catch (e) {
|
||
console.warn("[扫码] 补标记失败:", e);
|
||
}
|
||
}
|
||
showBikeDetail(codeNum);
|
||
} else if (data.success === false) {
|
||
const mapBike = S.markersData[codeNum] || S.markersData[code];
|
||
if (mapBike && mapBike.latitude && mapBike.longitude) {
|
||
const c = offsetCoord(mapBike.latitude, mapBike.longitude);
|
||
S.map.panTo(new BMapGL.Point(c.lng, c.lat));
|
||
setTimeout(() => S.map.setZoom(S.map.getZoom() + 1), 300);
|
||
mapBike.code = code;
|
||
S.markersData[codeNum] = mapBike;
|
||
showBikeDetail(codeNum);
|
||
showToast(data.message || "该车辆已被使用");
|
||
} else {
|
||
showToast(data.message || "查询失败");
|
||
}
|
||
} else {
|
||
showToast(data.message || "查询失败");
|
||
}
|
||
}).catch((err) => showToast("请求失败: " + friendlyError(err)));
|
||
}
|
||
var _lostModeActive = false;
|
||
var _lostModeTimer = null;
|
||
var _findClickTimer = null;
|
||
var LOST_TRIGGER_CLICKS = 3;
|
||
var LOST_TRIGGER_LONG = 700;
|
||
var LOST_INTERVAL = 3e3;
|
||
function _doFindBikeRequest(code) {
|
||
return fetch("/api/find_bike", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${S.authToken}`
|
||
},
|
||
body: JSON.stringify({ 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 (!S.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(S.selectedBike.code);
|
||
_lostModeTimer = setInterval(() => {
|
||
if (!_lostModeActive || !S.selectedBike) {
|
||
disableLostMode();
|
||
return;
|
||
}
|
||
_doFindBikeRequest(S.selectedBike.code);
|
||
}, LOST_INTERVAL);
|
||
window.addEventListener("beforeunload", _onPageUnload);
|
||
document.addEventListener("visibilitychange", _onVisibilityChange);
|
||
}
|
||
function disableLostMode() {
|
||
if (!_lostModeActive) return;
|
||
_lostModeActive = false;
|
||
clearInterval(_lostModeTimer);
|
||
_lostModeTimer = null;
|
||
S._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();
|
||
}
|
||
function findBike() {
|
||
if (!S.selectedBike) return;
|
||
if (_lostModeActive) {
|
||
disableLostMode();
|
||
return;
|
||
}
|
||
S._findClickCount++;
|
||
clearTimeout(_findClickTimer);
|
||
_findClickTimer = setTimeout(() => {
|
||
S._findClickCount = 0;
|
||
}, 1200);
|
||
if (S._findClickCount >= LOST_TRIGGER_CLICKS) {
|
||
S._findClickCount = 0;
|
||
clearTimeout(_findClickTimer);
|
||
showLostModal();
|
||
return;
|
||
}
|
||
const code = S.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 clearRentalState() {
|
||
if (S.rentalCountdownTimer) {
|
||
clearInterval(S.rentalCountdownTimer);
|
||
S.rentalCountdownTimer = null;
|
||
}
|
||
S.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 ${S.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 ${S.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 (!S.authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/rental/sync", {
|
||
method: "POST",
|
||
headers: {
|
||
"Authorization": `Bearer ${S.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;
|
||
S.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(S.activeRental));
|
||
} else if (data.rtn_code === 0 && data.data) {
|
||
clearRentalState();
|
||
}
|
||
} catch (err) {
|
||
console.error("[syncWechatOrder] 同步失败:", err);
|
||
}
|
||
}
|
||
function checkRentalStatus() {
|
||
if (!S.authToken) {
|
||
console.log("[checkRentalStatus] 无token,跳过");
|
||
return;
|
||
}
|
||
console.log("[checkRentalStatus] 发送请求, authToken:", S.authToken);
|
||
fetch("/api/rental/status", {
|
||
headers: { "Authorization": `Bearer ${S.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;
|
||
if (r.remaining_seconds <= 0) {
|
||
clearRentalState();
|
||
return;
|
||
}
|
||
S.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(S.activeRental));
|
||
showRentalBar();
|
||
} else {
|
||
console.log("[checkRentalStatus] 无活跃租车");
|
||
clearRentalState();
|
||
}
|
||
}).catch((err) => console.error("检查租车状态失败:", err));
|
||
}
|
||
function startRental(bikeCode) {
|
||
showQrModal(bikeCode);
|
||
closeCard();
|
||
console.log("[startRental] authToken:", S.authToken, "currentUser:", S.currentUser);
|
||
if (!S.currentUser) {
|
||
showToast("登录后可开启用车计时提醒");
|
||
return;
|
||
}
|
||
fetch("/api/rental/start", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${S.authToken}`
|
||
},
|
||
body: JSON.stringify({ bike_code: bikeCode })
|
||
}).then((r) => r.json()).then((data) => {
|
||
if (data.rtn_code === 0) {
|
||
const now = /* @__PURE__ */ new Date();
|
||
const endTime = new Date(now.getTime() + data.data.remaining_seconds * 1e3);
|
||
S.activeRental = {
|
||
rental_id: data.data.rental_id,
|
||
bike_code: bikeCode,
|
||
email: S.currentUser.email,
|
||
remaining_seconds: data.data.remaining_seconds,
|
||
end_time: endTime.toISOString().slice(0, 19).replace("T", " ")
|
||
};
|
||
localStorage.setItem(RENTAL_KEY, JSON.stringify(S.activeRental));
|
||
showRentalBar();
|
||
showToast("提醒计时已开始;未绑定微信订单,请到期前手动还车");
|
||
} else {
|
||
showToast(data.message || "计时启动失败");
|
||
}
|
||
}).catch((err) => {
|
||
showToast("计时未开启,请检查网络");
|
||
console.error("启动计时失败:", err);
|
||
});
|
||
}
|
||
function showRentalBar() {
|
||
if (!S.activeRental) return;
|
||
const bar = document.getElementById("rental-bar");
|
||
document.getElementById("rental-bike-code").textContent = `#${S.activeRental.bike_code}`;
|
||
const addBtn = document.getElementById("rental-add-round-btn");
|
||
if (addBtn) {
|
||
const realOrder = S.activeRental.source ? S.activeRental.source !== "reminder" : !!S.activeRental.order_id;
|
||
addBtn.style.display = realOrder ? "inline-flex" : "none";
|
||
}
|
||
updateRentalFinalTime();
|
||
bar.classList.add("show");
|
||
updateRentalCountdown();
|
||
if (S.rentalCountdownTimer) clearInterval(S.rentalCountdownTimer);
|
||
S.rentalCountdownTimer = setInterval(updateRentalCountdown, 1e3);
|
||
}
|
||
function updateRentalFinalTime() {
|
||
const el = document.getElementById("rental-final-time");
|
||
if (!el) return;
|
||
if (S.activeRental && S.activeRental.final_end_time) {
|
||
const hhmm = String(S.activeRental.final_end_time).slice(11, 16);
|
||
const total = S.activeRental.total_rounds || S.activeRental.rounds_planned;
|
||
el.textContent = total ? ` · 共${total}轮 预计${hhmm}还车` : ` · 预计${hhmm}还车`;
|
||
el.style.display = "inline";
|
||
} else {
|
||
el.style.display = "none";
|
||
}
|
||
}
|
||
function updateRentalCountdown() {
|
||
if (!S.activeRental) return;
|
||
const el = document.getElementById("rental-time");
|
||
const remaining = Math.max(0, S.activeRental.remaining_seconds - 1);
|
||
S.activeRental.remaining_seconds = remaining;
|
||
localStorage.setItem(RENTAL_KEY, JSON.stringify(S.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(S.rentalCountdownTimer);
|
||
S.rentalCountdownTimer = setInterval(checkRentalStatus, 6e4);
|
||
}
|
||
}
|
||
function showReturnModal() {
|
||
if (!S.activeRental) return;
|
||
document.getElementById("return-bike-code").textContent = `#${S.activeRental.bike_code}`;
|
||
document.getElementById("return-modal").classList.add("show");
|
||
}
|
||
function closeReturnModal() {
|
||
document.getElementById("return-modal").classList.remove("show");
|
||
}
|
||
async function confirmReturn() {
|
||
closeReturnModal();
|
||
if (!S.activeRental) return;
|
||
try {
|
||
const response = await fetch("/api/rental/return", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${S.authToken}`
|
||
},
|
||
body: JSON.stringify({ rental_id: S.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("网络错误,请检查网络后重试");
|
||
}
|
||
}
|
||
function isNativeShell() {
|
||
return document.documentElement && document.documentElement.classList.contains("in-native-shell");
|
||
}
|
||
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 (!S.selectedBike) return;
|
||
const bikeState = getBikeState(S.selectedBike);
|
||
if (bikeState === "inuse") {
|
||
showToast("该车正在使用中,请稍后再试");
|
||
closeCard();
|
||
return;
|
||
}
|
||
if (bikeState === "locked") {
|
||
showToast("该车已锁定,无法使用");
|
||
closeCard();
|
||
return;
|
||
}
|
||
if (bikeState === "reserved") {
|
||
showToast("该车已损坏,无法使用");
|
||
closeCard();
|
||
return;
|
||
}
|
||
if (nativeUnlockBike(S.selectedBike.code)) {
|
||
return;
|
||
}
|
||
showQrModal(S.selectedBike.code);
|
||
}
|
||
|
||
// src-ts/ui/modals.ts
|
||
var 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: 5e3 }
|
||
);
|
||
}
|
||
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";
|
||
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 = S.authToken && S.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 (S.authToken && S.currentUser) {
|
||
quickBtn.style.display = "block";
|
||
} else {
|
||
quickBtn.style.display = "none";
|
||
}
|
||
});
|
||
}
|
||
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);
|
||
if (typeof QRCode === "undefined") {
|
||
document.body.removeChild(tmp);
|
||
callback(null);
|
||
return;
|
||
}
|
||
new QRCode(tmp, {
|
||
text,
|
||
width: size,
|
||
height: size,
|
||
colorDark: dark,
|
||
colorLight: light,
|
||
correctLevel: QRCode.CorrectLevel.L
|
||
});
|
||
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;
|
||
}
|
||
var longPressTimer = null;
|
||
var longPressTarget = null;
|
||
var qrModalBikeCode = null;
|
||
function setupQrLongPress() {
|
||
const qrBox = document.getElementById("qrcode-box");
|
||
qrBox.addEventListener("pointerdown", function(e) {
|
||
if (!S.currentUser) return;
|
||
e.preventDefault();
|
||
qrModalBikeCode = qrBox.dataset.bikeCode || "";
|
||
longPressTimer = setTimeout(() => {
|
||
longPressTimer = null;
|
||
if (qrModalBikeCode && S.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;
|
||
}
|
||
});
|
||
}
|
||
var _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 || "确认操作";
|
||
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 showToast(msg) {
|
||
const t = document.getElementById("toast");
|
||
t.textContent = msg;
|
||
t.classList.add("show");
|
||
setTimeout(() => t.classList.remove("show"), 2500);
|
||
}
|
||
var CAPTURE_TOOL_PATH = "/download/capture-tool.exe";
|
||
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;
|
||
if (/Macintosh/.test(ua) && touchPoints > 1) return "iPad";
|
||
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) ? "安卓平板" : "安卓手机";
|
||
if (/Mobile/i.test(ua)) return "手机";
|
||
return null;
|
||
}
|
||
function detectInAppBrowser() {
|
||
const ua = navigator.userAgent || "";
|
||
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;
|
||
}
|
||
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");
|
||
}
|
||
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 (!S.authToken) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
showToast("正在生成导出链接...");
|
||
try {
|
||
const resp = await fetch("/api/export/create", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${S.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) {
|
||
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");
|
||
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("复制失败,请长按链接手动复制");
|
||
}
|
||
}
|
||
}
|
||
var _credInvalidLastShownAt = 0;
|
||
var CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1e3;
|
||
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");
|
||
loadExpiredTokenFields();
|
||
}
|
||
function closeTokenExpiredModal() {
|
||
document.getElementById("token-expired-modal").classList.remove("show");
|
||
document.getElementById("expired-tip").textContent = "";
|
||
}
|
||
async function loadExpiredTokenFields() {
|
||
if (!S.authToken) return;
|
||
try {
|
||
const resp = await fetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${S.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) {
|
||
}
|
||
}
|
||
async function saveExpiredToken() {
|
||
if (!S.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 ${S.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 ${S.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 shareAfterLogin() {
|
||
refreshShareBanners();
|
||
setTimeout(() => checkPendingShareRequests(), 800);
|
||
}
|
||
|
||
// src-ts/nav/navigation.ts
|
||
var _nav = null;
|
||
var _navLoading = false;
|
||
var _navEpoch = 0;
|
||
var NAV_DEVIATE_M = 60;
|
||
var NAV_RECOMPUTE_COOLDOWN_MS = 12e3;
|
||
var NAV_SNAP_M = 10;
|
||
var NAV_BOTTOM_RATIO = 0.2;
|
||
var NAV_FREE_TIMEOUT = 8e3;
|
||
function _haversineM(lat1, lng1, lat2, lng2) {
|
||
const R = 6371e3;
|
||
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));
|
||
}
|
||
function _gpsToGcj(coords) {
|
||
const lat = coords.latitude, lng = coords.longitude;
|
||
if (typeof coordtransform !== "undefined" && coordtransform.wgs84togcj02) {
|
||
try {
|
||
const g = coordtransform.wgs84togcj02(lng, lat);
|
||
return { lat: g[1], lng: g[0] };
|
||
} catch (e) {
|
||
}
|
||
}
|
||
return { lat, lng };
|
||
}
|
||
function _bearing(from, to) {
|
||
const p1 = from.lat * Math.PI / 180, p2 = to.lat * Math.PI / 180;
|
||
const dl = (to.lng - from.lng) * Math.PI / 180;
|
||
const y = Math.sin(dl) * Math.cos(p2);
|
||
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
|
||
return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
|
||
}
|
||
function _projectOnRoute(ptsBD, point) {
|
||
if (!ptsBD || ptsBD.length === 0) return { index: 0, meters: Infinity, point };
|
||
if (ptsBD.length === 1) {
|
||
return {
|
||
index: 0,
|
||
meters: _haversineM(point.lat, point.lng, ptsBD[0].lat, ptsBD[0].lng),
|
||
point: ptsBD[0]
|
||
};
|
||
}
|
||
const cosLat = Math.cos(point.lat * Math.PI / 180);
|
||
const toXY = (p2) => [
|
||
(p2.lng - point.lng) * 111320 * cosLat,
|
||
(p2.lat - point.lat) * 110540
|
||
];
|
||
let bestI = 0, bestM = Infinity, bestT = 0;
|
||
for (let i = 0; i < ptsBD.length - 1; i++) {
|
||
const a2 = toXY(ptsBD[i]), b2 = toXY(ptsBD[i + 1]);
|
||
const dx = b2[0] - a2[0], dy = b2[1] - a2[1];
|
||
const seg2 = dx * dx + dy * dy;
|
||
const t = seg2 === 0 ? 0 : Math.max(0, Math.min(1, -(a2[0] * dx + a2[1] * dy) / seg2));
|
||
const cx = a2[0] + t * dx, cy = a2[1] + t * dy;
|
||
const d = Math.hypot(cx, cy);
|
||
if (d < bestM) {
|
||
bestM = d;
|
||
bestI = i;
|
||
bestT = t;
|
||
}
|
||
}
|
||
const a = ptsBD[bestI], b = ptsBD[bestI + 1];
|
||
const p = new BMapGL.Point(
|
||
a.lng + bestT * (b.lng - a.lng),
|
||
a.lat + bestT * (b.lat - a.lat)
|
||
);
|
||
return { index: bestI, meters: bestM, point: p };
|
||
}
|
||
function _navBanner(show) {
|
||
const el = document.getElementById("nav-banner");
|
||
if (el) el.hidden = !show;
|
||
}
|
||
function _navPill(show) {
|
||
const el = document.getElementById("nav-resume");
|
||
if (el) el.hidden = !show;
|
||
}
|
||
function _navBtnText(text) {
|
||
const el = document.getElementById("bike-nav-btn-text");
|
||
if (el) el.textContent = text;
|
||
if (typeof _fitCardActions === "function") _fitCardActions();
|
||
}
|
||
function _clearNavLayers() {
|
||
if (!_nav) return;
|
||
(_nav.walking || []).forEach((ov) => {
|
||
try {
|
||
S.map.removeOverlay(ov);
|
||
} catch (e) {
|
||
}
|
||
});
|
||
(_nav.remaining || []).forEach((ov) => {
|
||
try {
|
||
S.map.removeOverlay(ov);
|
||
} catch (e) {
|
||
}
|
||
});
|
||
if (_nav.endMarker) {
|
||
try {
|
||
S.map.removeOverlay(_nav.endMarker);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
_nav.walking = [];
|
||
_nav.remaining = [];
|
||
_nav.endMarker = null;
|
||
}
|
||
function _redrawRoute(fromIndex) {
|
||
if (!_nav || !_nav.ptsBD || !_nav.ptsBD.length) return;
|
||
_clearNavLayers();
|
||
const pts = _nav.ptsBD;
|
||
const cut = Math.max(0, Math.min(fromIndex, pts.length - 1));
|
||
if (cut > 0) {
|
||
const walked = new BMapGL.Polyline(pts.slice(0, cut + 1), {
|
||
strokeColor: "#9E9E9E",
|
||
strokeWeight: 6,
|
||
strokeOpacity: 0.85,
|
||
strokeStyle: "solid"
|
||
});
|
||
S.map.addOverlay(walked);
|
||
_nav.walking.push(walked);
|
||
}
|
||
if (cut < pts.length - 1) {
|
||
const rest = pts.slice(cut);
|
||
const casing = new BMapGL.Polyline(rest, {
|
||
strokeColor: "#FFFFFF",
|
||
strokeWeight: 11,
|
||
strokeOpacity: 0.95,
|
||
strokeStyle: "solid"
|
||
});
|
||
const line = new BMapGL.Polyline(rest, {
|
||
strokeColor: "#0A84FF",
|
||
strokeWeight: 6,
|
||
strokeOpacity: 1,
|
||
strokeStyle: "solid"
|
||
});
|
||
S.map.addOverlay(casing);
|
||
S.map.addOverlay(line);
|
||
_nav.remaining.push(casing, line);
|
||
}
|
||
if (!_nav.endMarker) {
|
||
_nav.endMarker = new BMapGL.Marker(pts[pts.length - 1], { icon: _destIcon() });
|
||
S.map.addOverlay(_nav.endMarker);
|
||
}
|
||
}
|
||
var _headingSupported = null;
|
||
var _headingAnim = null;
|
||
function _rotateByAnimation(deg) {
|
||
try {
|
||
if (typeof BMapGL.ViewAnimation !== "function") return false;
|
||
const from = (typeof S.map.getHeading === "function" ? S.map.getHeading() : 0) || 0;
|
||
if (_headingAnim && S.map.cancelViewAnimation) {
|
||
try {
|
||
S.map.cancelViewAnimation(_headingAnim);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
_headingAnim = new BMapGL.ViewAnimation([
|
||
{ heading: from, percentage: 0 },
|
||
{ heading: deg, percentage: 1 }
|
||
], { duration: 260 });
|
||
S.map.startViewAnimation(_headingAnim);
|
||
return true;
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
function _applyHeading(deg) {
|
||
if (_headingSupported === false) return;
|
||
try {
|
||
if (typeof S.map.setHeading !== "function") {
|
||
_headingSupported = false;
|
||
return;
|
||
}
|
||
S.map.setHeading(deg);
|
||
if (_headingSupported === null) {
|
||
const got = typeof S.map.getHeading === "function" ? S.map.getHeading() : void 0;
|
||
_headingSupported = typeof got === "number" && Math.abs(got) > 0.5;
|
||
if (!_headingSupported) {
|
||
console.info("[导航] 当前环境不支持 setHeading,尝试 ViewAnimation 旋转");
|
||
try {
|
||
if (S.map.resetHeading) S.map.resetHeading();
|
||
} catch (e) {
|
||
}
|
||
try {
|
||
const c = S.map.getCenter ? S.map.getCenter() : null;
|
||
if (c) S.map.setCenter(c);
|
||
} catch (e) {
|
||
}
|
||
if (_rotateByAnimation(deg)) {
|
||
_headingSupported = true;
|
||
console.info("[导航] ViewAnimation 旋转可用");
|
||
}
|
||
}
|
||
}
|
||
} catch (e) {
|
||
_headingSupported = false;
|
||
}
|
||
}
|
||
function _centerOnUser(point, headingDeg) {
|
||
const h = window.innerHeight || 800;
|
||
const offsetY = Math.round(h * NAV_BOTTOM_RATIO);
|
||
const mapHeading = typeof headingDeg === "number" ? -headingDeg : null;
|
||
_markProgrammaticMove();
|
||
try {
|
||
S.map.setCenter(point, {
|
||
noAnimation: true,
|
||
callback: function() {
|
||
if (mapHeading !== null) _applyHeading(mapHeading);
|
||
try {
|
||
if (S.map.panBy) S.map.panBy(0, offsetY);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
});
|
||
} catch (e) {
|
||
try {
|
||
S.map.setCenter(point);
|
||
if (mapHeading !== null) _applyHeading(mapHeading);
|
||
if (S.map.panBy) S.map.panBy(0, offsetY);
|
||
} catch (e2) {
|
||
}
|
||
}
|
||
}
|
||
var _compassHeading = null;
|
||
var _compassBound = false;
|
||
function _bindCompass() {
|
||
if (_compassBound) return;
|
||
_compassBound = true;
|
||
const onOrient = (e) => {
|
||
let h = null;
|
||
if (typeof e.webkitCompassHeading === "number") {
|
||
h = e.webkitCompassHeading;
|
||
} else if (typeof e.alpha === "number") {
|
||
h = (360 - e.alpha) % 360;
|
||
}
|
||
if (h !== null && Number.isFinite(h)) _compassHeading = h;
|
||
};
|
||
window.addEventListener("deviceorientationabsolute", onOrient, true);
|
||
window.addEventListener("deviceorientation", onOrient, true);
|
||
}
|
||
async function _ensureCompassPermission() {
|
||
const D = window.DeviceOrientationEvent;
|
||
try {
|
||
if (D && typeof D.requestPermission === "function") {
|
||
const res = await D.requestPermission();
|
||
if (res !== "granted") {
|
||
console.info("[导航] 未获得方向传感器权限,箭头改用行进方向");
|
||
}
|
||
}
|
||
} catch (e) {
|
||
}
|
||
_bindCompass();
|
||
}
|
||
function _navArrowIcon() {
|
||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72"><circle cx="36" cy="36" r="30" fill="#0A84FF" fill-opacity="0.16"/><path d="M36 10 L52 52 L36 43 L20 52 Z" fill="#0A84FF" stroke="#FFFFFF" stroke-width="3" stroke-linejoin="round"/></svg>';
|
||
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||
return new BMapGL.Icon(
|
||
url,
|
||
new BMapGL.Size(36, 36),
|
||
{ anchor: new BMapGL.Size(18, 18) }
|
||
);
|
||
}
|
||
function _turnKind(turnType) {
|
||
const t = String(turnType || "");
|
||
if (t.indexOf("掉头") >= 0) return "uturn";
|
||
if (t.indexOf("左") >= 0) return "left";
|
||
if (t.indexOf("右") >= 0) return "right";
|
||
return "straight";
|
||
}
|
||
function _turnSvg(kind) {
|
||
const paths = {
|
||
straight: '<path d="M24 42 L24 12" /><path d="M14 22 L24 10 L34 22" />',
|
||
left: '<path d="M34 42 L34 22 L16 22" /><path d="M24 12 L12 22 L24 32" />',
|
||
right: '<path d="M14 42 L14 22 L32 22" /><path d="M30 12 L42 22 L30 32" />',
|
||
uturn: '<path d="M18 42 L18 18 A8 8 0 0 1 34 18 L34 26" /><path d="M26 20 L34 10 L42 20" />'
|
||
};
|
||
const body = paths[kind] || paths.straight;
|
||
return '<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round">' + body + "</svg>";
|
||
}
|
||
function _setTurnIcon(kind) {
|
||
const el = document.getElementById("nav-banner-turn");
|
||
if (!el) return;
|
||
if (el.__kind === kind) return;
|
||
el.__kind = kind;
|
||
el.innerHTML = _turnSvg(kind);
|
||
}
|
||
function _destIcon() {
|
||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="76" viewBox="0 0 32 38"><path d="M16 36C16 36 30 22.5 30 14A14 14 0 1 0 2 14C2 22.5 16 36 16 36Z" fill="#FF3B30" stroke="#FFFFFF" stroke-width="2.4"/><circle cx="16" cy="14" r="5" fill="#FFFFFF"/></svg>';
|
||
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||
return new BMapGL.Icon(url, new BMapGL.Size(30, 36), { anchor: new BMapGL.Size(15, 36) });
|
||
}
|
||
function _placeNavArrow(point) {
|
||
if (!_nav) return;
|
||
if (!_nav.arrow) {
|
||
_nav.arrow = new BMapGL.Marker(point, { icon: _navArrowIcon() });
|
||
S.map.addOverlay(_nav.arrow);
|
||
try {
|
||
if (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker) S.autoLocationMarker.hide();
|
||
} catch (e) {
|
||
}
|
||
return;
|
||
}
|
||
try {
|
||
_nav.arrow.setPosition(point);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function _rotateNavArrow(deg) {
|
||
if (!_nav || !_nav.arrow) return;
|
||
try {
|
||
if (typeof _nav.arrow.setRotation === "function") _nav.arrow.setRotation(deg);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function _clearNavArrow() {
|
||
if (_nav && _nav.arrow) {
|
||
try {
|
||
S.map.removeOverlay(_nav.arrow);
|
||
} catch (e) {
|
||
}
|
||
_nav.arrow = null;
|
||
}
|
||
try {
|
||
if (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker) S.autoLocationMarker.show();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function _navTick(position) {
|
||
if (!_nav || _nav.follow === false) return;
|
||
const gcj = _gpsToGcj(position);
|
||
const c = offsetCoord(gcj.lat, gcj.lng);
|
||
const me = new BMapGL.Point(c.lng, c.lat);
|
||
const proj = _projectOnRoute(_nav.ptsBD, me);
|
||
const now = Date.now();
|
||
if (proj.meters > NAV_DEVIATE_M && !_nav.recomputing && now - (_nav.lastRecomputeAt || 0) > NAV_RECOMPUTE_COOLDOWN_MS) {
|
||
_nav.recomputing = true;
|
||
_nav.lastRecomputeAt = now;
|
||
_recomputeRoute(gcj).finally(() => {
|
||
if (_nav) _nav.recomputing = false;
|
||
});
|
||
return;
|
||
}
|
||
if (proj.index !== _nav.idx) {
|
||
_nav.idx = proj.index;
|
||
_redrawRoute(_nav.idx);
|
||
}
|
||
const anchor = proj.meters <= NAV_SNAP_M && proj.point ? proj.point : me;
|
||
const aheadIdx = Math.min(proj.index + 3, _nav.ptsBD.length - 1);
|
||
const travelHeading = _bearing(_nav.ptsBD[proj.index], _nav.ptsBD[aheadIdx]);
|
||
_placeNavArrow(anchor);
|
||
const mapDeg = _headingSupported === false ? 0 : travelHeading;
|
||
const arrowDeg = typeof _compassHeading === "number" ? _compassHeading - mapDeg : 0;
|
||
_rotateNavArrow(arrowDeg);
|
||
_centerOnUser(anchor, travelHeading);
|
||
const total = _nav.ptsBD.length - 1;
|
||
const ratio = total > 0 ? Math.max(0, 1 - _nav.idx / total) : 0;
|
||
const leftM = Math.round((_nav.distance || 0) * ratio);
|
||
const leftS = Math.round((_nav.duration || 0) * ratio);
|
||
const travelled = (_nav.distance || 0) * (total > 0 ? _nav.idx / total : 0);
|
||
const actEl = document.getElementById("nav-banner-action");
|
||
if (actEl) {
|
||
const guide = _navGuidance(travelled);
|
||
if (guide.text) actEl.textContent = guide.text;
|
||
_setTurnIcon(guide.kind);
|
||
}
|
||
const bannerText = document.getElementById("nav-banner-text");
|
||
if (bannerText) {
|
||
bannerText.textContent = leftM < 1e3 ? "剩余 " + leftM + " 米 · 约 " + Math.max(1, Math.round(leftS / 60)) + " 分钟" : "剩余 " + (leftM / 1e3).toFixed(1) + " 公里 · 约 " + Math.max(1, Math.round(leftS / 60)) + " 分钟";
|
||
}
|
||
const dest = _nav.ptsBD[_nav.ptsBD.length - 1];
|
||
const toDest = _haversineM(me.lat, me.lng, dest.lat, dest.lng);
|
||
if (toDest < 25) {
|
||
showToast("已到达车辆附近");
|
||
stopNavigation();
|
||
}
|
||
}
|
||
function _navGuidance(travelled) {
|
||
if (!_nav || !_nav.stepEnds || !_nav.stepEnds.length) {
|
||
return { text: "", kind: "straight" };
|
||
}
|
||
const ends = _nav.stepEnds;
|
||
const steps = _nav.steps || [];
|
||
let i = ends.findIndex((e) => e > travelled);
|
||
const isLast = i === -1 || i >= ends.length - 1;
|
||
if (i === -1) i = ends.length - 1;
|
||
const left = Math.max(0, Math.round(ends[i] - travelled));
|
||
if (isLast) {
|
||
return {
|
||
text: left > 5 ? "前方 " + left + " 米 到达目的地" : "即将到达目的地",
|
||
kind: "straight"
|
||
};
|
||
}
|
||
const step = steps[i] || {};
|
||
let action = step.turn || "";
|
||
if (!action && step.text) {
|
||
const parts = step.text.split(/[,,]/);
|
||
action = parts[parts.length - 1] || step.text;
|
||
}
|
||
if (!action) action = "继续前行";
|
||
return { text: "前方 " + left + " 米 " + action, kind: _turnKind(step.turn) };
|
||
}
|
||
async function _recomputeRoute(gcj) {
|
||
if (!_nav || !_nav.destLat) return;
|
||
const myNav = _nav;
|
||
const epoch = _navEpoch;
|
||
try {
|
||
const data = await _requestNavRoute(
|
||
gcj.lat,
|
||
gcj.lng,
|
||
_nav.destLat,
|
||
_nav.destLng
|
||
);
|
||
if (!data) return;
|
||
if (_nav !== myNav || epoch !== _navEpoch || !_nav) return;
|
||
_applyRoute(data);
|
||
showToast("已重新规划路线");
|
||
} catch (e) {
|
||
console.warn("[导航] 重算失败", e);
|
||
}
|
||
}
|
||
async function _requestNavRoute(originLat, originLng, destLat, destLng) {
|
||
const url = "/api/nav_route?mode=walking&origin_lat=" + originLat + "&origin_lng=" + originLng + "&dest_lat=" + destLat + "&dest_lng=" + destLng;
|
||
const resp = await fetch(url, { headers: { "Authorization": "Bearer " + S.authToken } });
|
||
const json = await resp.json();
|
||
const d = json && json.data;
|
||
if (json.rtn_code !== 0 || !d || !d.points || !d.points.length) {
|
||
const msg = json && json.message || "没有拿到路线";
|
||
const err = new Error(msg);
|
||
if (json && (json.error_kind === "too_far" || /太远|200Km/i.test(msg))) {
|
||
err.tooFar = true;
|
||
}
|
||
throw err;
|
||
}
|
||
return d;
|
||
}
|
||
function _applyRoute(d) {
|
||
_nav.ptsGcj = d.points;
|
||
_nav.ptsBD = d.points.map((pt) => {
|
||
const c = offsetCoord(pt[1], pt[0]);
|
||
return new BMapGL.Point(c.lng, c.lat);
|
||
});
|
||
_nav.distance = d.distance;
|
||
_nav.duration = d.duration;
|
||
_nav.idx = 0;
|
||
_nav.recomputing = false;
|
||
_nav.steps = (d.steps || []).map((s) => ({
|
||
distance: s.distance || 0,
|
||
turn: s.turn_type || "",
|
||
text: String(s.instruction || "").replace(/<[^>]+>/g, "")
|
||
}));
|
||
let acc = 0;
|
||
_nav.stepEnds = _nav.steps.map((s) => acc += s.distance);
|
||
_redrawRoute(0);
|
||
}
|
||
function stopNavigation() {
|
||
_navEpoch++;
|
||
if (_nav && _nav.watchId !== null && navigator.geolocation) {
|
||
navigator.geolocation.clearWatch(_nav.watchId);
|
||
}
|
||
if (_nav && _nav.timer) clearTimeout(_nav.timer);
|
||
_clearNavLayers();
|
||
_clearNavArrow();
|
||
_nav = null;
|
||
_navBanner(false);
|
||
_navPill(false);
|
||
_navBtnText("导航");
|
||
try {
|
||
if (S.map.resetHeading) S.map.resetHeading();
|
||
} catch (e) {
|
||
}
|
||
_headingSupported = null;
|
||
}
|
||
function toggleNavigation() {
|
||
const bike = S.selectedBike;
|
||
if (!bike) return;
|
||
if (_nav && String(_nav.destCode) === String(bike.code)) {
|
||
stopNavigation();
|
||
return;
|
||
}
|
||
startNavigation(bike);
|
||
}
|
||
var _navSelfMoveUntil = 0;
|
||
function _markProgrammaticMove() {
|
||
_navSelfMoveUntil = Date.now() + 250;
|
||
}
|
||
function _scheduleResume() {
|
||
if (!_nav) return;
|
||
if (_nav.timer) clearTimeout(_nav.timer);
|
||
_nav.timer = setTimeout(() => {
|
||
if (_nav && _nav.follow === false) resumeNavigation();
|
||
}, NAV_FREE_TIMEOUT);
|
||
}
|
||
function _onMapDragStart() {
|
||
if (!_nav) return;
|
||
if (Date.now() < _navSelfMoveUntil) return;
|
||
_nav.follow = false;
|
||
_navPill(true);
|
||
_scheduleResume();
|
||
}
|
||
function _onMapDragging() {
|
||
if (!_nav || _nav.follow !== false) return;
|
||
_scheduleResume();
|
||
}
|
||
function _onMapDragEnd() {
|
||
if (!_nav || _nav.follow !== false) return;
|
||
_scheduleResume();
|
||
}
|
||
function resumeNavigation() {
|
||
if (!_nav) return;
|
||
_nav.follow = true;
|
||
_navPill(false);
|
||
if (_nav.timer) {
|
||
clearTimeout(_nav.timer);
|
||
_nav.timer = null;
|
||
}
|
||
const i = Math.min(_nav.idx, _nav.ptsBD.length - 1);
|
||
const j = Math.min(i + 3, _nav.ptsBD.length - 1);
|
||
const heading = _bearing(_nav.ptsBD[i], _nav.ptsBD[j]);
|
||
const me = typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||
const anchor = me || _nav.ptsBD[i];
|
||
_placeNavArrow(anchor);
|
||
_centerOnUser(anchor, heading);
|
||
}
|
||
async function startNavigation(bike) {
|
||
if (_navLoading) return;
|
||
const me = typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||
if (!me) {
|
||
showToast("请先开启定位,才能规划路线");
|
||
return;
|
||
}
|
||
if (!bike || !bike.latitude || !bike.longitude) {
|
||
showToast("这辆车没有坐标,无法导航");
|
||
return;
|
||
}
|
||
try {
|
||
const dest = offsetCoord(bike.latitude, bike.longitude);
|
||
const straight = calcDistance(me.lat, me.lng, dest.lat, dest.lng);
|
||
if (Number.isFinite(straight) && straight >= MAX_WALK_DISTANCE_M) return;
|
||
} catch (e) {
|
||
}
|
||
if (_nav) stopNavigation();
|
||
const epoch = ++_navEpoch;
|
||
_navLoading = true;
|
||
_navBanner(true);
|
||
const bannerText = document.getElementById("nav-banner-text");
|
||
if (bannerText) bannerText.textContent = "正在规划路线…";
|
||
try {
|
||
let gcj = null;
|
||
if (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) {
|
||
gcj = coordtransform.bd09togcj02(me.lng, me.lat);
|
||
}
|
||
if (!gcj) throw new Error("坐标转换不可用");
|
||
const d = await _requestNavRoute(gcj[1], gcj[0], bike.latitude, bike.longitude);
|
||
if (epoch !== _navEpoch) {
|
||
_navBanner(false);
|
||
_navBtnText("导航");
|
||
return;
|
||
}
|
||
_nav = {
|
||
destCode: bike.code,
|
||
destLat: bike.latitude,
|
||
destLng: bike.longitude,
|
||
follow: true,
|
||
timer: null,
|
||
watchId: null,
|
||
walking: [],
|
||
remaining: [],
|
||
endMarker: null,
|
||
idx: 0,
|
||
recomputing: false
|
||
};
|
||
_applyRoute(d);
|
||
_navBtnText("结束");
|
||
const start = _nav.ptsBD[0];
|
||
const next = _nav.ptsBD[Math.min(1, _nav.ptsBD.length - 1)];
|
||
_placeNavArrow(start);
|
||
_rotateNavArrow(_bearing(start, next));
|
||
_centerOnUser(start, _bearing(start, next));
|
||
_ensureCompassPermission();
|
||
const actEl0 = document.getElementById("nav-banner-action");
|
||
const g0 = _navGuidance(0);
|
||
if (actEl0) actEl0.textContent = g0.text || "沿路线前行";
|
||
_setTurnIcon(g0.kind);
|
||
if (bannerText) {
|
||
bannerText.textContent = d.distance < 1e3 ? "剩余 " + Math.round(d.distance) + " 米 · 约 " + Math.max(1, Math.round(d.duration / 60)) + " 分钟" : "剩余 " + (d.distance / 1e3).toFixed(1) + " 公里 · 约 " + Math.max(1, Math.round(d.duration / 60)) + " 分钟";
|
||
}
|
||
try {
|
||
closeCard();
|
||
} catch (e) {
|
||
}
|
||
if (navigator.geolocation) {
|
||
_nav.watchId = navigator.geolocation.watchPosition(
|
||
(pos) => _navTick(pos.coords),
|
||
(err) => console.warn("[导航] 定位失败", err.message),
|
||
{ enableHighAccuracy: true, maximumAge: 3e3, timeout: 1e4 }
|
||
);
|
||
}
|
||
} catch (err) {
|
||
console.error("[导航] 失败", err);
|
||
_navBanner(false);
|
||
if (err && err.tooFar) {
|
||
_navBtnText("导航");
|
||
_nav = null;
|
||
return;
|
||
}
|
||
showToast("导航失败:" + (err && err.message ? err.message : "请稍后再试"));
|
||
if (_nav && !_nav.ptsBD) _nav = null;
|
||
} finally {
|
||
_navLoading = false;
|
||
}
|
||
}
|
||
function bindNavMapEvents() {
|
||
try {
|
||
if (typeof S.map === "undefined" || !S.map || !S.map.addEventListener) return false;
|
||
if (S.map.__navBound) return true;
|
||
S.map.__navBound = true;
|
||
S.map.addEventListener("dragstart", _onMapDragStart);
|
||
S.map.addEventListener("dragging", _onMapDragging);
|
||
S.map.addEventListener("dragend", _onMapDragEnd);
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
try {
|
||
console.info("[导航] 已绑定地图拖动事件");
|
||
} catch (e) {
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// src-ts/map/core.ts
|
||
var INIT_OFFSET_EXTRA = 27e-5;
|
||
var INIT_OFFSET_EAST = 3e-3;
|
||
var mapInitializationStarted = false;
|
||
function initMap2() {
|
||
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 initMapCore() {
|
||
preloadBaseIcons();
|
||
fetch("/api/config").then((r) => r.json()).then((cfg) => {
|
||
document.getElementById("school-name").textContent = cfg.school_name || "山东管理学院";
|
||
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
|
||
c.lat += INIT_OFFSET_EXTRA;
|
||
c.lng += INIT_OFFSET_EAST;
|
||
S.map = new BMapGL.Map("baidu_map");
|
||
try {
|
||
if (typeof bindNavMapEvents === "function") bindNavMapEvents();
|
||
} catch (e) {
|
||
}
|
||
S.map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
|
||
S.map.enableScrollWheelZoom(true);
|
||
S.map.enableDragging(true);
|
||
S.map.enableInertialDragging(true);
|
||
S.map.addControl(new BMapGL.ScaleControl());
|
||
updateMapStyle();
|
||
loadMapData(S.currentType);
|
||
startAutoLocation();
|
||
}).catch((err) => {
|
||
console.error("初始化失败:", err);
|
||
showToast("地图初始化失败,请刷新重试");
|
||
});
|
||
}
|
||
function updateMapStyle() {
|
||
const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||
if (isDark) {
|
||
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 = "";
|
||
}
|
||
}
|
||
var mapRequest = null;
|
||
var mapRefreshTimer = null;
|
||
var renderedMapSnapshot = null;
|
||
var mapRefreshFailed = false;
|
||
function scheduleMapRefresh(snapshot, serverTime, retrySeconds = 5) {
|
||
clearTimeout(mapRefreshTimer);
|
||
const expires = Number(snapshot == null ? void 0 : snapshot.expires_at);
|
||
const delay = Number.isFinite(expires) && Number.isFinite(serverTime) ? Math.max(500, (expires - serverTime) * 1e3 + 150) : Math.max(1e3, retrySeconds * 1e3);
|
||
mapRefreshTimer = setTimeout(() => {
|
||
if (S.authToken && S.map && document.visibilityState === "visible") {
|
||
loadMapData(S.currentType, false, true);
|
||
}
|
||
}, Math.min(delay, 6e4));
|
||
}
|
||
function loadMapData(type, showLoading = true, quiet = false) {
|
||
if (!S.authToken) {
|
||
showLoginGate();
|
||
return Promise.resolve();
|
||
}
|
||
if (!S.map) return Promise.resolve();
|
||
if (mapRequest && mapRequest.type === String(type)) return mapRequest.promise;
|
||
const requestToken = S.authToken;
|
||
const loading = document.getElementById("loading");
|
||
if (S.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() / 1e3;
|
||
return { result, serverTime };
|
||
}).then(({ result, serverTime }) => {
|
||
if (S.authToken !== requestToken || String(type) !== String(S.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], !S.isFirstLoad);
|
||
S.isFirstLoad = false;
|
||
mapRefreshFailed = false;
|
||
if (result.map_snapshot) {
|
||
renderedMapSnapshot = { ...result.map_snapshot, serverTime, receivedAt: performance.now() };
|
||
updateMapFreshnessBadge();
|
||
} else updateTime();
|
||
if (S.map) setupClusterListener();
|
||
}).catch((err) => {
|
||
if (S.authToken !== requestToken || String(type) !== String(S.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(S.currentType, false);
|
||
setTimeout(() => btn.classList.remove("spinning"), 1e3);
|
||
}
|
||
function mapSnapshotNow() {
|
||
return renderedMapSnapshot ? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1e3 : Date.now() / 1e3;
|
||
}
|
||
function updateMapFreshnessBadge() {
|
||
const el = document.getElementById("update-time");
|
||
if (!el) return;
|
||
const stamp = Number(renderedMapSnapshot == null ? void 0 : renderedMapSnapshot.fetched_at);
|
||
if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) {
|
||
el.textContent = new Date(stamp * 1e3).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;
|
||
}
|
||
fetch(`/api/map/freshness?type=${encodeURIComponent(S.currentType)}`, { cache: "no-store" }).then((r) => r.json()).then((result) => {
|
||
var _a;
|
||
if (result.rtn_code !== 0 || !((_a = result.data) == null ? void 0 : _a.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 * 1e3).toLocaleTimeString("zh-CN", { timeZone: "Asia/Shanghai" });
|
||
const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`;
|
||
showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ",更新暂时失败,正在自动重试" : ""}`);
|
||
return;
|
||
}
|
||
showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据");
|
||
}
|
||
function locateMe() {
|
||
if (!navigator.geolocation) {
|
||
showToast("您的浏览器不支持定位");
|
||
return;
|
||
}
|
||
startAutoLocation();
|
||
}
|
||
function findNearestBikeManual() {
|
||
if (!S.autoLocationMarker) {
|
||
showToast("请先开启定位");
|
||
return;
|
||
}
|
||
const point = S.autoLocationMarker.getPosition();
|
||
findNearestBike(point);
|
||
}
|
||
function showMyLocation(point) {
|
||
if (S.myLocationMarker) {
|
||
S.map.removeOverlay(S.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));
|
||
S.myLocationMarker = new BMapGL.Marker(point, { icon });
|
||
S.map.addOverlay(S.myLocationMarker);
|
||
S.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");
|
||
}
|
||
function updateAutoLocation(point) {
|
||
if (!S.autoLocationMarker) {
|
||
const iconUrl = createAutoLocationIcon();
|
||
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||
S.autoLocationMarker = new BMapGL.Marker(point, { icon });
|
||
S.map.addOverlay(S.autoLocationMarker);
|
||
} else {
|
||
S.autoLocationMarker.setPosition(point);
|
||
}
|
||
}
|
||
function startAutoLocation() {
|
||
if (!navigator.geolocation) {
|
||
console.log("[自动定位] 浏览器不支持定位");
|
||
return;
|
||
}
|
||
if (S.autoLocationWatchId !== null) {
|
||
navigator.geolocation.clearWatch(S.autoLocationWatchId);
|
||
}
|
||
showToast("正在获取您的位置...");
|
||
S.autoLocationWatchId = navigator.geolocation.watchPosition(
|
||
(pos) => {
|
||
const gpsLat = pos.coords.latitude;
|
||
const gpsLng = pos.coords.longitude;
|
||
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);
|
||
S.hasLocationPermission = true;
|
||
if (!S.initialLocationCentered) {
|
||
S.initialLocationCentered = true;
|
||
if (S.map) {
|
||
S.map.setCenter(myPoint);
|
||
}
|
||
}
|
||
},
|
||
(err) => {
|
||
console.log("[自动定位] 定位失败:", err.message);
|
||
S.hasLocationPermission = false;
|
||
},
|
||
{ enableHighAccuracy: false, maximumAge: 5e3, timeout: 1e4 }
|
||
);
|
||
}
|
||
function stopAutoLocation() {
|
||
if (S.autoLocationWatchId !== null) {
|
||
navigator.geolocation.clearWatch(S.autoLocationWatchId);
|
||
S.autoLocationWatchId = null;
|
||
}
|
||
if (S.autoLocationMarker) {
|
||
S.map.removeOverlay(S.autoLocationMarker);
|
||
S.autoLocationMarker = null;
|
||
}
|
||
}
|
||
function findNearestBike(myPoint) {
|
||
const myLat = myPoint.lat;
|
||
const myLng = myPoint.lng;
|
||
const NEARBY_THRESHOLD = 200;
|
||
const LOW_BATTERY = 20;
|
||
const available = [];
|
||
for (const id in S.markersData) {
|
||
const bike2 = S.markersData[id];
|
||
if (!bike2.latitude || !bike2.longitude) continue;
|
||
const bs = getBikeState(bike2);
|
||
if (bs !== "available") continue;
|
||
const electric = parseFloat(bike2.electric_quantity || bike2.electricQuantity || 0);
|
||
if (electric <= LOW_BATTERY) continue;
|
||
const c2 = offsetCoord(bike2.latitude, bike2.longitude);
|
||
const dist = calcDistance(myLat, myLng, c2.lat, c2.lng);
|
||
available.push({ id, bike: bike2, dist, electric });
|
||
}
|
||
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 = "最近可用";
|
||
S.nearestBikeId = selected.id;
|
||
const bike = selected.bike;
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
||
S.map.panTo(bikePoint);
|
||
setTimeout(() => {
|
||
S.map.setZoom(S.map.getZoom() + 1);
|
||
}, 300);
|
||
const stateLabel = {
|
||
inuse: "使用中",
|
||
available: "空闲",
|
||
lowbattery: "低电量",
|
||
locked: "欠压车辆",
|
||
reserved: "损坏车辆",
|
||
unknown: "未知"
|
||
}[getBikeState(bike)] || "未知";
|
||
const distText = selected.dist < 1e3 ? `${Math.round(selected.dist)}米` : `${(selected.dist / 1e3).toFixed(1)}公里`;
|
||
showToast(`${matchType}:#${bike.code}(${stateLabel} ${selected.electric}%),${distText}`);
|
||
setTimeout(() => showBikeDetail(selected.id), 500);
|
||
}
|
||
|
||
// src-ts/map/markers.ts
|
||
function findMarkerById(id) {
|
||
const key = String(id);
|
||
if (S.currentMarkersById && S.currentMarkersById[id]) return S.currentMarkersById[id];
|
||
if (Array.isArray(S.currentMarkers)) {
|
||
for (let i = S.currentMarkers.length - 1; i >= 0; i--) {
|
||
const m = S.currentMarkers[i];
|
||
if (m && m.__animId !== void 0 && String(m.__animId) === key) return m;
|
||
}
|
||
for (let i = S.currentMarkers.length - 1; i >= 0; i--) {
|
||
const m = S.currentMarkers[i];
|
||
if (m && m.getTitle) {
|
||
const t = String(m.getTitle()).replace(/^#/, "");
|
||
if (t === key) return m;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
function bringMarkerToTop(marker) {
|
||
if (marker && marker.bringToTop) {
|
||
marker.bringToTop();
|
||
return;
|
||
}
|
||
if (marker && typeof S.map !== "undefined" && S.map && typeof S.map.removeOverlay === "function" && typeof S.map.addOverlay === "function") {
|
||
try {
|
||
const markerId = marker.__animId;
|
||
S.map.removeOverlay(marker);
|
||
S.map.addOverlay(marker);
|
||
if (markerId !== void 0) bindMarkerDomTouch(marker);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
}
|
||
function setHighlight(id) {
|
||
if (S.highlightedBikeId !== null) {
|
||
const prevMarker = findMarkerById(S.highlightedBikeId);
|
||
const prevBike = S.markersData[S.highlightedBikeId];
|
||
if (prevMarker && prevBike) {
|
||
try {
|
||
prevMarker.setIcon(getBikeIcon(prevBike, false));
|
||
} catch (e) {
|
||
console.warn("[setHighlight] 还原图标失败", e);
|
||
}
|
||
}
|
||
}
|
||
S.highlightedBikeId = id;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(id);
|
||
if (id === null || id === void 0) return;
|
||
const marker = findMarkerById(id);
|
||
const bike = S.markersData[id] || S.markersData[String(id)] || S.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 (S.highlightedBikeId !== null) {
|
||
const prevMarker = findMarkerById(S.highlightedBikeId);
|
||
const prevBike = S.markersData[S.highlightedBikeId];
|
||
if (prevMarker && prevBike) {
|
||
try {
|
||
prevMarker.setIcon(getBikeIcon(prevBike, false));
|
||
} catch (e) {
|
||
console.warn("[clearHighlight] 还原图标失败", e);
|
||
}
|
||
}
|
||
}
|
||
S.highlightedBikeId = null;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(null);
|
||
}
|
||
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) {
|
||
}
|
||
}
|
||
function bindMarkerTap(marker, id) {
|
||
const tap = {
|
||
lastFire: 0,
|
||
// 防重入:同一 marker 短时间内只触发一次
|
||
downX: null,
|
||
downY: null,
|
||
downT: 0,
|
||
_fire() {
|
||
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;
|
||
if (moved < 10 && dt < 600) this._fire();
|
||
}
|
||
};
|
||
marker.__xbniuTap = tap;
|
||
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) {
|
||
}
|
||
bindMarkerDomTouch(marker);
|
||
if (!marker.domElement) {
|
||
let tries = 0;
|
||
const timer = setInterval(() => {
|
||
tries++;
|
||
if (marker.domElement) {
|
||
bindMarkerDomTouch(marker);
|
||
clearInterval(timer);
|
||
} else if (tries > 10) {
|
||
clearInterval(timer);
|
||
}
|
||
}, 100);
|
||
}
|
||
}
|
||
function renderMap(results, isRefresh = false) {
|
||
if (typeof BikeClusters === "undefined") {
|
||
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
|
||
}
|
||
Object.keys(S.scannedMarkers).forEach((key) => {
|
||
try {
|
||
S.map.removeOverlay(S.scannedMarkers[key]);
|
||
} catch (e) {
|
||
}
|
||
delete S.scannedMarkers[key];
|
||
delete S.currentMarkersById[key];
|
||
});
|
||
if (!isRefresh) {
|
||
const autoPoint = S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||
S.map.clearOverlays();
|
||
if (bikeBubbleLayer) {
|
||
bikeBubbleLayer.destroy();
|
||
bikeBubbleLayer = null;
|
||
}
|
||
S.autoLocationMarker = null;
|
||
S.myLocationMarker = null;
|
||
S.currentMarkers = [];
|
||
if (autoPoint) {
|
||
const iconUrl = createAutoLocationIcon();
|
||
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||
S.autoLocationMarker = new BMapGL.Marker(autoPoint, { icon });
|
||
S.map.addOverlay(S.autoLocationMarker);
|
||
}
|
||
S.currentPolygons = [];
|
||
S.currentMarkersById = {};
|
||
S.markersData = {};
|
||
S.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
|
||
});
|
||
S.map.addOverlay(boundaryPolygon);
|
||
S.currentPolygons.push(boundaryPolygon);
|
||
}
|
||
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
|
||
});
|
||
S.map.addOverlay(parkingPolygon);
|
||
S.currentPolygons.push(parkingPolygon);
|
||
});
|
||
}
|
||
const allBikes = BikeClusters.normalizeBikes(data.bicycleStation);
|
||
allBikes.forEach((bike) => {
|
||
var _a, _b;
|
||
const electric = Number((_b = (_a = bike.electric_quantity) != null ? _a : bike.electricQuantity) != null ? _b : 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);
|
||
});
|
||
S.markersData = {};
|
||
nextBikes.forEach((bike) => {
|
||
S.markersData[BikeClusters.bikeId(bike)] = bike;
|
||
});
|
||
document.getElementById("count-available").textContent = String(availableCount);
|
||
document.getElementById("count-used").textContent = String(usedCount);
|
||
document.getElementById("count-locked").textContent = String(lockedCount);
|
||
document.getElementById("count-reserved").textContent = String(reservedCount);
|
||
document.getElementById("count-low").textContent = String(lowCount);
|
||
rebuildMarkersForZoom(nextBikes);
|
||
}
|
||
var bikeBubbleLayer = null;
|
||
function setupClusterListener() {
|
||
if (!S.map || bikeBubbleLayer || typeof BikeClusters === "undefined") return;
|
||
bikeBubbleLayer = BikeClusters.createLayer({
|
||
map: S.map,
|
||
enabled: S.bikeClusteringEnabled,
|
||
getPoint: (bike) => offsetCoord(bike.latitude, bike.longitude),
|
||
getState: getBikeState,
|
||
getIcon: getBikeIcon,
|
||
onBikeClick: (id) => {
|
||
clearHighlight();
|
||
showBikeDetail(id);
|
||
},
|
||
onMarkersChanged: (markers) => {
|
||
S.currentMarkers = markers;
|
||
S.currentMarkersById = {};
|
||
markers.forEach((marker) => {
|
||
S.currentMarkersById[marker.__animId] = marker;
|
||
});
|
||
}
|
||
});
|
||
bikeBubbleLayer.setSelected(S.highlightedBikeId);
|
||
}
|
||
function rebuildMarkersForZoom(bikes) {
|
||
setupClusterListener();
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setData(bikes != null ? bikes : Object.values(S.markersData));
|
||
}
|
||
|
||
// src-ts/card/bike-card.ts
|
||
function updateRingProgress(percent, color) {
|
||
const fill = document.getElementById("battery-fill");
|
||
if (fill) {
|
||
const maxW = 39;
|
||
const w = Math.round(percent / 100 * maxW);
|
||
fill.setAttribute("width", String(w));
|
||
fill.setAttribute("fill", color);
|
||
}
|
||
}
|
||
function viewBikeDetailFromOrderModal() {
|
||
closeOrderActionsModal();
|
||
viewBikeDetailFromOrder();
|
||
}
|
||
function viewBikeDetailFromOrder() {
|
||
if (!S.currentOrder) {
|
||
showToast("当前没有进行中的订单");
|
||
return;
|
||
}
|
||
const code = (S.currentOrder.code || "").toString().trim();
|
||
if (!code) {
|
||
showToast("该订单没有车牌信息");
|
||
return;
|
||
}
|
||
document.getElementById("scan-input").value = code;
|
||
scanCode();
|
||
}
|
||
function _fitCardActions(retry = 0) {
|
||
const card = document.getElementById("bike-card");
|
||
const codeEl = document.getElementById("card-code");
|
||
const title = card && card.querySelector(".bike-card-title");
|
||
if (!card || !codeEl) return;
|
||
if (card.offsetParent === null || card.clientWidth === 0) {
|
||
if (retry < 4) requestAnimationFrame(() => _fitCardActions(retry + 1));
|
||
return;
|
||
}
|
||
card.classList.remove("compact-actions");
|
||
const titleOverflow = title ? title.scrollWidth > title.clientWidth + 1 : false;
|
||
const codeOverflow = codeEl.scrollWidth > codeEl.clientWidth + 1;
|
||
if (titleOverflow || codeOverflow) card.classList.add("compact-actions");
|
||
}
|
||
var _cardFitObserver = null;
|
||
var _cardFitTimer = null;
|
||
function installCardFitObservers() {
|
||
if (typeof ResizeObserver !== "undefined" && !_cardFitObserver) {
|
||
const card = document.getElementById("bike-card");
|
||
if (card) {
|
||
_cardFitObserver = new ResizeObserver(() => {
|
||
if (_cardFitTimer) clearTimeout(_cardFitTimer);
|
||
_cardFitTimer = setTimeout(() => _fitCardActions(), 60);
|
||
});
|
||
_cardFitObserver.observe(card);
|
||
}
|
||
}
|
||
try {
|
||
const fonts = document.fonts;
|
||
if (fonts && fonts.ready && typeof fonts.ready.then === "function") {
|
||
fonts.ready.then(() => _fitCardActions());
|
||
}
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function showBikeDetail(id) {
|
||
let bike = S.markersData[id];
|
||
if (!bike) bike = S.markersData[String(id)];
|
||
if (!bike) bike = S.markersData[Number(id)];
|
||
if (!bike) {
|
||
for (const key in S.markersData) {
|
||
if (S.markersData[key] && String(S.markersData[key].code) === String(id)) {
|
||
bike = S.markersData[key];
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if (!bike) {
|
||
console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(S.markersData).slice(0, 5));
|
||
return;
|
||
}
|
||
if (typeof _nav !== "undefined" && _nav && String(_nav.destCode) !== String(bike.code)) {
|
||
try {
|
||
stopNavigation();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
S.selectedBike = bike;
|
||
setHighlight(id);
|
||
document.getElementById("card-code").textContent = `#${bike.code || id}`;
|
||
_navBtnText(_nav && String(_nav.destCode) === String(bike.code) ? "结束" : "导航");
|
||
const metaLeft = document.getElementById("card-meta-left");
|
||
const distEl = document.getElementById("card-distance");
|
||
const walkEl = document.getElementById("card-walk");
|
||
let distMeters = null;
|
||
if (metaLeft && distEl && walkEl) {
|
||
let distText = "";
|
||
let walkText = "";
|
||
try {
|
||
const me = typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||
if (me && bike.latitude && bike.longitude) {
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const meters = calcDistance(me.lat, me.lng, c.lat, c.lng);
|
||
distMeters = meters;
|
||
if (Number.isFinite(meters) && meters < MAX_WALK_DISTANCE_M) {
|
||
distText = meters < 1e3 ? `距你 ${Math.round(meters)} 米` : `距你 ${(meters / 1e3).toFixed(1)} 公里`;
|
||
walkText = `步行 ${Math.max(1, Math.round(meters / 80))} 分钟`;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
distText = "";
|
||
walkText = "";
|
||
}
|
||
distEl.textContent = distText;
|
||
walkEl.textContent = walkText;
|
||
metaLeft.hidden = !distText;
|
||
}
|
||
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();
|
||
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 = String(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);
|
||
}
|
||
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");
|
||
installCardFitObservers();
|
||
_fitCardActions();
|
||
requestAnimationFrame(() => _fitCardActions());
|
||
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);
|
||
S.map.panTo(bikePoint);
|
||
clearTimeout(_cardZoomTimer);
|
||
_cardZoomTimer = setTimeout(() => {
|
||
if (S.map.getZoom() < 19) S.map.setZoom(S.map.getZoom() + 1);
|
||
}, 300);
|
||
}
|
||
}
|
||
var _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");
|
||
S.selectedBike = null;
|
||
clearHighlight();
|
||
if (typeof disableLostMode === "function") disableLostMode();
|
||
}
|
||
|
||
// src-ts/subscribe/subscribe.ts
|
||
var subscribeLocations = [];
|
||
var SUB_WEEKDAYS = { 0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" };
|
||
async function openSubscribeModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("subscribe-modal");
|
||
await loadSubscribeLocations();
|
||
loadSubscribeRules();
|
||
}
|
||
function closeSubscribeModal() {
|
||
SettingsPages.back();
|
||
}
|
||
async function loadSubscribeLocations() {
|
||
const sel = document.getElementById("sub-location");
|
||
sel.innerHTML = '<option value="">加载中...</option>';
|
||
try {
|
||
const resp = await fetch("/api/campus/locations");
|
||
const data = await resp.json();
|
||
subscribeLocations = ((data.rtn_code === 0 ? data.data : []) || []).filter((l) => l.kind === "parking");
|
||
} catch (err) {
|
||
subscribeLocations = [];
|
||
}
|
||
sel.innerHTML = subscribeLocations.length ? subscribeLocations.map((l) => `<option value="${l.id}">${escHtml(l.name)}</option>`).join("") : '<option value="">(管理员尚未配置停车点)</option>';
|
||
}
|
||
function subRuleRowHtml(r) {
|
||
const loc = subscribeLocations.find((l) => l.id === r.location_id);
|
||
const locName = loc ? loc.name : r.location_name || "停车点已删除";
|
||
const hh = String(Math.floor(r.minute_of_day / 60)).padStart(2, "0");
|
||
const mm = String(r.minute_of_day % 60).padStart(2, "0");
|
||
const kindText = r.kind_labels && r.kind_labels.length ? r.kind_labels.join("/") : "全部车型";
|
||
const eMin = r.min_electric != null ? r.min_electric : 0;
|
||
const eMax = r.max_electric != null ? r.max_electric : 100;
|
||
const sortLabel = r.sort_by_label || r.sort_by || "";
|
||
const tags = [];
|
||
if (r.auto_unlock) {
|
||
tags.push(`自动开锁 · ${kindText} · 电量${eMin}-${eMax}% · ${sortLabel} · 重试${r.retry_times || 3}次`);
|
||
}
|
||
return `
|
||
<div class="device-item" style="display:block;padding:9px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
||
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;">
|
||
<div style="font-size:13px;line-height:1.6;min-width:0;">
|
||
<b>${escHtml(locName)}</b>
|
||
<span style="color:var(--text-secondary);"> · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm}</span>
|
||
<div style="font-size:11.5px;color:var(--text-secondary);">${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}</div>
|
||
${tags.length ? `<div style="font-size:11.5px;color:#005bbf;">${escHtml(tags[0])}</div>` : ""}
|
||
</div>
|
||
<div style="display:flex;gap:6px;flex:0 0 auto;">
|
||
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#ececf1;" onclick="toggleSubscribeRule(${r.id}, ${r.enabled ? 0 : 1})">${r.enabled ? "停用" : "启用"}</button>
|
||
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#fce4ec;color:#c62828;" onclick="deleteSubscribeRule(${r.id})">删除</button>
|
||
</div>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
function toggleSubAdvanced() {
|
||
const box = document.getElementById("sub-advanced");
|
||
if (!box) return;
|
||
const show = box.style.display === "none";
|
||
box.style.display = show ? "block" : "none";
|
||
}
|
||
async function loadSubscribeRules() {
|
||
const box = document.getElementById("subscribe-list");
|
||
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||
try {
|
||
const resp = await fetch("/api/subscribe/rules", {
|
||
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code !== 0) {
|
||
box.innerHTML = `<div class="device-loading">${escHtml(data.message || "加载失败")}</div>`;
|
||
return;
|
||
}
|
||
const rules = data.data || [];
|
||
box.innerHTML = rules.length ? rules.map(subRuleRowHtml).join("") : '<div class="device-loading">暂无规则,在下方添加</div>';
|
||
} catch (err) {
|
||
box.innerHTML = '<div class="device-loading">网络错误,请重试</div>';
|
||
}
|
||
}
|
||
async function addSubscribeRule() {
|
||
const locationId = Number(document.getElementById("sub-location").value || 0);
|
||
const weekday = Number(document.getElementById("sub-weekday").value);
|
||
const time = document.getElementById("sub-time").value;
|
||
const notify = document.getElementById("sub-notify").checked;
|
||
const auto = document.getElementById("sub-auto").checked;
|
||
const kinds = [...document.querySelectorAll(".sub-kind:checked")].map((el) => el.value);
|
||
const minE = Number(document.getElementById("sub-min-e").value || 0);
|
||
const maxE = Number(document.getElementById("sub-max-e").value || 100);
|
||
const sortBy = document.getElementById("sub-sort").value;
|
||
const retry = Number(document.getElementById("sub-retry").value || 3);
|
||
if (!locationId) {
|
||
showToast("请先选择停车点(需要管理员先配置停车点)");
|
||
return;
|
||
}
|
||
if (!/^\d{2}:\d{2}$/.test(time)) {
|
||
showToast("请选择时间");
|
||
return;
|
||
}
|
||
if (!kinds.length) {
|
||
showToast("至少选择一个车型");
|
||
return;
|
||
}
|
||
if (!(minE >= 0 && maxE <= 100 && minE <= maxE)) {
|
||
showToast("电量区间需在 0-100 且下限≤上限");
|
||
return;
|
||
}
|
||
if (auto) {
|
||
const ok = await appConfirm(
|
||
`开启自动开锁后,命中规则时系统会用你的账号直接开锁车辆。
|
||
|
||
筛选:${kinds.map((k) => ({ small: "小车", big: "大车", red: "红车" })[k]).join("/")},电量 ${minE}%-${maxE}%,${document.getElementById("sub-sort").selectedOptions[0].textContent};被他人抢先时最多重试 ${retry} 次。`,
|
||
{ title: "开启自动开锁", okText: "确认添加" }
|
||
);
|
||
if (!ok) return;
|
||
}
|
||
try {
|
||
const resp = await fetch("/api/subscribe/rules", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${S.authToken}`, "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
location_id: locationId,
|
||
weekday,
|
||
time,
|
||
notify_enabled: notify,
|
||
auto_unlock: auto,
|
||
kinds,
|
||
min_electric: minE,
|
||
max_electric: maxE,
|
||
sort_by: sortBy,
|
||
retry_times: retry
|
||
})
|
||
});
|
||
const data = await resp.json();
|
||
showToast(data.message || (data.rtn_code === 0 ? "已添加" : "添加失败"));
|
||
if (data.rtn_code === 0) loadSubscribeRules();
|
||
} catch (err) {
|
||
showToast("网络错误,请重试");
|
||
}
|
||
}
|
||
async function toggleSubscribeRule(ruleId, enable) {
|
||
try {
|
||
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||
method: "PUT",
|
||
headers: { "Authorization": `Bearer ${S.authToken}`, "Content-Type": "application/json" },
|
||
body: JSON.stringify({ enabled: !!enable })
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) loadSubscribeRules();
|
||
else showToast(data.message || "操作失败");
|
||
} catch (err) {
|
||
showToast("网络错误");
|
||
}
|
||
}
|
||
async function deleteSubscribeRule(ruleId) {
|
||
try {
|
||
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||
method: "DELETE",
|
||
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) loadSubscribeRules();
|
||
else showToast(data.message || "删除失败");
|
||
} catch (err) {
|
||
showToast("网络错误");
|
||
}
|
||
}
|
||
|
||
// src-ts/compat/globals.ts
|
||
window._alertOrderExpiring = _alertOrderExpiring;
|
||
window._applyHeading = _applyHeading;
|
||
window._applyRoute = _applyRoute;
|
||
window._bearing = _bearing;
|
||
window._bindCompass = _bindCompass;
|
||
window._centerOnUser = _centerOnUser;
|
||
window._clearNavArrow = _clearNavArrow;
|
||
window._clearNavLayers = _clearNavLayers;
|
||
window._destIcon = _destIcon;
|
||
window._doFindBikeRequest = _doFindBikeRequest;
|
||
window._ensureCompassPermission = _ensureCompassPermission;
|
||
window._fitCardActions = _fitCardActions;
|
||
window._gpsToGcj = _gpsToGcj;
|
||
window._haversineM = _haversineM;
|
||
window._markProgrammaticMove = _markProgrammaticMove;
|
||
window._navArrowIcon = _navArrowIcon;
|
||
window._navBanner = _navBanner;
|
||
window._navBtnText = _navBtnText;
|
||
window._navGuidance = _navGuidance;
|
||
window._navPill = _navPill;
|
||
window._navTick = _navTick;
|
||
window._onMapDragEnd = _onMapDragEnd;
|
||
window._onMapDragStart = _onMapDragStart;
|
||
window._onMapDragging = _onMapDragging;
|
||
window._onPageUnload = _onPageUnload;
|
||
window._onVisibilityChange = _onVisibilityChange;
|
||
window._placeNavArrow = _placeNavArrow;
|
||
window._projectOnRoute = _projectOnRoute;
|
||
window._recomputeRoute = _recomputeRoute;
|
||
window._redrawRoute = _redrawRoute;
|
||
window._requestNavRoute = _requestNavRoute;
|
||
window._rotateByAnimation = _rotateByAnimation;
|
||
window._rotateNavArrow = _rotateNavArrow;
|
||
window._scheduleResume = _scheduleResume;
|
||
window._setTurnIcon = _setTurnIcon;
|
||
window._turnKind = _turnKind;
|
||
window._turnSvg = _turnSvg;
|
||
window.acceptCurrentShareAsk = acceptCurrentShareAsk;
|
||
window.acceptShareRequest = acceptShareRequest;
|
||
window.addRoundForCurrent = addRoundForCurrent;
|
||
window.addRoundFromBanner = addRoundFromBanner;
|
||
window.addSubscribeRule = addSubscribeRule;
|
||
window.appConfirm = appConfirm;
|
||
window.appConfirmClose = appConfirmClose;
|
||
window.backToLoginFromForgot = backToLoginFromForgot;
|
||
window.bindMarkerDomTouch = bindMarkerDomTouch;
|
||
window.bindMarkerTap = bindMarkerTap;
|
||
window.bindNavMapEvents = bindNavMapEvents;
|
||
window.bringMarkerToTop = bringMarkerToTop;
|
||
window.canUseBatchRing = canUseBatchRing;
|
||
window.captureToolUrl = captureToolUrl;
|
||
window.checkAuthStatus = checkAuthStatus;
|
||
window.checkOrderStatus = checkOrderStatus;
|
||
window.checkPendingShareRequests = checkPendingShareRequests;
|
||
window.checkRentalStatus = checkRentalStatus;
|
||
window.checkStrictGuide = checkStrictGuide;
|
||
window.chooseUnlockSrc = chooseUnlockSrc;
|
||
window.clearHighlight = clearHighlight;
|
||
window.clearRentalState = clearRentalState;
|
||
window.closeAddRoundModal = closeAddRoundModal;
|
||
window.closeAllModals = closeAllModals;
|
||
window.closeAuthModal = closeAuthModal;
|
||
window.closeBellModal = closeBellModal;
|
||
window.closeCard = closeCard;
|
||
window.closeDevicesModal = closeDevicesModal;
|
||
window.closeDownloadTipModal = closeDownloadTipModal;
|
||
window.closeExportTipModal = closeExportTipModal;
|
||
window.closeForgotModal = closeForgotModal;
|
||
window.closeLoginModal = closeLoginModal;
|
||
window.closeLostModal = closeLostModal;
|
||
window.closeOrderActionsModal = closeOrderActionsModal;
|
||
window.closeOrderTrajModal = closeOrderTrajModal;
|
||
window.closeOrdersModal = closeOrdersModal;
|
||
window.closePackagesModal = closePackagesModal;
|
||
window.closeProfileModal = closeProfileModal;
|
||
window.closeQrModal = closeQrModal;
|
||
window.closeRegisterModal = closeRegisterModal;
|
||
window.closeRentalSettingsModal = closeRentalSettingsModal;
|
||
window.closeReturnConfirm = closeReturnConfirm;
|
||
window.closeReturnModal = closeReturnModal;
|
||
window.closeSettingsPage = closeSettingsPage;
|
||
window.closeShareConfig = closeShareConfig;
|
||
window.closeShareModal = closeShareModal;
|
||
window.closeShareRemark = closeShareRemark;
|
||
window.closeShareReturnModal = closeShareReturnModal;
|
||
window.closeSubscribeModal = closeSubscribeModal;
|
||
window.closeTokenExpiredModal = closeTokenExpiredModal;
|
||
window.closeUnlockConfirm = closeUnlockConfirm;
|
||
window.closeUnlockSrc = closeUnlockSrc;
|
||
window.closeVersionModal = closeVersionModal;
|
||
window.confirmAddRound = confirmAddRound;
|
||
window.confirmReturn = confirmReturn;
|
||
window.confirmShareReturn = confirmShareReturn;
|
||
window.copyDownloadLink = copyDownloadLink;
|
||
window.copyExportLink = copyExportLink;
|
||
window.createAutoLocationIcon = createAutoLocationIcon;
|
||
window.createFullIcon = createFullIcon;
|
||
window.createQrImage = createQrImage;
|
||
window.deleteSubscribeRule = deleteSubscribeRule;
|
||
window.describeTokenExpiry = describeTokenExpiry;
|
||
window.detectHarmony = detectHarmony;
|
||
window.detectInAppBrowser = detectInAppBrowser;
|
||
window.detectMobile = detectMobile;
|
||
window.disableLostMode = disableLostMode;
|
||
window.doLogin = doLogin;
|
||
window.doReturnBike = doReturnBike;
|
||
window.doUnlockBike = doUnlockBike;
|
||
window.enableLostMode = enableLostMode;
|
||
window.escHtml = escHtml;
|
||
window.exportHistoryCsv = exportHistoryCsv;
|
||
window.fetchOrderCountdown = fetchOrderCountdown;
|
||
window.findBike = findBike;
|
||
window.findCurrentOrderBike = findCurrentOrderBike;
|
||
window.findMarkerById = findMarkerById;
|
||
window.findNearestBike = findNearestBike;
|
||
window.findNearestBikeManual = findNearestBikeManual;
|
||
window.fmtClock = fmtClock;
|
||
window.fmtDuration = fmtDuration;
|
||
window.fmtLocalTime = fmtLocalTime;
|
||
window.fmtOrderTime = fmtOrderTime;
|
||
window.fmtRemainShort = fmtRemainShort;
|
||
window.fmtTime = fmtTime;
|
||
window.friendlyError = friendlyError;
|
||
window.getBikeIcon = getBikeIcon;
|
||
window.getBikeKind = getBikeKind;
|
||
window.getBikeState = getBikeState;
|
||
window.getDeviceId = getDeviceId;
|
||
window.getDeviceName = getDeviceName;
|
||
window.getFilteredBikes = getFilteredBikes;
|
||
window.getOrderOperationLocation = getOrderOperationLocation;
|
||
window.handleAuthBtnClick = handleAuthBtnClick;
|
||
window.handleForgotSubmit = handleForgotSubmit;
|
||
window.handleLoginSubmit = handleLoginSubmit;
|
||
window.handleLogout = handleLogout;
|
||
window.handleOrderBannerClick = handleOrderBannerClick;
|
||
window.handleOrderBannerSurfaceClick = handleOrderBannerSurfaceClick;
|
||
window.handleQuickUnlock = handleQuickUnlock;
|
||
window.handleRegisterSubmit = handleRegisterSubmit;
|
||
window.hideLoginGate = hideLoginGate;
|
||
window.hideOrderBanner = hideOrderBanner;
|
||
window.hideOrderCountdown = hideOrderCountdown;
|
||
window.initMap = initMap2;
|
||
window.initMapCore = initMapCore;
|
||
window.isNativeShell = isNativeShell;
|
||
window.isOrderActionEligible = isOrderActionEligible;
|
||
window.kickDevice = kickDevice;
|
||
window.loadDevicesList = loadDevicesList;
|
||
window.loadExpiredTokenFields = loadExpiredTokenFields;
|
||
window.loadMapData = loadMapData;
|
||
window.loadPackagesList = loadPackagesList;
|
||
window.loadProfileData = loadProfileData;
|
||
window.loadShareData = loadShareData;
|
||
window.loadSubscribeLocations = loadSubscribeLocations;
|
||
window.loadSubscribeRules = loadSubscribeRules;
|
||
window.loadUnlockPreview = loadUnlockPreview;
|
||
window.loadUnlockSrcShowAll = loadUnlockSrcShowAll;
|
||
window.loadUserInfo = loadUserInfo;
|
||
window.locateMe = locateMe;
|
||
window.logoutAllOtherDevices = logoutAllOtherDevices;
|
||
window.makeIconDataURI = makeIconDataURI;
|
||
window.mapSnapshotNow = mapSnapshotNow;
|
||
window.maybeAutoShowVersion = maybeAutoShowVersion;
|
||
window.maybeStrictGuide = maybeStrictGuide;
|
||
window.nativeUnlockBike = nativeUnlockBike;
|
||
window.nextShareAskIfQueue = nextShareAskIfQueue;
|
||
window.notifyCredentialInvalid = notifyCredentialInvalid;
|
||
window.onDownloadCaptureTool = onDownloadCaptureTool;
|
||
window.openAuthModal = openAuthModal;
|
||
window.openDevicesModal = openDevicesModal;
|
||
window.openOrderTrajectory = openOrderTrajectory;
|
||
window.openOrdersModal = openOrdersModal;
|
||
window.openPackagesModal = openPackagesModal;
|
||
window.openRentalSettingsModal = openRentalSettingsModal;
|
||
window.openSettingsPage = openSettingsPage;
|
||
window.openShareConfig = openShareConfig;
|
||
window.openShareModal = openShareModal;
|
||
window.openShareRemark = openShareRemark;
|
||
window.openShareReturnByIdx = openShareReturnByIdx;
|
||
window.openSubscribeModal = openSubscribeModal;
|
||
window.openUnlockAccountChooser = openUnlockAccountChooser;
|
||
window.openVersionModal = openVersionModal;
|
||
window.orderCardHtml = orderCardHtml;
|
||
window.parseJwtExpiry = parseJwtExpiry;
|
||
window.parseWalkDistance = parseWalkDistance;
|
||
window.parseWalkDuration = parseWalkDuration;
|
||
window.partnerLabel = partnerLabel;
|
||
window.payCurrentOrderFromModal = payCurrentOrderFromModal;
|
||
window.preloadBaseIcons = preloadBaseIcons;
|
||
window.proceedToUnlockConfirm = proceedToUnlockConfirm;
|
||
window.quickUnlock = quickUnlock;
|
||
window.rebuildMarkersForZoom = rebuildMarkersForZoom;
|
||
window.refineWalkRoute = refineWalkRoute;
|
||
window.refreshAuthExpiry = refreshAuthExpiry;
|
||
window.refreshMap = refreshMap;
|
||
window.refreshShareBanners = refreshShareBanners;
|
||
window.rejectCurrentShareAsk = rejectCurrentShareAsk;
|
||
window.rejectShareRequest = rejectShareRequest;
|
||
window.remainingTimeText = remainingTimeText;
|
||
window.renderAuthExpiryBanner = renderAuthExpiryBanner;
|
||
window.renderMap = renderMap;
|
||
window.renderOrderTrajectory = renderOrderTrajectory;
|
||
window.renderTokenExpiry = renderTokenExpiry;
|
||
window.renderUnlockPreview = renderUnlockPreview;
|
||
window.renderUnlockSrcList = renderUnlockSrcList;
|
||
window.resumeNavigation = resumeNavigation;
|
||
window.returnCurrentOrderFromModal = returnCurrentOrderFromModal;
|
||
window.rideProgressText = rideProgressText;
|
||
window.saveExpiredToken = saveExpiredToken;
|
||
window.saveMapClusteringSetting = saveMapClusteringSetting;
|
||
window.saveProfileToken = saveProfileToken;
|
||
window.saveRentalSettings = saveRentalSettings;
|
||
window.saveShareConfig = saveShareConfig;
|
||
window.saveShareRemark = saveShareRemark;
|
||
window.scanCode = scanCode;
|
||
window.scheduleMapRefresh = scheduleMapRefresh;
|
||
window.selectRadius = selectRadius;
|
||
window.sendForgotCode = sendForgotCode;
|
||
window.sendRegisterCode = sendRegisterCode;
|
||
window.sendShareRequest = sendShareRequest;
|
||
window.setForgotCodeBtn = setForgotCodeBtn;
|
||
window.setHighlight = setHighlight;
|
||
window.setRegisterCodeBtn = setRegisterCodeBtn;
|
||
window.setupClusterListener = setupClusterListener;
|
||
window.setupQrLongPress = setupQrLongPress;
|
||
window.shareAfterLogin = shareAfterLogin;
|
||
window.shareApi = shareApi;
|
||
window.sharePendingHtml = sharePendingHtml;
|
||
window.showAddRoundConfirm = showAddRoundConfirm;
|
||
window.showBellPasswordModal = showBellPasswordModal;
|
||
window.showBikeDetail = showBikeDetail;
|
||
window.showDownloadTipModal = showDownloadTipModal;
|
||
window.showForgotFromGate = showForgotFromGate;
|
||
window.showForgotModal = showForgotModal;
|
||
window.showFreshnessDetail = showFreshnessDetail;
|
||
window.showLoginGate = showLoginGate;
|
||
window.showLoginModal = showLoginModal;
|
||
window.showLostModal = showLostModal;
|
||
window.showMyLocation = showMyLocation;
|
||
window.showOrderActionsModal = showOrderActionsModal;
|
||
window.showOrderBanner = showOrderBanner;
|
||
window.showOrderCountdown = showOrderCountdown;
|
||
window.showProfileModal = showProfileModal;
|
||
window.showQrModal = showQrModal;
|
||
window.showRegisterModal = showRegisterModal;
|
||
window.showRentalBar = showRentalBar;
|
||
window.showReturnConfirm = showReturnConfirm;
|
||
window.showReturnModal = showReturnModal;
|
||
window.showToast = showToast;
|
||
window.showTokenExpiredModal = showTokenExpiredModal;
|
||
window.startAutoLocation = startAutoLocation;
|
||
window.startNavigation = startNavigation;
|
||
window.startOrderCountdown = startOrderCountdown;
|
||
window.startRental = startRental;
|
||
window.startRentalFromServer = startRentalFromServer;
|
||
window.stopAutoLocation = stopAutoLocation;
|
||
window.stopNavigation = stopNavigation;
|
||
window.subRuleRowHtml = subRuleRowHtml;
|
||
window.submitBellPassword = submitBellPassword;
|
||
window.switchBellTab = switchBellTab;
|
||
window.switchShareTab = switchShareTab;
|
||
window.syncWechatOrder = syncWechatOrder;
|
||
window.tempLockCurrentOrder = tempLockCurrentOrder;
|
||
window.tempUnlockCurrentOrder = tempUnlockCurrentOrder;
|
||
window.toggleNavigation = toggleNavigation;
|
||
window.toggleStatusFilter = toggleStatusFilter;
|
||
window.toggleSubAdvanced = toggleSubAdvanced;
|
||
window.toggleSubscribeRule = toggleSubscribeRule;
|
||
window.tryCardPayOrRedirect = tryCardPayOrRedirect;
|
||
window.unbindShare = unbindShare;
|
||
window.unlockBike = unlockBike;
|
||
window.updateAuthButton = updateAuthButton;
|
||
window.updateAutoLocation = updateAutoLocation;
|
||
window.updateBellBtnVisibility = updateBellBtnVisibility;
|
||
window.updateFilterInfo = updateFilterInfo;
|
||
window.updateMapFreshnessBadge = updateMapFreshnessBadge;
|
||
window.updateMapStyle = updateMapStyle;
|
||
window.updateOrderCountdownText = updateOrderCountdownText;
|
||
window.updateRangeCircle = updateRangeCircle;
|
||
window.updateRentalCountdown = updateRentalCountdown;
|
||
window.updateRentalFinalTime = updateRentalFinalTime;
|
||
window.updateRingProgress = updateRingProgress;
|
||
window.updateShareCountdowns = updateShareCountdowns;
|
||
window.updateStatusCounts = updateStatusCounts;
|
||
window.updateTime = updateTime;
|
||
window.updateTokenExpiryDisplays = updateTokenExpiryDisplays;
|
||
window.useCenterLocation = useCenterLocation;
|
||
window.useCurrentLocation = useCurrentLocation;
|
||
window.viewBikeDetailFromOrder = viewBikeDetailFromOrder;
|
||
window.viewBikeDetailFromOrderModal = viewBikeDetailFromOrderModal;
|
||
window.Geo = Geo;
|
||
window.offsetCoord = offsetCoord;
|
||
window.calcDistance = calcDistance;
|
||
window.S = S;
|
||
|
||
// src-ts/main.ts
|
||
function bootstrap() {
|
||
window.bindNavMapEvents = bindNavMapEvents;
|
||
(function _retryBindNavMapEvents(tries = 0) {
|
||
if (bindNavMapEvents()) return;
|
||
if (tries >= 20) {
|
||
console.warn("[导航] 地图拖动事件未能绑定(map 一直未就绪)");
|
||
return;
|
||
}
|
||
setTimeout(() => _retryBindNavMapEvents(tries + 1), 500);
|
||
})();
|
||
setInterval(updateShareCountdowns, 1e3);
|
||
window.addEventListener("storage", (event) => {
|
||
if (typeof BikeClusters === "undefined") return;
|
||
if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return;
|
||
S.bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage);
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(S.bikeClusteringEnabled);
|
||
document.getElementById("settings-clustering").checked = S.bikeClusteringEnabled;
|
||
});
|
||
setInterval(updateTokenExpiryDisplays, 3e4);
|
||
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']")
|
||
);
|
||
});
|
||
document.addEventListener("keydown", (event) => {
|
||
if (event.key !== "Escape") return;
|
||
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;
|
||
}
|
||
});
|
||
document.addEventListener("DOMContentLoaded", async () => {
|
||
if (S.authToken) {
|
||
await syncWechatOrder();
|
||
checkOrderStatus();
|
||
checkRentalStatus();
|
||
checkStrictGuide();
|
||
refreshAuthExpiry();
|
||
}
|
||
});
|
||
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
|
||
updateMapStyle();
|
||
});
|
||
window.addEventListener("resize", () => {
|
||
clearTimeout(S._fitCardTimer);
|
||
S._fitCardTimer = setTimeout(() => {
|
||
if (document.getElementById("bike-card"))
|
||
_fitCardActions();
|
||
}, 120);
|
||
});
|
||
(function initSwipeClose() {
|
||
const card = document.getElementById("bike-card");
|
||
let startY = 0, startTime = 0, dragging = false;
|
||
card.addEventListener("touchstart", (e) => {
|
||
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;
|
||
if (dy > 120 || dy > 40 && dt < 250) {
|
||
closeCard();
|
||
} else {
|
||
card.style.transform = "";
|
||
}
|
||
}, { passive: true });
|
||
})();
|
||
(function initFindBtnLongPress() {
|
||
const btn = document.getElementById("bike-find-btn-header");
|
||
if (!btn) return;
|
||
function startLongPress(e) {
|
||
if (_lostModeActive) return;
|
||
clearTimeout(S._findLongPressTimer);
|
||
S._findLongPressTimer = setTimeout(() => {
|
||
S._findClickCount = 0;
|
||
clearTimeout(_findClickTimer);
|
||
showLostModal();
|
||
}, LOST_TRIGGER_LONG);
|
||
}
|
||
function cancelLongPress() {
|
||
clearTimeout(S._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);
|
||
})();
|
||
setupQrLongPress();
|
||
document.getElementById("qr-modal").addEventListener("click", function(e) {
|
||
if (e.target === this) closeQrModal();
|
||
});
|
||
checkAuthStatus().then(() => {
|
||
if (S.authToken && typeof SettingsPages !== "undefined") SettingsPages.restore();
|
||
checkRentalStatus();
|
||
if (S.authToken) shareAfterLogin();
|
||
});
|
||
if (!S.authToken) showLoginGate();
|
||
document.addEventListener("DOMContentLoaded", initMap2);
|
||
window.addEventListener("xbniu-map-ready", initMap2);
|
||
document.getElementById("scan-input").addEventListener("keydown", (e) => {
|
||
if (e.key === "Enter") scanCode();
|
||
});
|
||
setInterval(updateMapFreshnessBadge, 1e3);
|
||
setInterval(async () => {
|
||
if (!S.authToken || document.visibilityState !== "visible") return;
|
||
if (!S.currentOrder || Number(S.currentOrder.status) !== 2) return;
|
||
try {
|
||
await syncWechatOrder();
|
||
checkOrderStatus();
|
||
if (S.currentOrder && S.currentOrder.order_id) {
|
||
fetchOrderCountdown(S.currentOrder.order_id);
|
||
}
|
||
} catch (e) {
|
||
console.error("[订单2分钟刷新] 失败:", e);
|
||
}
|
||
}, 12e4);
|
||
document.addEventListener("visibilitychange", () => {
|
||
if (document.visibilityState === "visible") {
|
||
if (S.authToken && S.map) loadMapData(S.currentType, false, true);
|
||
checkAuthStatus().then(async () => {
|
||
if (S.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") && S.currentOrder && S.currentOrder.status === 2) {
|
||
console.log("[visibilitychange] order-banner 进行中,同步倒计时");
|
||
fetchOrderCountdown(S.currentOrder.order_id);
|
||
}
|
||
});
|
||
}
|
||
});
|
||
(function() {
|
||
var b = document.getElementById("version-badge");
|
||
if (b) b.textContent = VERSION_TAG;
|
||
})();
|
||
document.addEventListener("DOMContentLoaded", () => {
|
||
if (S.authToken) shareAfterLogin();
|
||
setInterval(() => {
|
||
if (S.authToken) {
|
||
checkAuthStatus();
|
||
checkOrderStatus();
|
||
refreshShareBanners();
|
||
}
|
||
}, 2e4);
|
||
setInterval(() => {
|
||
if (S.authToken) checkPendingShareRequests();
|
||
}, 3e4);
|
||
});
|
||
}
|
||
bootstrap();
|
||
})();
|
||
//# sourceMappingURL=app.js.map
|