Files
xbcr/src-ts/order/actions.ts
T
zzy 8ece55983a feat(前端): TypeScript 重写版(esbuild IIFE 产物,暂不接管线上)
- 新增 src-ts/(22 个 .ts / 7792 行):按 core / map / card / order / nav / share /
  subscribe / ui / compat 分层,types 里有 BMapGL 与 API 响应声明
- compat/globals.ts 是唯一挂 window 的地方(292 个),覆盖模板 139 处内联事件
- esbuild 产出 static/dist/app.js(226.6 KiB,IIFE,es2019)+ README(构建/切换/回滚)
- 构建可复现:node esbuild.config.mjs、node --check、npx tsc --noEmit 均通过
- .gitignore 增加 node_modules/ 与 static/dist/*.map(sourcemap 可重生成,不入库)
- 暂不改 templates/map.html 与 MAP_ASSETS:等独立核对通过再切换,回滚=换回四个 script
2026-11-16 10:44:11 +08:00

1841 lines
67 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
import { S } from "../core/state";
import { RENTAL_KEY } from "../core/state";
import { closeCard, showBikeDetail } from "../card/bike-card";
import { escHtml, fmtOrderTime, friendlyError } from "../core/format";
import { calcDistance, offsetCoord } from "../core/geo";
import { initMap, refreshMap } from "../map/core";
import { getBikeIcon, getBikeState } from "../map/icons";
import { bindMarkerTap } from "../map/markers";
import { checkOrderStatus, fetchOrderCountdown, hideOrderBanner, isOrderActionEligible, orderCardHtml, orderCountdownSeconds } from "./status";
import { partnerLabel, refreshShareBanners } from "../share/share";
import { closeQrModal, showQrModal, showToast } from "../ui/modals";
import { canUseBatchRing, closeAllModals, showLoginGate } from "../ui/settings";
// static/js/map.js:1064-1064
let currentBellTab: any = 'all'; // 当前选项卡
// static/js/map.js:1065-1065
let selectedRadius: any = 200; // 选中的半径(米)
// static/js/map.js:1066-1066
let selectedLocation: any = null; // 选中的地点 {lat, lng}
// static/js/map.js:1067-1067
let selectedStatuses: any = {available: true, used: true, locked: true, low: true, reserved: true}; // 选中的状态
// static/js/map.js:1068-1068
let rangeCircleOverlay: any = null; // 范围圆覆盖物
// static/js/map.js:1070-1106
export 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();
}
// 切换选项卡
// static/js/map.js:1107-1129
export 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;
}
}
}
// 选择半径
// static/js/map.js:1130-1140
export function selectRadius(radius) {
selectedRadius = radius;
document.querySelectorAll('.radius-btn').forEach(btn => {
btn.classList.toggle('active', parseInt(btn.dataset.radius) === radius);
});
// 更新范围圆
updateRangeCircle();
updateFilterInfo();
}
// 使用当前位置
// static/js/map.js:1141-1168
export 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} 辆车`);
}
// 使用地图中心
// static/js/map.js:1169-1191
export 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} 辆车`);
}
// 更新范围圆覆盖物
// static/js/map.js:1192-1211
export 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);
}
// 切换状态筛选
// static/js/map.js:1212-1224
export 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();
}
// 更新状态计数
// static/js/map.js:1225-1250
export function updateStatusCounts() {
const bikes = Object.values<any>(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);
}
// 计算两点之间的距离(米)
// 导航相关已拆到 static/js/navigation.js
// 根据当前模式筛选车辆
// static/js/map.js:1251-1289
export function getFilteredBikes() {
const allBikes = Object.values<any>(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;
}
// 更新筛选信息显示
// static/js/map.js:1290-1307
export 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<any>(selectedStatuses).filter(v => v).length;
infoEl.textContent = `已选 ${selectedCount} 种状态,共 ${bikes.length} 辆车`;
}
}
// static/js/map.js:1309-1311
export function closeBellModal() {
document.getElementById("bell-modal").classList.remove("show");
}
// static/js/map.js:1313-1394
export 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);
}
}
// ========== 全屏登录门 ==========
// static/js/map.js:2025-2025
let cardPayLoading: any = false;
// static/js/map.js:2027-2103
export async function tryCardPayOrRedirect() {
if (cardPayLoading || !S.currentOrder) return;
const btn = document.getElementById("order-banner-btn");
cardPayLoading = true;
btn.textContent = "检测中…";
btn.disabled = true;
try {
// 1. 查询可用支付方式
const methodsResp = await fetch(
`/api/order/pay_methods?code=${encodeURIComponent(S.currentOrder.code || "")}`,
{ headers: { "Authorization": `Bearer ${S.authToken}` } }
);
const methodsData = await methodsResp.json();
if (methodsData.rtn_code !== 0) {
// 接口失败,降级提示跳转
showToast("请到小白超人小程序支付订单");
return;
}
const cardMethods = methodsData.data?.card_methods || [];
if (cardMethods.length === 0) {
// 没有月卡/周卡 → 原来逻辑
showToast("未找到月卡,请到小白超人小程序支付");
return;
}
// 2. 优先选 get_type=2(推荐/激活)的卡,否则取第一个
const preferred = cardMethods.find(m => m.get_type === 2) || cardMethods[0];
const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡";
// 3. 更新按钮状态
btn.textContent = `${cardTypeName}支付中…`;
// 4. 调用月卡支付接口
const payResp = await fetch("/api/order/pay_with_card", {
method: "POST",
headers: {
"Authorization": `Bearer ${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 && payData.data?.paid) {
// 月卡支付成功
showToast(`${cardTypeName}支付成功 ✓`);
S.currentOrder = null;
hideOrderBanner();
refreshMap();
} else if (payData.rtn_code === 0 && payData.data?.need_wechat_pay) {
// 月卡不足,需要微信支付
showToast("月卡余额不足,请到小白超人小程序完成支付");
} else {
showToast(payData.message || "支付失败,请到小白超人小程序支付");
}
} catch (err) {
console.error("月卡支付失败:", err);
showToast("请到小白超人小程序支付订单");
} finally {
cardPayLoading = false;
btn.textContent = "去支付";
btn.disabled = false;
}
}
// ========== 还车确认 ==========
// static/js/map.js:2104-2104
let returnLoading: any = false;
// static/js/map.js:2105-2105
let pendingReturnOrder: any = null;
// static/js/map.js:2107-2127
export async function getOrderOperationLocation() {
let position = null;
if (navigator.geolocation) {
position = await new Promise<any>(resolve => {
navigator.geolocation.getCurrentPosition(
pos => resolve(pos),
err => {
console.error("获取位置失败:", err);
resolve(null);
},
{ timeout: 5000 }
);
});
}
const latitude = Number.isFinite(position?.coords?.latitude)
? position.coords.latitude : 36.67;
const longitude = Number.isFinite(position?.coords?.longitude)
? position.coords.longitude : 116.98;
return { latitude, longitude };
}
// static/js/map.js:2129-2142
export 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 = "确认还车";
}
// static/js/map.js:2144-2147
export function closeReturnConfirm() {
document.getElementById("return-confirm-modal").classList.remove("show");
pendingReturnOrder = null;
}
// static/js/map.js:2149-2209
export 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: latitude,
longitude: longitude
})
});
const data = await resp.json();
if (data.rtn_code === 0) {
let msg = data.used_nearest
? "还车成功 · 不在停车区也没关系,已替你记到最近的还车点"
: "还车成功";
// 显示月卡支付结果
if (data.card_pay) {
msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`;
}
showToast(msg);
closeReturnConfirm();
if (!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 = "确认还车";
}
}
// static/js/map.js:2211-2211
let orderTempActionLoading: any = false;
// static/js/map.js:2213-2260
export async function tempLockCurrentOrder() {
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
// 先快照:等定位(最长 5 秒)期间 20 秒轮询可能把 currentOrder 置空,
// 之后再读 currentOrder.order_id 会抛 TypeError 并被吞成「临时锁车失败」。
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 = "临时锁车";
}
}
}
// static/js/map.js:2262-2300
export 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 = "临时开车";
}
}
}
// ========== 一键开锁 ==========
// static/js/map.js:2301-2301
let unlockPendingCode: any = null; // 待开锁的车牌
// static/js/map.js:2302-2302
let unlockPendingPosition: any = null; // 待开锁的位置
// static/js/map.js:2304-2335
export function handleQuickUnlock() {
const qrBox = document.getElementById("qrcode-box");
const code = qrBox.dataset.bikeCode;
if (!code) {
showToast("无法获取车辆编码");
return;
}
if (!S.currentUser) {
showToast("请先登录");
return;
}
// 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位)
// 注意:开二维码弹窗时 startRental 会 closeCard() 把 selectedBike 清空,
// 所以坐标优先从 markersData 按车牌取,避免退化成硬编码的 (36.67, 116.98)。
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 = 0.0001;
unlockPendingCode = code;
unlockPendingPosition = {
lat: baseLat + (Math.random() * 2 - 1) * jit,
lng: baseLng + (Math.random() * 2 - 1) * jit
};
// 有共享绑定 → 先选开锁账号;否则直接确认
openUnlockAccountChooser();
}
// ===== 开锁账号选择(自己 / 共享者列表) =====
// static/js/map.js:2336-2336
let unlockChoice: any = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
// static/js/map.js:2337-2337
let unlockSrcList: any = [];
// static/js/map.js:2338-2338
let unlockSrcShowAll: any = false;
// static/js/map.js:2340-2354
export 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());
}
// static/js/map.js:2356-2375
export 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;
}
// static/js/map.js:2377-2382
export 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); });
}
// static/js/map.js:2384-2394
export 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();
}
// static/js/map.js:2396-2398
export function closeUnlockSrc() {
document.getElementById("unlock-src-modal").classList.remove("show");
}
// static/js/map.js:2400-2411
export 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");
}
// static/js/map.js:2413-2417
export function closeUnlockConfirm() {
document.getElementById("unlock-confirm-modal").classList.remove("show");
unlockPendingCode = null;
unlockPendingPosition = null;
}
// static/js/map.js:2419-2487
export 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: any = {
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);
// closeUnlockConfirm() 会把 unlockPendingCode 清空,先把车牌存到局部变量,
// 否则后面 startRentalFromServer 会把 null 写进 activeRental/localStorage。
const code = unlockPendingCode;
closeUnlockConfirm();
if (data.rtn_code === 0) {
showToast(data.message || "开锁成功!");
closeQrModal();
if (isShared) {
// 共享开锁:横幅由后端订单状态驱动,不启动本地计时
refreshShareBanners();
checkOrderStatus();
} else {
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
const _ud = data.data || {};
startRentalFromServer(data.order_id, code, 19,
_ud.end_time, _ud);
// 刷新订单状态
checkOrderStatus();
}
} else if (data.need_pay) {
// 未支付订单月卡也付不了 → 提示用户并刷新订单横幅
showToast(data.message || "存在未支付订单,请先支付");
checkOrderStatus(); // 刷新横幅显示待支付
} else {
showToast(data.message || "开锁失败");
}
} catch (err) {
console.error("[开锁] 请求失败:", err);
showToast("开锁失败,请重试");
} finally {
btn.disabled = false;
btn.textContent = isShared ? "确认共享开锁" : "确认开锁";
unlockPendingCode = null;
unlockPendingPosition = null;
unlockChoice = { mode: "own", owner_user_id: null, owner_email: null };
}
}
// static/js/map.js:2489-2530
export 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: code,
latitude: latitude,
longitude: longitude
})
});
const data = await resp.json();
console.log("[开锁] 响应:", data); // 调试日志
if (data.rtn_code === 0) {
showToast(data.message || "开锁成功!");
closeQrModal();
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
const _qd = data.data || {};
startRentalFromServer(data.order_id, code, 19, _qd.end_time, _qd);
// 刷新订单状态
checkOrderStatus();
} else {
showToast(data.message || "开锁失败");
}
} catch (err) {
console.error("[开锁] 请求失败:", err); // 调试日志
showToast("开锁失败,请重试");
}
}
// 从后端计时器启动前端计时器(隐藏横幅,由后端控制邮件通知)
// static/js/map.js:2531-2562
export 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));
// 到期动作由后端依据订单类型及用户设置执行
// 这里不需要做任何操作
}
}, 1000);
}
// ========== 忘记密码 ==========
// 忘记密码可从两处打开:弹窗登录(login-modal)与全屏登录门(login-gate)。
// 用 _forgotFromGate 记住入口,重置成功后回到原处,避免用户被"换页面"。
// static/js/map.js:2714-2714
let orderTrajMap: any = null;
// static/js/map.js:2715-2715
let orderTrajOverlays: any = [];
// static/js/map.js:2716-2733
export 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 = "网络错误,请重试";
}
}
// static/js/map.js:2734-2741
export function closeOrderTrajModal(){
SettingsPages.back();
// 保留地图实例,下次复用;只清理覆盖物
if (orderTrajMap) {
try { orderTrajMap.clearOverlays(); } catch(e) {}
}
orderTrajOverlays = [];
}
// static/js/map.js:2742-2817
export function renderOrderTrajectory(t){
const pts = t.points || [];
// textContent 不解析 HTML,这里不能用 escHtml(会把 & 显示成 &amp;)
document.getElementById("order-traj-summary").textContent =
`#${t.bike_code} · ${fmtOrderTime(t.start_time)} → ${fmtOrderTime(t.end_time)} · ` +
`${t.start_label || "起点未知"} → ${t.end_label || (t.returned ? "终点未知" : "骑行中")}`;
const initMap = () => {
if (!orderTrajMap) {
orderTrajMap = new BMapGL.Map("order-traj-map");
orderTrajMap.enableScrollWheelZoom(true);
}
const overlayPts = [];
try { orderTrajMap.clearOverlays(); } catch(e) {}
const toBd = (lat, lng) => offsetCoord(lat, lng);
// 轨迹线(GCJ02 → BD09 逐点转换)
const linePts = pts.map(p => {
const c = toBd(p.lat, p.lng);
return new BMapGL.Point(c.lng, c.lat);
});
// 采集缺失时用订单起终点兜底成两点直线
if (linePts.length < 2 && (t.start_point || t.end_point)) {
const s = t.start_point, e = t.end_point || t.start_point;
const cs = toBd(s.lat, s.lng), ce = toBd(e.lat, e.lng);
linePts.push(new BMapGL.Point(cs.lng, cs.lat), new BMapGL.Point(ce.lng, ce.lat));
}
if (linePts.length >= 2) {
const poly = new BMapGL.Polyline(linePts, {
strokeColor: "#0a84ff", strokeWeight: 5, strokeOpacity: 0.85,
});
orderTrajMap.addOverlay(poly);
overlayPts.push(...linePts);
}
// 起终点标记
const mark = (pt, color, text) => {
if (!pt) return;
const c = toBd(pt.lat, pt.lng);
const p = new BMapGL.Point(c.lng, c.lat);
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 26;
const ctx = canvas.getContext("2d");
ctx.beginPath(); ctx.arc(13, 13, 10, 0, Math.PI * 2);
ctx.fillStyle = color; ctx.fill();
ctx.fillStyle = "#fff"; ctx.font = "bold 12px Arial";
ctx.textAlign = "center"; ctx.textBaseline = "middle";
ctx.fillText(text, 13, 13);
const marker = new BMapGL.Marker(p, {
icon: new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(26, 26), new BMapGL.Size(13, 13))
});
orderTrajMap.addOverlay(marker);
overlayPts.push(p);
};
mark(t.start_point, "#34c759", "起");
mark(t.end_point, "#ff3b30", "终");
if (overlayPts.length) {
try {
orderTrajMap.setViewport(overlayPts, { margins: [30, 30, 30, 30] });
} catch (e) {
orderTrajMap.centerAndZoom(overlayPts[0], 18);
}
} else {
fetch("/api/config").then(r => r.json()).then(cfg => {
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
orderTrajMap.centerAndZoom(new BMapGL.Point(c.lng, c.lat), 17);
});
}
document.getElementById("order-traj-hint").textContent = pts.length
? `共 ${pts.length} 个定位点`
: "该时间段没有采集到定位点(采集间隔 5-10 分钟),已用订单起终点示意";
};
// 弹窗刚显示,等一帧再初始化,避免容器尺寸为 0
setTimeout(initMap, 60);
}
// static/js/map.js:2818-2841
export 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>';
}
}
// static/js/map.js:2842-2848
export function closeOrdersModal() {
SettingsPages.back();
}
// 订阅提醒已拆到 static/js/subscribe.js
// ========== 开锁前预览(月卡余量 + 轮次预估) ==========
// static/js/map.js:2849-2869
export 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";
}
// static/js/map.js:2870-2889
export 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);
}
}
// ========== 手动 +1 轮 ==========
// ========== 手动 +1 轮(带确认弹窗) ==========
// 语义:只把「计划轮数」+1。当前这一轮照常到点 → 自动还车 → 优惠卡支付
// → 立刻重新开锁同一辆车进入下一轮(绝不延长本轮时长)。
// static/js/map.js:2890-2890
let _addRoundTarget: any = null;
// static/js/map.js:2891-2907
export 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");
}
// static/js/map.js:2908-2911
export function closeAddRoundModal() {
document.getElementById("add-round-modal").classList.remove("show");
_addRoundTarget = null;
}
// static/js/map.js:2912-2945
export 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();
}
}
// static/js/map.js:2946-2949
export function addRoundForCurrent() {
if (!S.activeRental || !S.authToken) { showToast("当前没有进行中的订单"); return; }
showAddRoundConfirm({ kind: "rental", value: S.activeRental.rental_id });
}
// static/js/map.js:2950-2954
export function addRoundFromBanner() {
if (!S.currentOrder || !S.currentOrder.order_id) { showToast("当前没有进行中的订单"); return; }
showAddRoundConfirm({ kind: "order", value: S.currentOrder.order_id });
}
// 页面加载时检查订单状态和租车状态
// static/js/map.js:3482-3579
export 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;
// 优先用 markersData 的实时位置,其次用 API 返回的位置
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);
}
// success=false 时,也尝试用 markersData 显示详情和定位
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);
// toast 提示
showToast(data.message || "该车辆已被使用");
} else {
showToast(data.message || "查询失败");
}
}
else {
showToast(data.message || "查询失败");
}
})
.catch(err => showToast("请求失败: " + friendlyError(err)));
}
// ========== 寻车功能 ==========
// ----- 丢失模式状态 -----
// static/js/map.js:3580-3580
export let _lostModeActive: any = false; // 是否处于丢失模式
// static/js/map.js:3581-3581
let _lostModeTimer: any = null; // setInterval 句柄
// static/js/map.js:3583-3583
export let _findClickTimer: any = null; // 连续点击重置计时器
// static/js/map.js:3585-3585
const LOST_TRIGGER_CLICKS = 3; // 连续点击 N 次触发
// static/js/map.js:3586-3586
export const LOST_TRIGGER_LONG = 700; // 长按毫秒数触发
// static/js/map.js:3587-3589
const LOST_INTERVAL = 3000; // 丢失模式下每次寻车间隔(ms)
/** 发送单次寻车请求(内部使用,不操作按钮状态) */
// static/js/map.js:3590-3601
export function _doFindBikeRequest(code) {
return fetch("/api/find_bike", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${S.authToken}`
},
body: JSON.stringify({ code: code, school_id: 10 })
}).then(r => r.json()).catch(() => null);
}
/** 打开丢失模式确认弹窗 */
// static/js/map.js:3602-3606
export function showLostModal() {
document.getElementById("lost-modal").classList.add("show");
}
/** 关闭丢失模式确认弹窗(不启用) */
// static/js/map.js:3607-3611
export function closeLostModal() {
document.getElementById("lost-modal").classList.remove("show");
}
/** 启用丢失模式(弹窗确认后调用) */
// static/js/map.js:3612-3642
export 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);
}
/** 停止丢失模式 */
// static/js/map.js:3643-3663
export 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("丢失模式已关闭");
}
// static/js/map.js:3665-3665
export function _onPageUnload() { disableLostMode(); }
// static/js/map.js:3666-3675
export function _onVisibilityChange() {
if (document.visibilityState === "hidden") disableLostMode();
}
/**
* 主寻车入口(绑定到按钮 onclick)
* - 丢失模式激活时:点击直接关闭丢失模式
* - 连续点击 LOST_TRIGGER_CLICKS 次:触发丢失模式弹窗
* - 否则:正常寻车
*/
// static/js/map.js:3676-3726
export 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 = "寻车";
}
});
}
// ===== 长按触发丢失模式 =====
// static/js/map.js:3756-3765
export 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");
}
// static/js/map.js:3767-3787
export 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));
}
}
// static/js/map.js:3789-3789
export function closeRentalSettingsModal() { SettingsPages.back(); }
// static/js/map.js:3791-3814
export 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));
}
}
// static/js/map.js:3816-3846
export 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) {
// 真实订单走订单横幅(checkOrderStatus / fetchOrderCountdown 驱动),
// 本地计时条只承载 reminder 计时
clearRentalState();
}
} catch (err) {
console.error("[syncWechatOrder] 同步失败:", err);
}
}
// static/js/map.js:3848-3892
export 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;
// 剩余时间 <= 0 也视为无活跃
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));
}
// static/js/map.js:3894-3938
export 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 = new Date();
const endTime = new Date(now.getTime() + data.data.remaining_seconds * 1000);
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);
});
}
// static/js/map.js:3940-3957
export function showRentalBar() {
if (!S.activeRental) return;
const bar = document.getElementById("rental-bar");
document.getElementById("rental-bike-code").textContent = `#${S.activeRental.bike_code}`;
// +1轮 按钮仅对真实微信订单展示(reminder 计时不支持)
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, 1000);
}
// static/js/map.js:3959-3970
export 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";
}
}
// static/js/map.js:3972-3997
export 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, 60000);
}
}
// static/js/map.js:3999-4003
export function showReturnModal() {
if (!S.activeRental) return;
document.getElementById("return-bike-code").textContent = `#${S.activeRental.bike_code}`;
document.getElementById("return-modal").classList.add("show");
}
// static/js/map.js:4005-4007
export function closeReturnModal() {
document.getElementById("return-modal").classList.remove("show");
}
// static/js/map.js:4009-4039
export 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("网络错误,请检查网络后重试");
}
}
// 原生壳(Android)判定:UA 由 Android WebView 注入 xbniu-native,head 脚本已给 <html> 加 in-native-shell
// static/js/map.js:4040-4043
export function isNativeShell() {
return document.documentElement && document.documentElement.classList.contains('in-native-shell');
}
// 网页点“开锁用车”时,把开锁交给安卓原生(原生里选账号/共享并开锁);返回 true 表示已交给原生
// static/js/map.js:4044-4052
export 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;
}
// static/js/map.js:4054-4084
export 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("该车已损坏,无法使用"); // 上游 state=2 表示损坏,不是被预约
closeCard();
return;
}
// 原生壳:点击即交给安卓原生开锁(账号选择在原生 BikeDetailActivity),不在此出网页二维码
if (nativeUnlockBike(S.selectedBike.code)) {
return;
}
// 网页端默认:显示二维码弹窗(长按二维码才开始计时)
showQrModal(S.selectedBike.code);
}
// 显示二维码弹窗(适配微信扫码 - img格式)