// ========== 订单状态检测 ========== let currentOrder = null; // 当前订单信息 async function checkOrderStatus() { if (!authToken) { hideOrderBanner(); return; } try { const resp = await apiFetch("/api/order/status", { headers: { "Authorization": `Bearer ${authToken}` } }); const data = await resp.json(); if (data.rtn_code === 0) { if (!data.has_credentials) { // 用户没有配置凭据 hideOrderBanner(); return; } if (data.has_order && data.order) { currentOrder = data.order; // 仅当“当前微信订单本身就是我共享出去的这笔订单”时隐藏普通横幅。 // 骑行者自己账号另有待支付/进行中订单时,必须与借用中的共享横幅同时保留。 if (data.order.shared) { hideOrderBanner(); } else { showOrderBanner(data.order); } } else { currentOrder = null; hideOrderBanner(); } } else if (data.rtn_code === 102001 || data.token_invalid) { // token_id 已失效(小程序重新登录会踢掉旧会话):弹窗引导重新配置(带冷却,避免每20秒轮询骚扰) notifyCredentialInvalid(data.message); } } catch (err) { console.error("检查订单状态失败:", err); } } function showOrderBanner(order) { const banner = document.getElementById("order-banner"); const icon = document.getElementById("order-banner-icon"); const text = document.getElementById("order-banner-text"); const btn = document.getElementById("order-banner-btn"); banner.classList.remove("warning", "riding"); if (Number(order.status) === 1) { // 待支付 banner.classList.add("warning"); icon.innerHTML = ''; 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 = ''; if (order.shared) { const sName = partnerLabel(order.shared.rider_name, order.shared.rider_email, order.shared.remark); text.textContent = ("共享中 #" + (order.code || order.order_id.slice(-6)) + " · " + sName + "使用中"); } else { text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`; } btn.textContent = "还车"; if (String(orderCountdownOrderId) !== String(order.order_id)) { hideOrderCountdown(); const progress = document.getElementById("order-final-time"); progress.textContent = "骑行中 · 正在同步计时"; progress.style.display = "inline"; } // 从后端获取剩余时间并启动倒计时 fetchOrderCountdown(order.order_id); } banner.classList.add("show"); } let orderCountdownTimer = null; let orderCountdownSeconds = 0; let orderCountdownDeadline = null; let orderCountdownOrderId = null; function rideProgressText(summary) { const current = Math.max(1, Number(summary.current_round) || 1); const total = Math.max(current, Number(summary.total_rounds) || current); const end = String(summary.final_end_time || summary.end_time || "").match(/(?:T|\s)(\d{2}:\d{2})/); const phase = summary.auto_return ? "自动还车已开启" : "手动还车"; return `第 ${current}/${total} 轮 · ${phase}` + (end ? ` · 预计 ${end[1]} 结束` : ""); } function remainingTimeText(seconds) { const remaining = Math.max(0, Math.ceil(Number(seconds) || 0)); return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`; } function fetchOrderCountdown(orderId) { if (!authToken || !orderId) return; apiFetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, { headers: { "Authorization": `Bearer ${authToken}` } }) .then(r => r.json()) .then(data => { if (!currentOrder || String(currentOrder.order_id) !== String(orderId) || Number(currentOrder.status) !== 2) return; if (data.rtn_code === 0 && data.data && data.data.active) { orderCountdownSeconds = Math.max(0, Number(data.data.remaining_seconds) || 0); orderCountdownDeadline = performance.now() + orderCountdownSeconds * 1000; orderCountdownOrderId = orderId; // 多轮适配:展示计划总轮数与最终预计还车时间 const finalEl = document.getElementById("order-final-time"); const addBtn = document.getElementById("order-banner-add-round-btn"); if (finalEl) { finalEl.textContent = rideProgressText(data.data); finalEl.style.display = "inline"; } if (addBtn) { // 真实订单才可加轮; reminder 计时不显示 const eligible = data.data.order_id && String(data.data.source) !== "reminder"; addBtn.style.display = eligible ? "inline-block" : "none"; } showOrderCountdown(); startOrderCountdown(); } else if (data.rtn_code === 0) { hideOrderCountdown(); const progress = document.getElementById("order-final-time"); progress.textContent = "骑行中 · 计时同步中"; progress.style.display = "inline"; } }) .catch(err => console.error("获取倒计时失败:", err)); } function showOrderCountdown() { const el = document.getElementById("order-countdown"); el.style.display = "inline"; updateOrderCountdownText(); } function hideOrderCountdown() { orderCountdownDeadline = null; orderCountdownOrderId = null; document.getElementById("order-banner-add-round-btn").style.display = "none"; document.getElementById("order-final-time").style.display = "none"; const el = document.getElementById("order-countdown"); el.style.display = "none"; if (orderCountdownTimer) { clearInterval(orderCountdownTimer); orderCountdownTimer = null; } } function updateOrderCountdownText() { const el = document.getElementById("order-countdown"); const remaining = Math.max(0, orderCountdownSeconds); const mins = Math.floor(remaining / 60); const secs = remaining % 60; el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中"; // 变色提示 if (remaining <= 60) { el.style.color = "#ff3b30"; } else if (remaining <= 300) { el.style.color = "#ffcc00"; } else { el.style.color = "white"; } } function startOrderCountdown() { if (orderCountdownTimer) clearInterval(orderCountdownTimer); orderCountdownTimer = setInterval(() => { orderCountdownSeconds = Math.max(0, Math.ceil((orderCountdownDeadline - performance.now()) / 1000)); updateOrderCountdownText(); if (orderCountdownSeconds <= 0) { clearInterval(orderCountdownTimer); // 倒计时结束,刷新订单状态 checkOrderStatus(); } }, 1000); } function hideOrderBanner() { document.getElementById("order-banner").classList.remove("show"); hideOrderCountdown(); closeOrderActionsModal(); } function isOrderActionEligible(order) { if (!order) return false; const type = String(order.type || "").toLowerCase(); const source = String(order.source || "").toLowerCase(); return type !== "reminder" && source !== "reminder"; } function handleOrderBannerSurfaceClick(event) { // 横幅右侧已有的两个按钮继续走原有行为,不触发全屏面板。 if (event && event.target && event.target.closest && event.target.closest("button")) return; if (!isOrderActionEligible(currentOrder)) return; showOrderActionsModal(); } function showOrderActionsModal() { if (!isOrderActionEligible(currentOrder)) return; const modal = document.getElementById("order-actions-modal"); const meta = document.getElementById("order-actions-meta"); const status = document.getElementById("order-actions-status"); const hint = document.getElementById("order-actions-hint"); const code = currentOrder.code || currentOrder.order_id || "未知"; const pending = Number(currentOrder.status) === 1; meta.textContent = `车辆 #${code}`; status.textContent = pending ? "待支付订单" : "订单进行中"; status.classList.toggle("warning", pending); status.classList.toggle("riding", !pending); hint.textContent = pending ? "当前订单尚未支付,请先完成支付后再使用车辆操作。" : "临时锁车不会结束订单,确认车辆停放安全后再操作。"; // 待支付订单明确不展示临时锁车/临时开车。 ["order-action-lock", "order-action-unlock"].forEach(id => { const button = document.getElementById(id); if (button) button.style.display = pending ? "none" : "flex"; }); const pay = document.getElementById("order-action-pay"); const ret = document.getElementById("order-action-return"); if (pay) pay.style.display = pending ? "flex" : "none"; if (ret) ret.style.display = pending ? "none" : "flex"; modal.classList.add("show"); modal.setAttribute("aria-hidden", "false"); document.body.classList.add("order-actions-open"); window.setTimeout(() => document.getElementById("order-actions-close")?.focus(), 0); } function closeOrderActionsModal() { const modal = document.getElementById("order-actions-modal"); if (!modal) return; modal.classList.remove("show"); modal.setAttribute("aria-hidden", "true"); document.body.classList.remove("order-actions-open"); } function viewBikeDetailFromOrderModal() { closeOrderActionsModal(); viewBikeDetailFromOrder(); } async function findCurrentOrderBike() { if (!isOrderActionEligible(currentOrder)) return; const code = (currentOrder.code || "").toString().trim(); if (!code) { showToast("该订单没有车牌信息"); return; } const button = document.getElementById("order-action-find"); if (button) { button.disabled = true; button.querySelector("strong").textContent = "发送中..."; } try { const data = await _doFindBikeRequest(code); if (data && (data.rtn_code === 0 || data.success)) { showToast("寻车指令已发送,请听声音"); } else { showToast((data && data.message) || "寻车失败"); } } catch (err) { console.error("订单寻车失败:", err); showToast("寻车失败,请重试"); } finally { if (button) { button.disabled = false; button.querySelector("strong").textContent = "寻车"; } } } function payCurrentOrderFromModal() { closeOrderActionsModal(); tryCardPayOrRedirect(); } function returnCurrentOrderFromModal() { closeOrderActionsModal(); showReturnConfirm(); } function handleOrderBannerClick() { if (!currentOrder) { showToast("订单状态已变化,正在刷新,请稍后重试"); checkOrderStatus(); return; } if (Number(currentOrder.status) === 1) { // 待支付 - 先检查是否有月卡/周卡 tryCardPayOrRedirect(); } else if (Number(currentOrder.status) === 2) { // 进行中 - 显示还车确认弹窗 showReturnConfirm(); } else { showToast("订单状态已变化,正在刷新,请稍后重试"); checkOrderStatus(); } } // 查看详情:等同在搜索框输入当前订单车牌并点击查询,直接弹出车辆详情 function viewBikeDetailFromOrder() { if (!currentOrder) { showToast("当前没有进行中的订单"); return; } const code = (currentOrder.code || "").toString().trim(); if (!code) { showToast("该订单没有车牌信息"); return; } document.getElementById("scan-input").value = code; scanCode(); } document.addEventListener("keydown", event => { if (event.key !== "Escape") return; // 确认弹窗优先响应 ESC(原生壳没有系统对话框,全靠页面内弹窗) const _cm = document.getElementById("app-confirm-modal"); if (_cm && _cm.classList.contains("show")) { appConfirmClose(); return; } const _arm = document.getElementById("add-round-modal"); if (_arm && _arm.classList.contains("show")) { closeAddRoundModal(); return; } const _oam = document.getElementById("order-actions-modal"); if (_oam && _oam.classList.contains("show")) { closeOrderActionsModal(); return; } }); // ========== 月卡/周卡自动支付 ========== let cardPayLoading = false; async function tryCardPayOrRedirect() { if (cardPayLoading || !currentOrder) return; const btn = document.getElementById("order-banner-btn"); cardPayLoading = true; btn.textContent = "检测中…"; btn.disabled = true; try { // 1. 查询可用支付方式 const methodsResp = await apiFetch( `/api/order/pay_methods?code=${encodeURIComponent(currentOrder.code || "")}`, { headers: { "Authorization": `Bearer ${authToken}` } } ); const methodsData = await methodsResp.json(); if (methodsData.rtn_code !== 0) { // 接口失败,降级提示跳转 showToast("请到小白超人小程序支付订单"); return; } const cardMethods = methodsData.data?.card_methods || []; if (cardMethods.length === 0) { // 没有月卡/周卡 → 原来逻辑 showToast("未找到月卡,请到小白超人小程序支付"); return; } // 2. 优先选 get_type=2(推荐/激活)的卡,否则取第一个 const preferred = cardMethods.find(m => m.get_type === 2) || cardMethods[0]; const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡"; // 3. 更新按钮状态 btn.textContent = `${cardTypeName}支付中…`; // 4. 调用月卡支付接口 const payResp = await apiFetch("/api/order/pay_with_card", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ order_id: currentOrder.order_id, code: currentOrder.code || "", type: String(preferred.type), package_id: String(preferred.package_id) }) }); const payData = await payResp.json(); if (payData.rtn_code === 0 && payData.data?.paid) { // 月卡支付成功 showToast(`${cardTypeName}支付成功 ✓`); currentOrder = null; hideOrderBanner(); refreshMap(); } else if (payData.rtn_code === 0 && payData.data?.need_wechat_pay) { // 月卡不足,需要微信支付 showToast("月卡余额不足,请到小白超人小程序完成支付"); } else { showToast(payData.message || "支付失败,请到小白超人小程序支付"); } } catch (err) { console.error("月卡支付失败:", err); showToast("请到小白超人小程序支付订单"); } finally { cardPayLoading = false; btn.textContent = "去支付"; btn.disabled = false; } } // ========== 还车确认 ========== let returnLoading = false; let pendingReturnOrder = null; async function getOrderOperationLocation() { let position = null; if (navigator.geolocation) { position = await new Promise(resolve => { navigator.geolocation.getCurrentPosition( pos => resolve(pos), err => { console.error("获取位置失败:", err); resolve(null); }, { timeout: 5000 } ); }); } const latitude = Number.isFinite(position?.coords?.latitude) ? position.coords.latitude : 36.67; const longitude = Number.isFinite(position?.coords?.longitude) ? position.coords.longitude : 116.98; return { latitude, longitude }; } function showReturnConfirm() { if (returnLoading) return; if (!currentOrder || Number(currentOrder.status) !== 2) { showToast("当前没有可还车的进行中订单,正在刷新"); checkOrderStatus(); return; } pendingReturnOrder = { ...currentOrder }; document.getElementById("return-confirm-text").textContent = `车辆 #${currentOrder.code || currentOrder.order_id} 正在骑行,确认要还车吗?`; document.getElementById("return-confirm-modal").classList.add("show"); document.getElementById("return-confirm-btn").disabled = false; document.getElementById("return-confirm-btn").textContent = "确认还车"; } function closeReturnConfirm() { document.getElementById("return-confirm-modal").classList.remove("show"); pendingReturnOrder = null; } async function doReturnBike() { if (returnLoading) return; const order = pendingReturnOrder; if (!order) { showToast("请重新点击还车并确认订单"); return; } returnLoading = true; const btn = document.getElementById("return-confirm-btn"); btn.disabled = true; btn.textContent = "还车中..."; try { // 还车和临时锁车共用同一套当前位置获取逻辑。 const { latitude, longitude } = await getOrderOperationLocation(); const resp = await apiFetch("/api/order/return", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ order_id: order.order_id, code: order.code, latitude: latitude, longitude: longitude }) }); const data = await resp.json(); if (data.rtn_code === 0) { let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功"; // 显示月卡支付结果 if (data.card_pay) { msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`; } showToast(msg); closeReturnConfirm(); if (!currentOrder || String(currentOrder.order_id) === String(order.order_id)) { currentOrder = null; hideOrderBanner(); } // 刷新地图 refreshMap(); refreshShareBanners(); } else { showToast(data.message || "还车失败"); } } catch (err) { showToast("还车失败,请重试"); } finally { returnLoading = false; btn.disabled = false; btn.textContent = "确认还车"; } } let orderTempActionLoading = false; async function tempLockCurrentOrder() { if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return; const button = document.getElementById("order-action-lock"); orderTempActionLoading = true; if (button) { button.disabled = true; button.querySelector("strong").textContent = "锁车中..."; } try { const { latitude, longitude } = await getOrderOperationLocation(); const resp = await apiFetch("/api/order/temp_lock", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ order_id: currentOrder.order_id, code: currentOrder.code, latitude, longitude }) }); const data = await resp.json(); if (data.rtn_code === 0) { showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功"); const status = document.getElementById("order-actions-status"); if (status) status.textContent = "车辆已临时锁定,订单仍在进行中"; } else { showToast(data.message || "临时锁车失败"); } } catch (err) { console.error("临时锁车失败:", err); showToast("临时锁车失败,请重试"); } finally { orderTempActionLoading = false; if (button) { button.disabled = false; button.querySelector("strong").textContent = "临时锁车"; } } } async function tempUnlockCurrentOrder() { if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return; const button = document.getElementById("order-action-unlock"); orderTempActionLoading = true; if (button) { button.disabled = true; button.querySelector("strong").textContent = "开车中..."; } try { const resp = await apiFetch("/api/order/temp_unlock", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ order_id: currentOrder.order_id }) }); const data = await resp.json(); if (data.rtn_code === 0) { showToast(data.message || "临时开车成功"); const status = document.getElementById("order-actions-status"); if (status) status.textContent = "车辆正在解锁,请稍候"; } else { showToast(data.message || "临时开车失败"); } } catch (err) { console.error("临时开车失败:", err); showToast("临时开车失败,请重试"); } finally { orderTempActionLoading = false; if (button) { button.disabled = false; button.querySelector("strong").textContent = "临时开车"; } } } // ========== 一键开锁 ========== let unlockPendingCode = null; // 待开锁的车牌 let unlockPendingPosition = null; // 待开锁的位置 function handleQuickUnlock() { const qrBox = document.getElementById("qrcode-box"); const code = qrBox.dataset.bikeCode; if (!code) { showToast("无法获取车辆编码"); return; } if (!currentUser) { showToast("请先登录"); return; } // 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位) const baseLat = parseFloat(selectedBike?.latitude) || 36.67; const baseLng = parseFloat(selectedBike?.longitude) || 116.98; const jit = 0.0001; unlockPendingCode = code; unlockPendingPosition = { lat: baseLat + (Math.random() * 2 - 1) * jit, lng: baseLng + (Math.random() * 2 - 1) * jit }; // 有共享绑定 → 先选开锁账号;否则直接确认 openUnlockAccountChooser(); } // ===== 开锁账号选择(自己 / 共享者列表) ===== let unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; let unlockSrcList = []; let unlockSrcShowAll = false; function openUnlockAccountChooser() { unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; unlockSrcShowAll = false; if (!authToken || !currentUser) { proceedToUnlockConfirm(); return; } apiFetch("/api/share/sources", { headers: { "Authorization": "Bearer " + authToken } }) .then(r => r.json()) .then(data => { if (data.rtn_code !== 0 || !data.data) { proceedToUnlockConfirm(); return; } const d = data.data; if (!d.has_any) { proceedToUnlockConfirm(); return; } renderUnlockSrcList(d); document.getElementById("unlock-src-modal").classList.add("show"); }) .catch(() => proceedToUnlockConfirm()); } function renderUnlockSrcList(d) { const box = document.getElementById("unlock-src-list"); let html = ""; html += ''; const srcs = d.sources || []; unlockSrcList = srcs.slice(); if (srcs.length === 0 && d.hidden_count > 0) { html += '
共享者今日次数都已用完,可查看或直接用自己的账号。
'; } 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 += ''; }); if (d.hidden_count > 0) { html += '还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)'; } box.innerHTML = html; } function loadUnlockSrcShowAll() { unlockSrcShowAll = true; apiFetch("/api/share/sources?show_unavailable=1", { headers: { "Authorization": "Bearer " + authToken } }) .then(r => r.json()) .then(data => { if (data.rtn_code === 0) renderUnlockSrcList(data.data); }); } function chooseUnlockSrc(ownerId) { ownerId = ownerId || 0; const rec = unlockSrcList.find(x => Number(x.owner_user_id) === Number(ownerId)); if (ownerId && !rec) { closeUnlockSrc(); return; } unlockChoice = rec ? { mode: "shared", owner_user_id: rec.owner_user_id, owner_email: rec.owner_email, owner_display: partnerLabel(rec.owner_name, rec.owner_email, rec.remark) } : { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; closeUnlockSrc(); proceedToUnlockConfirm(); } function closeUnlockSrc() { document.getElementById("unlock-src-modal").classList.remove("show"); } function proceedToUnlockConfirm() { if (!unlockPendingCode) return; const btn = document.getElementById("unlock-confirm-btn"); btn.disabled = false; btn.textContent = unlockChoice.mode === "shared" ? ("确认用 " + (unlockChoice.owner_display || "对方") + " 的共享开锁") : "确认开锁"; // 开锁前预览:月卡余量 + 自动续租轮次预估(共享单用车主的卡) loadUnlockPreview(unlockPendingCode, unlockChoice.mode === "shared" ? unlockChoice.owner_user_id : null); document.getElementById("unlock-confirm-modal").classList.add("show"); } function closeUnlockConfirm() { document.getElementById("unlock-confirm-modal").classList.remove("show"); unlockPendingCode = null; unlockPendingPosition = null; } async function doUnlockBike() { if (!unlockPendingCode || !authToken) { closeUnlockConfirm(); return; } const btn = document.getElementById("unlock-confirm-btn"); btn.disabled = true; btn.textContent = "开锁中..."; const isShared = unlockChoice && unlockChoice.mode === "shared"; try { const payload = { code: unlockPendingCode, latitude: unlockPendingPosition.lat, longitude: unlockPendingPosition.lng }; if (isShared) payload.owner_user_id = unlockChoice.owner_user_id; const resp = await apiFetch(isShared ? "/api/order/shared_unlock" : "/api/order/unlock", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const data = await resp.json(); console.log("[开锁] 响应:", data); closeUnlockConfirm(); if (data.rtn_code === 0) { showToast(data.message || "开锁成功!"); closeQrModal(); if (isShared) { // 共享开锁:横幅由后端订单状态驱动,不启动本地计时 refreshShareBanners(); checkOrderStatus(); } else { // 启动前端计时器;end_time/轮次预估取自后端开锁响应 const _ud = data.data || {}; startRentalFromServer(data.order_id, unlockPendingCode, 19, _ud.end_time, _ud); // 刷新订单状态 checkOrderStatus(); } } else if (data.need_pay) { // 未支付订单月卡也付不了 → 提示用户并刷新订单横幅 showToast(data.message || "存在未支付订单,请先支付"); checkOrderStatus(); // 刷新横幅显示待支付 } else { showToast(data.message || "开锁失败"); } } catch (err) { console.error("[开锁] 请求失败:", err); showToast("开锁失败,请重试"); } finally { btn.disabled = false; btn.textContent = isShared ? "确认共享开锁" : "确认开锁"; unlockPendingCode = null; unlockPendingPosition = null; unlockChoice = { mode: "own", owner_user_id: null, owner_email: null }; } } async function quickUnlock(code, latitude, longitude) { if (!authToken) { showToast("请先登录"); return; } try { const resp = await apiFetch("/api/order/unlock", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ code: code, latitude: latitude, longitude: longitude }) }); const data = await resp.json(); console.log("[开锁] 响应:", data); // 调试日志 if (data.rtn_code === 0) { showToast(data.message || "开锁成功!"); closeQrModal(); // 启动前端计时器;end_time/轮次预估取自后端开锁响应 const _qd = data.data || {}; startRentalFromServer(data.order_id, code, 19, _qd.end_time, _qd); // 刷新订单状态 checkOrderStatus(); } else { showToast(data.message || "开锁失败"); } } catch (err) { console.error("[开锁] 请求失败:", err); // 调试日志 showToast("开锁失败,请重试"); } } // 从后端计时器启动前端计时器(隐藏横幅,由后端控制邮件通知) function startRentalFromServer(rentalId, bikeCode, durationMinutes, endTime, summary) { // 启动本地计时器(不显示横幅,由后端统一管理) const remaining = durationMinutes * 60; activeRental = { rental_id: rentalId, bike_code: bikeCode, remaining_seconds: remaining, source: "unlock", // 网页开锁 → 真实订单,+1轮可用 end_time: endTime || null, final_end_time: (summary && summary.final_end_time) || endTime || null, current_round: (summary && summary.current_round) || 1, total_rounds: (summary && summary.total_rounds) || null, auto_return: true }; localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); // 启动倒计时更新(每秒) if (rentalCountdownTimer) clearInterval(rentalCountdownTimer); rentalCountdownTimer = setInterval(() => { if (activeRental && activeRental.remaining_seconds > 0) { activeRental.remaining_seconds--; localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); // 到期动作由后端依据订单类型及用户设置执行 // 这里不需要做任何操作 } }, 1000); } // ========== 开锁前预览(月卡余量 + 轮次预估) ========== function renderUnlockPreview(p) { const box = document.getElementById("unlock-preview"); if (!box) return; if (!p) { box.style.display = "none"; box.innerHTML = ""; return; } const lines = []; lines.push(`
${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}
`); if (p.has_card) { const cardText = (p.cards || []).slice(0, 3).map(c => `${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(","); lines.push(`
优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}
`); } else { lines.push(`
未检测到优惠卡:本次费用将按小程序计费(还车后需支付)
`); } if (p.auto_return) { lines.push(`
自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车
`); } else { lines.push(`
自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车
`); } 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 = '
预览加载中...
'; } try { const q = new URLSearchParams({ code: String(code) }); if (ownerUserId) q.set("owner_user_id", ownerUserId); const resp = await apiFetch(`/api/order/preview?${q.toString()}`, { headers: { "Authorization": `Bearer ${authToken}` } }); const data = await resp.json(); renderUnlockPreview(data.rtn_code === 0 ? data.data : null); } catch (err) { renderUnlockPreview(null); } } // ========== 手动 +1 轮 ========== // ========== 手动 +1 轮(带确认弹窗) ========== // 语义:只把「计划轮数」+1。当前这一轮照常到点 → 自动还车 → 优惠卡支付 // → 立刻重新开锁同一辆车进入下一轮(绝不延长本轮时长)。 let _addRoundTarget = null; function showAddRoundConfirm(target) { _addRoundTarget = target; const remainSec = target.kind === "rental" ? (activeRental && activeRental.remaining_seconds) || orderCountdownSeconds || 0 : orderCountdownSeconds || 0; const mins = Math.max(1, Math.round(remainSec / 60)); const btn = document.getElementById("add-round-confirm-btn"); if (btn) { btn.disabled = false; btn.textContent = "确认加 1 轮"; } const text = document.getElementById("add-round-text"); if (text) { text.innerHTML = `当前这一轮还剩约 ${mins} 分钟,不会延长。
` + `到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`; } document.getElementById("add-round-modal").classList.add("show"); } function closeAddRoundModal() { document.getElementById("add-round-modal").classList.remove("show"); _addRoundTarget = null; } async function confirmAddRound() { if (!_addRoundTarget || !authToken) { closeAddRoundModal(); return; } const btn = document.getElementById("add-round-confirm-btn"); if (btn) { btn.disabled = true; btn.textContent = "提交中..."; } const payload = _addRoundTarget.kind === "rental" ? { rental_id: _addRoundTarget.value } : { order_id: _addRoundTarget.value }; try { const resp = await apiFetch("/api/order/add_round", { method: "POST", headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const data = await resp.json(); if (data.rtn_code === 0) { showToast(data.message || "已加 1 轮"); // 本轮剩余不变,只更新计划轮数与预计还车时间 if (activeRental) { activeRental.total_rounds = data.data.total_rounds; activeRental.final_end_time = data.data.final_end_time; localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); updateRentalFinalTime(); } if (currentOrder && currentOrder.order_id) fetchOrderCountdown(currentOrder.order_id); checkOrderStatus(); } else { showToast(data.message || "加轮失败"); } } catch (err) { showToast("网络错误,请重试"); } finally { closeAddRoundModal(); } } function addRoundForCurrent() { if (!activeRental || !authToken) { showToast("当前没有进行中的订单"); return; } showAddRoundConfirm({ kind: "rental", value: activeRental.rental_id }); } function addRoundFromBanner() { if (!currentOrder || !currentOrder.order_id) { showToast("当前没有进行中的订单"); return; } showAddRoundConfirm({ kind: "order", value: currentOrder.order_id }); } // 页面加载时检查订单状态和租车状态 document.addEventListener("DOMContentLoaded", async () => { if (authToken) { await syncWechatOrder(); // 先同步微信订单状态 checkOrderStatus(); checkRentalStatus(); // 再恢复租车横幅 checkStrictGuide(); // 强签名验证:缺 AccessToken 进页面立即引导 refreshAuthExpiry(); // 登录态有效期:不足 2 天在主页面挂提醒横幅 } });