1280 lines
53 KiB
JavaScript
1280 lines
53 KiB
JavaScript
// ========== 登录认证 ==========
|
||
function handleAuthBtnClick() {
|
||
if (currentUser) {
|
||
// 已登录,显示个人中心
|
||
showProfileModal();
|
||
} else {
|
||
// 未登录,显示登录弹窗
|
||
showLoginModal();
|
||
}
|
||
}
|
||
|
||
function showLoginModal() {
|
||
closeAllModals();
|
||
document.getElementById("login-modal").classList.add("show");
|
||
document.getElementById("login-email").focus();
|
||
}
|
||
|
||
function closeLoginModal() {
|
||
document.getElementById("login-modal").classList.remove("show");
|
||
document.getElementById("login-tip").textContent = "";
|
||
}
|
||
|
||
function showRegisterModal() {
|
||
closeLoginModal();
|
||
closeRegisterModal();
|
||
document.getElementById("register-modal").classList.add("show");
|
||
document.getElementById("register-email").focus();
|
||
}
|
||
|
||
function closeRegisterModal() {
|
||
document.getElementById("register-modal").classList.remove("show");
|
||
document.getElementById("register-tip").textContent = "";
|
||
}
|
||
|
||
function openSettingsPage() {
|
||
closeAllModals();
|
||
document.getElementById("settings-clustering").checked = bikeClusteringEnabled;
|
||
document.getElementById("settings-save-status").textContent = "地图偏好自动保存在当前设备,即时生效。";
|
||
SettingsPages.open("settings-modal");
|
||
loadProfileData();
|
||
}
|
||
|
||
function closeSettingsPage() { SettingsPages.back(); }
|
||
|
||
function saveMapClusteringSetting(enabled) {
|
||
if (typeof BikeClusters === "undefined") {
|
||
showToast("地图组件未加载,请刷新页面后重试");
|
||
return;
|
||
}
|
||
bikeClusteringEnabled = !!enabled;
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled);
|
||
const saved = BikeClusters.writeClusteringPreference(localStorage, bikeClusteringEnabled);
|
||
document.getElementById("settings-save-status").textContent = saved
|
||
? (bikeClusteringEnabled ? "已开启车辆聚类,设置已保存。" : "已关闭聚类,所有车辆单独显示。设置已保存。")
|
||
: "设置已生效,当前浏览器无法保存,刷新后会恢复默认。";
|
||
}
|
||
|
||
window.addEventListener("storage", event => {
|
||
if (typeof BikeClusters === "undefined") return;
|
||
if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return;
|
||
bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage);
|
||
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled);
|
||
document.getElementById("settings-clustering").checked = bikeClusteringEnabled;
|
||
});
|
||
|
||
function showProfileModal() { openSettingsPage(); }
|
||
|
||
function closeProfileModal() { SettingsPages.close(); }
|
||
|
||
function closeAllModals() {
|
||
if (typeof SettingsPages !== "undefined") SettingsPages.hide();
|
||
document.getElementById("login-modal").classList.remove("show");
|
||
document.getElementById("register-modal").classList.remove("show");
|
||
document.getElementById("settings-modal").classList.remove("show");
|
||
document.getElementById("rental-settings-modal").classList.remove("show");
|
||
document.getElementById("devices-modal").classList.remove("show");
|
||
document.getElementById("auth-modal").classList.remove("show");
|
||
document.getElementById("packages-modal").classList.remove("show");
|
||
const forgot = document.getElementById("forgot-modal");
|
||
if (forgot) forgot.classList.remove("show");
|
||
const orders = document.getElementById("orders-modal");
|
||
if (orders) orders.classList.remove("show");
|
||
const subscribe = document.getElementById("subscribe-modal");
|
||
if (subscribe) subscribe.classList.remove("show");
|
||
const traj = document.getElementById("order-traj-modal");
|
||
if (traj) traj.classList.remove("show");
|
||
const _armc = document.getElementById("add-round-modal");
|
||
if (_armc) _armc.classList.remove("show");
|
||
const _srm = document.getElementById("share-return-modal");
|
||
if (_srm) _srm.classList.remove("show");
|
||
appConfirmClose(); // 视为「取消」,避免 Promise 悬空
|
||
}
|
||
|
||
async function loadProfileData() {
|
||
if (!authToken) return;
|
||
|
||
try {
|
||
const resp = await apiFetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const email = data.data.email || "";
|
||
document.getElementById("profile-email").textContent = email;
|
||
const firstChar = email.charAt(0).toUpperCase();
|
||
document.getElementById("profile-avatar").textContent = firstChar;
|
||
|
||
maybeStrictGuide(data.data);
|
||
|
||
// 微信凭据(accessToken JWT)有效期,实时倒计时展示
|
||
_savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable
|
||
? { expireAt: data.data.access_token_expiry.expire_at,
|
||
source: data.data.access_token_expiry.source } : null;
|
||
updateTokenExpiryDisplays();
|
||
|
||
// 隐藏/显示消费统计和提示
|
||
const hasAuth = data.data.has_auth;
|
||
document.getElementById("profile-stats").style.display = hasAuth ? "flex" : "none";
|
||
document.getElementById("profile-auth-hint").style.display = hasAuth ? "none" : "flex";
|
||
document.getElementById("profile-name").textContent = "--";
|
||
document.getElementById("profile-out-money").textContent = "--";
|
||
document.getElementById("profile-save-money").textContent = "--";
|
||
}
|
||
} catch (err) {
|
||
console.error("加载用户信息失败:", err);
|
||
}
|
||
|
||
// 加载姓名和消费信息
|
||
loadUserInfo();
|
||
}
|
||
|
||
async function loadUserInfo() {
|
||
if (!authToken) return;
|
||
|
||
try {
|
||
const resp = await apiFetch("/api/auth/user_info", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const info = data.data;
|
||
|
||
// 显示姓名
|
||
if (info.true_name) {
|
||
document.getElementById("profile-name").textContent = info.true_name;
|
||
document.getElementById("profile-avatar").textContent = info.true_name.charAt(0);
|
||
}
|
||
|
||
// 显示消费统计
|
||
if (info.out_money !== null) {
|
||
document.getElementById("profile-out-money").textContent = (info.out_money || 0).toFixed(1);
|
||
}
|
||
if (info.save_money !== null) {
|
||
document.getElementById("profile-save-money").textContent = (info.save_money || 0).toFixed(1);
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error("加载用户详情失败:", err);
|
||
}
|
||
}
|
||
|
||
// ========== AccessToken 有效期解析 ==========
|
||
// accessToken 是上游登录响应中的 JWT(RS256),payload 带 iat/nbf/exp,
|
||
// 实测有效期 30 天。此处只解码展示,不做签名校验。
|
||
function parseJwtExpiry(token) {
|
||
token = (token || "").trim();
|
||
if (!token || token.indexOf(".") < 0) return null;
|
||
const parts = token.split(".");
|
||
if (parts.length !== 3 || parts[1].length < 8) return null;
|
||
try {
|
||
let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
||
while (b64.length % 4) b64 += "=";
|
||
const payload = JSON.parse(decodeURIComponent(escape(atob(b64))));
|
||
let exp = payload.exp ? parseInt(payload.exp) : null;
|
||
let iat = payload.iat ? parseInt(payload.iat) : null;
|
||
if (!exp && iat) exp = iat + 30 * 86400; // 与上游实测一致:30 天有效期
|
||
if (!exp) return null;
|
||
return { expireAt: exp, source: payload.exp ? "exp" : "iat+30d" };
|
||
} catch (e) { return null; }
|
||
}
|
||
function fmtLocalTime(ts) {
|
||
const d = new Date(ts * 1000);
|
||
const p = n => String(n).padStart(2, "0");
|
||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||
}
|
||
function describeTokenExpiry(expiry) {
|
||
const remain = expiry.expireAt - Math.floor(Date.now() / 1000);
|
||
const when = fmtLocalTime(expiry.expireAt);
|
||
const left = remain <= 0 ? "已过期" : `约剩 ${fmtRemainShort(remain)}`;
|
||
const note = expiry.source === "iat+30d" ? "(按签发时间 +30 天推算)" : "";
|
||
return { text: `该凭据(登录态)有效期至 ${when}${note},${left}`, remain };
|
||
}
|
||
function fmtRemainShort(remain) {
|
||
const dd = Math.floor(remain / 86400), hh = Math.floor((remain % 86400) / 3600),
|
||
mm = Math.floor((remain % 3600) / 60);
|
||
if (dd >= 1) return `${dd} 天${hh ? " " + hh + " 小时" : ""}`;
|
||
if (hh >= 1) return `${hh} 小时${mm ? " " + mm + " 分" : ""}`;
|
||
return `${Math.max(1, mm)} 分钟`;
|
||
}
|
||
function renderTokenExpiry(el, expiry) {
|
||
if (!el) return;
|
||
if (!expiry) { el.style.display = "none"; el.innerHTML = ""; return; }
|
||
const { text, remain } = describeTokenExpiry(expiry);
|
||
let color = "#34c759", bg = "#eafaf0";
|
||
if (remain <= 0) { color = "#e02020"; bg = "#fdecec"; }
|
||
else if (remain <= 259200) { color = "#e02020"; bg = "#fdecec"; } // ≤3 天
|
||
else if (remain <= 604800) { color = "#e67e22"; bg = "#fdf3e7"; } // ≤7 天
|
||
el.style.display = "block";
|
||
el.style.color = color;
|
||
el.style.background = bg;
|
||
el.textContent = text;
|
||
}
|
||
function updateTokenExpiryDisplays() {
|
||
// “填写凭证”弹窗:粘贴中的新 token 优先实时预览,否则显示已保存凭据
|
||
const authEl = document.getElementById("auth-token-expiry");
|
||
if (authEl) {
|
||
const pasted = document.getElementById("profile-token").value.trim();
|
||
if (pasted) {
|
||
const expiry = parseJwtExpiry(pasted);
|
||
if (expiry) {
|
||
renderTokenExpiry(authEl, expiry);
|
||
} else {
|
||
authEl.style.display = "block";
|
||
authEl.style.color = "#e67e22";
|
||
authEl.style.background = "#fdf3e7";
|
||
authEl.textContent = "无法解析该 AccessToken 的有效期(不是标准 JWT,仍可保存使用)";
|
||
}
|
||
} else {
|
||
renderTokenExpiry(authEl, _savedTokenExpiry);
|
||
}
|
||
}
|
||
// 个人中心:始终实时显示
|
||
const pEl = document.getElementById("profile-token-expiry");
|
||
if (pEl) renderTokenExpiry(pEl, _savedTokenExpiry);
|
||
renderAuthExpiryBanner();
|
||
}
|
||
let _savedTokenExpiry = null;
|
||
|
||
// ========== 登录态到期横幅 ==========
|
||
// 有效期不足 2 天时在主页面顶部常驻提醒,避免用户毫无预警地遇到上游凭据失效。
|
||
const AUTH_EXPIRY_BANNER_THRESHOLD = 2 * 86400; // 2 天
|
||
const AUTH_EXPIRY_BANNER_URGENT = 86400; // 不足 1 天转红
|
||
function renderAuthExpiryBanner() {
|
||
const banner = document.getElementById("auth-expiry-banner");
|
||
if (!banner) return;
|
||
const text = document.getElementById("auth-expiry-banner-text");
|
||
if (!authToken || !_savedTokenExpiry) {
|
||
banner.classList.remove("show", "urgent");
|
||
return;
|
||
}
|
||
const { remain } = describeTokenExpiry(_savedTokenExpiry);
|
||
if (remain > AUTH_EXPIRY_BANNER_THRESHOLD) {
|
||
banner.classList.remove("show", "urgent");
|
||
return;
|
||
}
|
||
const when = fmtLocalTime(_savedTokenExpiry.expireAt);
|
||
text.textContent = remain <= 0
|
||
? "登录态已过期,为不影响使用请尽快抓包"
|
||
: `登录态剩 ${fmtRemainShort(remain)},为不影响使用请尽快抓包`;
|
||
banner.title = `有效期至 ${when}`;
|
||
banner.classList.toggle("urgent", remain <= AUTH_EXPIRY_BANNER_URGENT);
|
||
banner.classList.add("show");
|
||
}
|
||
// 拉取服务端解析出的有效期(profile 接口),成功后刷新横幅
|
||
async function refreshAuthExpiry() {
|
||
if (!authToken) { _savedTokenExpiry = null; renderAuthExpiryBanner(); return; }
|
||
try {
|
||
const resp = await apiFetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0 && data.data) {
|
||
const e = data.data.access_token_expiry;
|
||
_savedTokenExpiry = e && e.parseable
|
||
? { expireAt: e.expire_at, source: e.source } : null;
|
||
} else {
|
||
_savedTokenExpiry = null;
|
||
}
|
||
} catch (err) {
|
||
console.error("获取登录态有效期失败:", err);
|
||
}
|
||
updateTokenExpiryDisplays();
|
||
}
|
||
setInterval(updateTokenExpiryDisplays, 30000); // 实时倒计时:每 30 秒刷新
|
||
|
||
// 打开凭证填写弹窗
|
||
function openAuthModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("auth-modal");
|
||
// 填充现有值
|
||
apiFetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
}).then(r => r.json()).then(data => {
|
||
if (data.rtn_code === 0 && data.data) {
|
||
document.getElementById("profile-token").value = data.data.token || "";
|
||
document.getElementById("profile-token-id").value = data.data.token_id || "";
|
||
const alertEl = document.getElementById("profile-alert-email");
|
||
if (alertEl) {
|
||
// 未自定义时显示账号邮箱占位(提交空串即回退账号邮箱)
|
||
alertEl.value = data.data.alert_email || "";
|
||
alertEl.placeholder = data.data.email || "留空则使用账号邮箱";
|
||
}
|
||
_savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable
|
||
? { expireAt: data.data.access_token_expiry.expire_at,
|
||
source: data.data.access_token_expiry.source } : null;
|
||
updateTokenExpiryDisplays();
|
||
}
|
||
});
|
||
}
|
||
|
||
function closeAuthModal() {
|
||
SettingsPages.back();
|
||
}
|
||
|
||
// ========== 强签名验证引导 ==========
|
||
let _strictGuideShown = false;
|
||
function maybeStrictGuide(info) {
|
||
if (info && info.strict_mode && info.has_access_token === false && !_strictGuideShown) {
|
||
_strictGuideShown = true;
|
||
showTokenExpiredModal(
|
||
"需要补充 AccessToken",
|
||
"管理员已开启强签名验证,您的账号尚未填写 AccessToken,填写前无法调用用车功能。请按教程抓包获取 accessToken(登录响应中的 JWT)并保存。"
|
||
);
|
||
}
|
||
}
|
||
async function checkStrictGuide() {
|
||
if (!authToken) return;
|
||
try {
|
||
const resp = await apiFetch("/api/auth/profile", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0 && data.data) maybeStrictGuide(data.data);
|
||
} catch (err) { console.error("强验证检测失败:", err); }
|
||
}
|
||
|
||
// ========== 登录设备管理(多设备) ==========
|
||
// 生成本设备持久标识:同一浏览器/设备保持不变,用于区分不同登录设备
|
||
function getDeviceId() {
|
||
let id = localStorage.getItem("xbniu_device_id");
|
||
if (!id) {
|
||
id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
||
try { localStorage.setItem("xbniu_device_id", id); } catch (e) {}
|
||
}
|
||
return id;
|
||
}
|
||
function getDeviceName() {
|
||
const ua = navigator.userAgent || "";
|
||
// 与服务端 routes/auth.py _ua_label 保持同一套识别规则
|
||
if (/xbniu-native/i.test(ua)) return "Native App";
|
||
let os;
|
||
if (/Windows NT/.test(ua)) os = "Windows";
|
||
else if (/iPhone|iPad|iPod/.test(ua)) os = "iOS";
|
||
else if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) os = "鸿蒙";
|
||
else if (/Android/.test(ua)) os = "Android";
|
||
else if (/Mac OS X/.test(ua)) os = "macOS";
|
||
else if (/Linux/.test(ua)) os = "Linux";
|
||
else os = /Mobile/.test(ua) ? "移动设备" : "电脑";
|
||
let browser = "浏览器";
|
||
if (/MicroMessenger/i.test(ua)) browser = "微信";
|
||
else if (/HuaweiBrowser/.test(ua)) browser = "华为浏览器";
|
||
else if (/Edg\//.test(ua)) browser = "Edge";
|
||
else if (/QQBrowser/.test(ua)) browser = "QQ浏览器";
|
||
else if (/MiuiBrowser/.test(ua)) browser = "小米浏览器";
|
||
else if (/Chrome\//.test(ua)) browser = "Chrome";
|
||
else if (/Firefox\//.test(ua)) browser = "Firefox";
|
||
else if (/Safari\//.test(ua)) browser = "Safari";
|
||
let label = os + " · " + browser;
|
||
if (window.screen && screen.width) label += " · " + screen.width + "x" + screen.height;
|
||
return label;
|
||
}
|
||
function escHtml(s) {
|
||
return String(s == null ? "" : s).replace(/[&<>"']/g,
|
||
c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||
}
|
||
function fmtTime(t) {
|
||
if (!t) return "";
|
||
return escHtml(String(t).replace("T", " ").slice(0, 16));
|
||
}
|
||
function openDevicesModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("devices-modal");
|
||
loadDevicesList();
|
||
}
|
||
function closeDevicesModal() {
|
||
SettingsPages.back();
|
||
}
|
||
async function loadDevicesList() {
|
||
const box = document.getElementById("devices-list");
|
||
if (!authToken) { box.innerHTML = '<div class="devices-empty">请先登录</div>'; return; }
|
||
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||
try {
|
||
const resp = await apiFetch("/api/auth/sessions", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code !== 0) {
|
||
box.innerHTML = '<div class="devices-empty">' + escHtml(data.message || "加载失败") + '</div>';
|
||
return;
|
||
}
|
||
const list = data.data.sessions || [];
|
||
if (!list.length) {
|
||
box.innerHTML = '<div class="devices-empty">暂无其他登录设备</div>';
|
||
return;
|
||
}
|
||
box.innerHTML = list.map(s => {
|
||
const isCur = !!s.is_current;
|
||
const meta = "登录 " + fmtTime(s.created_at) +
|
||
(s.last_active ? " · 活跃 " + fmtTime(s.last_active) : "");
|
||
return `<div class="device-row">
|
||
<div class="device-main">
|
||
<div class="device-name">${escHtml(s.device_name || "未知设备")}${isCur ? ' <span class="device-badge">当前</span>' : ""}</div>
|
||
<div class="device-meta">${meta}</div>
|
||
</div>
|
||
${isCur ? "" : `<button class="device-kick" onclick="kickDevice(${Number(s.id)})">下线</button>`}
|
||
</div>`;
|
||
}).join("");
|
||
} catch (err) {
|
||
box.innerHTML = '<div class="devices-empty">加载失败</div>';
|
||
}
|
||
}
|
||
async function kickDevice(id) {
|
||
if (!(await appConfirm("确认将该设备下线?该设备需要重新登录。", { title: "下线设备", okText: "下线" }))) return;
|
||
try {
|
||
const resp = await apiFetch("/api/auth/sessions/kick", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||
body: JSON.stringify({ session_id: id })
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) { showToast("已下线该设备"); loadDevicesList(); }
|
||
else showToast(data.message || "下线失败");
|
||
} catch (e) { showToast("网络错误"); }
|
||
}
|
||
async function logoutAllOtherDevices() {
|
||
if (!(await appConfirm("确认下线当前账号其他所有设备?\n本设备会保留登录。", { title: "下线其他设备", okText: "全部下线" }))) return;
|
||
try {
|
||
const resp = await apiFetch("/api/auth/sessions/logout_all", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
if (data.rtn_code === 0) { showToast("已下线其他所有设备"); loadDevicesList(); }
|
||
else showToast(data.message || "操作失败");
|
||
} catch (e) { showToast("网络错误"); }
|
||
}
|
||
|
||
// 打开卡包弹窗
|
||
function openPackagesModal() {
|
||
closeAllModals();
|
||
SettingsPages.open("packages-modal");
|
||
loadPackagesList();
|
||
}
|
||
|
||
function closePackagesModal() {
|
||
SettingsPages.back();
|
||
}
|
||
|
||
// 加载卡包列表(用于卡包弹窗)
|
||
async function loadPackagesList() {
|
||
if (!authToken) {
|
||
document.getElementById("packages-list-2").innerHTML = '<div class="packages-empty">请先登录</div>';
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const resp = await apiFetch("/api/auth/packages", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
const container = document.getElementById("packages-list-2");
|
||
|
||
if (!data.data || !data.data.has_auth) {
|
||
container.innerHTML = '<div class="packages-empty">请先填写 Token ID(AccessToken 选填)</div>';
|
||
return;
|
||
}
|
||
|
||
const packages = data.data.packages || [];
|
||
if (packages.length === 0) {
|
||
container.innerHTML = '<div class="packages-empty">暂无优惠卡</div>';
|
||
return;
|
||
}
|
||
|
||
container.innerHTML = packages.map(pkg => `
|
||
<div class="package-card">
|
||
<div class="package-name">${pkg.name}</div>
|
||
<div class="package-info">${pkg.bikeTypeName || ''} · ${pkg.useTypeName || ''}</div>
|
||
<div class="package-time">有效期至 ${pkg.endTime || '无限'}</div>
|
||
<div class="package-times">剩余 ${pkg.remainTimes ?? '∞'} 次</div>
|
||
</div>
|
||
`).join('');
|
||
} catch (err) {
|
||
console.error("加载卡包失败:", err);
|
||
document.getElementById("packages-list-2").innerHTML = '<div class="packages-empty">加载失败</div>';
|
||
}
|
||
}
|
||
|
||
async function saveProfileToken() {
|
||
if (!authToken) {
|
||
showToast("请先登录");
|
||
return;
|
||
}
|
||
|
||
const access_token = document.getElementById("profile-token").value.trim();
|
||
const token_id = document.getElementById("profile-token-id").value.trim();
|
||
const alertEmailEl = document.getElementById("profile-alert-email");
|
||
const alert_email = alertEmailEl ? alertEmailEl.value.trim().toLowerCase() : null;
|
||
|
||
// 如果填了任意一个字段,需要先验证
|
||
if (access_token || token_id) {
|
||
if (!token_id) {
|
||
showToast("Token ID 必填;AccessToken 选填");
|
||
return;
|
||
}
|
||
|
||
// 先验证(必须带登录态,否则 verify_token 返回 401)
|
||
try {
|
||
const verifyResp = await apiFetch("/api/auth/verify_token", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json",
|
||
"Authorization": `Bearer ${authToken}` },
|
||
body: JSON.stringify({ access_token, token_id })
|
||
});
|
||
const verifyData = await verifyResp.json();
|
||
|
||
if (!verifyData.valid) {
|
||
showToast(verifyData.message || "凭据验证失败,请检查 Token ID 是否正确");
|
||
return;
|
||
}
|
||
} catch (err) {
|
||
showToast("验证失败");
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 验证通过或没填字段,直接保存
|
||
try {
|
||
const resp = await apiFetch("/api/auth/save_token", {
|
||
method: "POST",
|
||
headers: {
|
||
"Authorization": `Bearer ${authToken}`,
|
||
"Content-Type": "application/json"
|
||
},
|
||
body: JSON.stringify({ access_token, token_id })
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0) {
|
||
// 告警邮箱单独保存(可与凭据一起提交,失败不阻断)
|
||
if (alert_email !== null) {
|
||
apiFetch("/api/auth/alert_email", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json",
|
||
"Authorization": `Bearer ${authToken}` },
|
||
body: JSON.stringify({ email: alert_email })
|
||
}).catch(() => {});
|
||
}
|
||
showToast("保存成功");
|
||
closeAuthModal(); // 关闭凭证弹窗
|
||
loadProfileData(); // 刷新个人中心数据
|
||
refreshAuthExpiry(); // 新凭据可能已换有效期,重算顶部提醒
|
||
} else {
|
||
showToast(data.message || "保存失败");
|
||
}
|
||
} catch (err) {
|
||
showToast("保存失败");
|
||
}
|
||
}
|
||
|
||
// ========== 批量响铃相关状态 ==========
|
||
let currentBellTab = 'all'; // 当前选项卡
|
||
let selectedRadius = 200; // 选中的半径(米)
|
||
let selectedLocation = null; // 选中的地点 {lat, lng}
|
||
let selectedStatuses = {available: true, used: true, locked: true, low: true, reserved: true}; // 选中的状态
|
||
let rangeCircleOverlay = null; // 范围圆覆盖物
|
||
|
||
function showBellPasswordModal() {
|
||
if (!canUseBatchRing()) {
|
||
showToast("批量寻铃仅对指定用户开放");
|
||
return;
|
||
}
|
||
document.getElementById("bell-modal").classList.add("show");
|
||
// 重置所有输入
|
||
document.getElementById("bell-password").value = "";
|
||
document.getElementById("bell-password-range").value = "";
|
||
document.getElementById("bell-password-status").value = "";
|
||
document.getElementById("bell-error").textContent = "";
|
||
document.getElementById("bell-error-range").textContent = "";
|
||
document.getElementById("bell-error-status").textContent = "";
|
||
document.getElementById("bell-progress").textContent = "";
|
||
|
||
// 更新状态计数
|
||
updateStatusCounts();
|
||
|
||
// 重置范围相关
|
||
selectedLocation = null;
|
||
document.getElementById("range-point-text").textContent = "--";
|
||
document.getElementById("range-hint").classList.remove("active");
|
||
document.getElementById("range-hint").innerHTML = `
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
|
||
<circle cx="12" cy="12" r="10"/>
|
||
<path d="M12 8v4M12 16h.01"/>
|
||
</svg>
|
||
点击地图选择地点,或使用当前位置
|
||
`;
|
||
|
||
// 更新筛选信息
|
||
updateFilterInfo();
|
||
|
||
document.getElementById("bell-password").focus();
|
||
}
|
||
|
||
// 切换选项卡
|
||
function switchBellTab(tab) {
|
||
currentBellTab = tab;
|
||
|
||
// 更新选项卡样式
|
||
document.querySelectorAll('.bell-tab').forEach(t => {
|
||
t.classList.toggle('active', t.dataset.tab === tab);
|
||
});
|
||
|
||
// 更新内容区
|
||
document.querySelectorAll('.bell-section').forEach(s => {
|
||
s.classList.toggle('active', s.id === `bell-section-${tab}`);
|
||
});
|
||
|
||
// 切换到范围模式时清除之前的选择
|
||
if (tab !== 'range') {
|
||
if (rangeCircleOverlay) {
|
||
map.removeOverlay(rangeCircleOverlay);
|
||
rangeCircleOverlay = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 选择半径
|
||
function selectRadius(radius) {
|
||
selectedRadius = radius;
|
||
document.querySelectorAll('.radius-btn').forEach(btn => {
|
||
btn.classList.toggle('active', parseInt(btn.dataset.radius) === radius);
|
||
});
|
||
// 更新范围圆
|
||
updateRangeCircle();
|
||
updateFilterInfo();
|
||
}
|
||
|
||
// 使用当前位置
|
||
function useCurrentLocation() {
|
||
if (!autoLocationMarker) {
|
||
showToast("请先开启定位(点击底部定位按钮)");
|
||
return;
|
||
}
|
||
|
||
const point = autoLocationMarker.getPosition();
|
||
const lat = point.lat;
|
||
const lng = point.lng;
|
||
|
||
selectedLocation = { lat, lng };
|
||
|
||
document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||
document.getElementById("range-hint").classList.add("active");
|
||
document.getElementById("range-hint").innerHTML = `
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#34c759" stroke-width="2">
|
||
<path d="M20 6L9 17l-5-5"/>
|
||
</svg>
|
||
已选择:${lat.toFixed(5)}, ${lng.toFixed(5)}
|
||
`;
|
||
|
||
updateRangeCircle();
|
||
updateFilterInfo();
|
||
|
||
showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`);
|
||
}
|
||
|
||
// 使用地图中心
|
||
function useCenterLocation() {
|
||
const center = map.getCenter();
|
||
const lat = center.lat;
|
||
const lng = center.lng;
|
||
|
||
selectedLocation = { lat, lng };
|
||
|
||
document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||
document.getElementById("range-hint").classList.add("active");
|
||
document.getElementById("range-hint").innerHTML = `
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#34c759" stroke-width="2">
|
||
<path d="M20 6L9 17l-5-5"/>
|
||
</svg>
|
||
已选择:${lat.toFixed(5)}, ${lng.toFixed(5)}
|
||
`;
|
||
|
||
updateRangeCircle();
|
||
updateFilterInfo();
|
||
|
||
showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`);
|
||
}
|
||
|
||
// 更新范围圆覆盖物
|
||
function updateRangeCircle() {
|
||
if (!selectedLocation) return;
|
||
|
||
// 清除旧的
|
||
if (rangeCircleOverlay) {
|
||
map.removeOverlay(rangeCircleOverlay);
|
||
}
|
||
|
||
const point = new BMapGL.Point(selectedLocation.lng, selectedLocation.lat);
|
||
rangeCircleOverlay = new BMapGL.Circle(point, selectedRadius, {
|
||
strokeColor: "#007AFF",
|
||
strokeWeight: 2,
|
||
strokeOpacity: 0.6,
|
||
fillColor: "#007AFF",
|
||
fillOpacity: 0.1
|
||
});
|
||
map.addOverlay(rangeCircleOverlay);
|
||
}
|
||
|
||
// 切换状态筛选
|
||
function toggleStatusFilter(state) {
|
||
selectedStatuses[state] = !selectedStatuses[state];
|
||
|
||
const item = document.querySelector(`.bell-status-item[data-state="${state}"]`);
|
||
if (item) {
|
||
item.classList.toggle('selected', selectedStatuses[state]);
|
||
item.querySelector('.bell-status-check').textContent = selectedStatuses[state] ? '✓' : '';
|
||
}
|
||
|
||
updateFilterInfo();
|
||
}
|
||
|
||
// 更新状态计数
|
||
function updateStatusCounts() {
|
||
const bikes = Object.values(markersData);
|
||
const counts = {available: 0, used: 0, locked: 0, low: 0, reserved: 0};
|
||
|
||
bikes.forEach(bike => {
|
||
const state = getBikeState(bike);
|
||
if (state === 'available') counts.available++;
|
||
else if (state === 'inuse') counts.used++;
|
||
else if (state === 'locked') counts.locked++;
|
||
else if (state === 'lowbattery') counts.low++;
|
||
else if (state === 'reserved') counts.reserved++;
|
||
});
|
||
|
||
document.getElementById('count-available-filter').textContent = counts.available;
|
||
document.getElementById('count-used-filter').textContent = counts.used;
|
||
document.getElementById('count-locked-filter').textContent = counts.locked;
|
||
document.getElementById('count-low-filter').textContent = counts.low;
|
||
document.getElementById('count-reserved-filter').textContent = counts.reserved;
|
||
}
|
||
|
||
// 计算两点之间的距离(米)
|
||
function calcDistance(lat1, lng1, lat2, lng2) {
|
||
const R = 6371000; // 地球半径(米)
|
||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||
Math.sin(dLng/2) * Math.sin(dLng/2);
|
||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
||
return R * c;
|
||
}
|
||
|
||
// 根据当前模式筛选车辆
|
||
function getFilteredBikes() {
|
||
const allBikes = Object.values(markersData);
|
||
|
||
if (currentBellTab === 'all') {
|
||
return allBikes;
|
||
}
|
||
|
||
if (currentBellTab === 'range') {
|
||
if (!selectedLocation) {
|
||
return []; // 没有选择地点
|
||
}
|
||
return allBikes.filter(bike => {
|
||
if (!bike.latitude || !bike.longitude) return false;
|
||
// 车辆在地图上显示的位置(偏移后)
|
||
const c = offsetCoord(bike.latitude, bike.longitude);
|
||
const dist = calcDistance(
|
||
selectedLocation.lat, selectedLocation.lng,
|
||
c.lat, c.lng
|
||
);
|
||
return dist <= selectedRadius;
|
||
});
|
||
}
|
||
|
||
if (currentBellTab === 'status') {
|
||
return allBikes.filter(bike => {
|
||
const state = getBikeState(bike);
|
||
if (state === 'available' && selectedStatuses.available) return true;
|
||
if (state === 'inuse' && selectedStatuses.used) return true;
|
||
if (state === 'locked' && selectedStatuses.locked) return true;
|
||
if (state === 'lowbattery' && selectedStatuses.low) return true;
|
||
if (state === 'reserved' && selectedStatuses.reserved) return true;
|
||
return false;
|
||
});
|
||
}
|
||
|
||
return allBikes;
|
||
}
|
||
|
||
// 更新筛选信息显示
|
||
function updateFilterInfo() {
|
||
const bikes = getFilteredBikes();
|
||
|
||
if (currentBellTab === 'range') {
|
||
const infoEl = document.getElementById('range-filter-info');
|
||
if (selectedLocation) {
|
||
infoEl.textContent = `范围内车辆:${bikes.length} 辆`;
|
||
} else {
|
||
infoEl.textContent = '';
|
||
}
|
||
}
|
||
|
||
if (currentBellTab === 'status') {
|
||
const infoEl = document.getElementById('status-filter-info');
|
||
const selectedCount = Object.values(selectedStatuses).filter(v => v).length;
|
||
infoEl.textContent = `已选 ${selectedCount} 种状态,共 ${bikes.length} 辆车`;
|
||
}
|
||
}
|
||
|
||
function closeBellModal() {
|
||
document.getElementById("bell-modal").classList.remove("show");
|
||
}
|
||
|
||
async function submitBellPassword() {
|
||
// 根据当前选项卡获取密码和错误元素
|
||
let pwd, errEl;
|
||
if (currentBellTab === 'all') {
|
||
pwd = document.getElementById("bell-password").value;
|
||
errEl = document.getElementById("bell-error");
|
||
} else if (currentBellTab === 'range') {
|
||
pwd = document.getElementById("bell-password-range").value;
|
||
errEl = document.getElementById("bell-error-range");
|
||
if (!selectedLocation) {
|
||
errEl.textContent = "请先选择地点(点击地图或使用当前位置/地图中心)";
|
||
return;
|
||
}
|
||
} else {
|
||
pwd = document.getElementById("bell-password-status").value;
|
||
errEl = document.getElementById("bell-error-status");
|
||
}
|
||
|
||
if (pwd !== "070517") {
|
||
errEl.textContent = "密码错误";
|
||
return;
|
||
}
|
||
|
||
// 根据模式筛选车辆
|
||
const bikes = getFilteredBikes();
|
||
|
||
if (bikes.length === 0) {
|
||
if (currentBellTab === 'range') {
|
||
errEl.textContent = "范围内没有车辆,请调整半径或选择其他地点";
|
||
} else if (currentBellTab === 'status') {
|
||
errEl.textContent = "没有符合条件的车,请调整状态筛选";
|
||
} else {
|
||
errEl.textContent = "暂无车辆数据,请先刷新地图";
|
||
}
|
||
return;
|
||
}
|
||
|
||
errEl.textContent = "启动中...";
|
||
|
||
try {
|
||
const res = await apiFetch("/api/ring_all", {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Authorization": `Bearer ${authToken}`
|
||
},
|
||
body: JSON.stringify({ codes: bikes.map(b => b.code) })
|
||
});
|
||
const data = await res.json();
|
||
if (data.rtn_code === 401) {
|
||
errEl.textContent = "登录已失效,请重新登录";
|
||
showLoginGate();
|
||
return;
|
||
}
|
||
if (data.rtn_code !== 0) {
|
||
errEl.textContent = data.message || "启动失败";
|
||
return;
|
||
}
|
||
|
||
closeBellModal();
|
||
|
||
// 清除范围圆
|
||
if (rangeCircleOverlay) {
|
||
map.removeOverlay(rangeCircleOverlay);
|
||
rangeCircleOverlay = null;
|
||
}
|
||
|
||
// 打开新窗口显示进度
|
||
const progressWin = window.open(
|
||
`/ring_progress.html?task_id=${data.task_id}&total=${data.total}`,
|
||
"ring_progress",
|
||
"width=450,height=520,menubar=no,toolbar=no,location=no,status=no"
|
||
);
|
||
if (!progressWin) {
|
||
showToast("请允许弹出窗口以查看进度");
|
||
}
|
||
} catch (e) {
|
||
errEl.textContent = "请求失败: " + friendlyError(e);
|
||
}
|
||
}
|
||
|
||
// ========== 全屏登录门 ==========
|
||
function showLoginGate() {
|
||
document.getElementById("login-gate").classList.add("show");
|
||
}
|
||
function hideLoginGate() {
|
||
document.getElementById("login-gate").classList.remove("show");
|
||
}
|
||
|
||
async function doLogin(email, password, tip, submitBtn) {
|
||
const btnText = submitBtn.textContent;
|
||
tip.textContent = "";
|
||
submitBtn.disabled = true;
|
||
submitBtn.textContent = "登录中...";
|
||
try {
|
||
const resp = await apiFetch("/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) {
|
||
if (currentUser?.email !== data.data.email) resetMapForAccount();
|
||
authToken = data.data.token;
|
||
localStorage.setItem("auth_token", authToken);
|
||
currentUser = { email: data.data.email };
|
||
authKickToastShown = false;
|
||
updateAuthButton();
|
||
hideLoginGate();
|
||
closeLoginModal();
|
||
showToast("登录成功");
|
||
shareAfterLogin();
|
||
checkOrderStatus();
|
||
checkRentalStatus();
|
||
refreshAuthExpiry(); // 登录态有效期不足 2 天时挂顶部提醒
|
||
if (map) { loadMapData(currentType, false); resumeLocationIfGranted(); }
|
||
} else {
|
||
tip.textContent = data.message || "登录失败";
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
} finally {
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = btnText;
|
||
}
|
||
}
|
||
|
||
async function handleLoginSubmit(e) {
|
||
e.preventDefault();
|
||
doLogin(
|
||
document.getElementById("login-email").value.trim().toLowerCase(),
|
||
document.getElementById("login-password").value,
|
||
document.getElementById("login-tip"),
|
||
e.target.querySelector("button[type='submit']")
|
||
);
|
||
}
|
||
|
||
document.getElementById("gate-login-form").addEventListener("submit", function (e) {
|
||
e.preventDefault();
|
||
doLogin(
|
||
document.getElementById("gate-email").value.trim().toLowerCase(),
|
||
document.getElementById("gate-password").value,
|
||
document.getElementById("gate-tip"),
|
||
this.querySelector("button[type='submit']")
|
||
);
|
||
});
|
||
|
||
let registerCodeCountdown = 0;
|
||
let registerCodeTimer = null;
|
||
function setRegisterCodeBtn(text, disabled) {
|
||
const btn = document.getElementById("register-code-btn");
|
||
if (!btn) return;
|
||
btn.disabled = disabled;
|
||
btn.textContent = text;
|
||
}
|
||
async function sendRegisterCode() {
|
||
const email = document.getElementById("register-email").value.trim().toLowerCase();
|
||
const tip = document.getElementById("register-tip");
|
||
if (!email) { tip.textContent = "请先填写邮箱"; return; }
|
||
if (registerCodeCountdown > 0) return;
|
||
setRegisterCodeBtn("发送中...", true);
|
||
try {
|
||
const resp = await apiFetch("/api/auth/send_code", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email })
|
||
});
|
||
const data = await resp.json();
|
||
tip.textContent = data.message || "";
|
||
if (data.rtn_code === 0) {
|
||
registerCodeCountdown = 60;
|
||
setRegisterCodeBtn(`${registerCodeCountdown}s`, true);
|
||
registerCodeTimer = setInterval(() => {
|
||
registerCodeCountdown--;
|
||
if (registerCodeCountdown <= 0) {
|
||
clearInterval(registerCodeTimer);
|
||
setRegisterCodeBtn("发送验证码", false);
|
||
} else {
|
||
setRegisterCodeBtn(`${registerCodeCountdown}s`, true);
|
||
}
|
||
}, 1000);
|
||
} else {
|
||
setRegisterCodeBtn("发送验证码", false);
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
setRegisterCodeBtn("发送验证码", false);
|
||
}
|
||
}
|
||
|
||
async function handleRegisterSubmit(e) {
|
||
e.preventDefault();
|
||
const email = document.getElementById("register-email").value.trim().toLowerCase();
|
||
const password = document.getElementById("register-password").value;
|
||
const code = document.getElementById("register-code").value.trim();
|
||
const invite_code = document.getElementById("register-invite").value.trim();
|
||
const token_id = document.getElementById("register-token-id").value.trim();
|
||
const access_token = document.getElementById("register-token").value.trim();
|
||
const tip = document.getElementById("register-tip");
|
||
const submitBtn = e.target.querySelector("button[type='submit']");
|
||
|
||
tip.textContent = "";
|
||
submitBtn.disabled = true;
|
||
submitBtn.textContent = "注册中...";
|
||
|
||
// 凭据字段的基础格式检查;上游有效性由 /api/auth/register 在服务端权威校验
|
||
// (注册时还没有登录态,verify_token 接口需要 Authorization,前端预检必然 401)
|
||
if (access_token || token_id) {
|
||
if (!token_id) {
|
||
tip.textContent = "Token ID 必填;AccessToken 选填";
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = "注册";
|
||
return;
|
||
}
|
||
}
|
||
|
||
try {
|
||
const resp = await apiFetch("/api/auth/register", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
email,
|
||
password,
|
||
code,
|
||
invite_code,
|
||
token_id: token_id || "",
|
||
access_token,
|
||
device_id: getDeviceId(),
|
||
device_name: getDeviceName()
|
||
})
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0) {
|
||
authToken = data.data.token;
|
||
localStorage.setItem("auth_token", authToken);
|
||
currentUser = { email: data.data.email };
|
||
authKickToastShown = false;
|
||
updateAuthButton();
|
||
closeRegisterModal();
|
||
hideLoginGate();
|
||
showToast("注册成功");
|
||
shareAfterLogin();
|
||
refreshAuthExpiry(); // 注册时可能已填凭证,立即评估有效期
|
||
if (map) loadMapData(currentType, false);
|
||
} else {
|
||
tip.textContent = data.message || "注册失败";
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "网络错误,请重试";
|
||
} finally {
|
||
submitBtn.disabled = false;
|
||
submitBtn.textContent = "注册";
|
||
}
|
||
}
|
||
|
||
async function handleLogout() {
|
||
clearTimeout(mapRefreshTimer);
|
||
if (authToken) {
|
||
try {
|
||
await apiFetch("/api/auth/logout", {
|
||
method: "POST",
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
} catch (err) {}
|
||
}
|
||
authToken = null;
|
||
currentUser = null;
|
||
localStorage.removeItem("auth_token");
|
||
authKickToastShown = false;
|
||
_savedTokenExpiry = null;
|
||
renderAuthExpiryBanner(); // 登出后隐藏登录态到期提醒
|
||
updateAuthButton();
|
||
closeProfileModal();
|
||
showToast("已登出");
|
||
showLoginGate();
|
||
const sb = document.getElementById("share-banners");
|
||
if (sb) sb.innerHTML = "";
|
||
shareAskQueue = [];
|
||
shareAskActive = false;
|
||
const askModal = document.getElementById("share-ask-modal");
|
||
if (askModal) askModal.classList.remove("show");
|
||
}
|
||
|
||
function updateAuthButton() {
|
||
const btn = document.getElementById("auth-btn");
|
||
const btnText = document.getElementById("auth-btn-text");
|
||
const avatar = document.getElementById("auth-avatar");
|
||
|
||
if (currentUser) {
|
||
btn.classList.add("logged-in");
|
||
btnText.style.display = "none";
|
||
avatar.style.display = "flex";
|
||
avatar.textContent = currentUser.email.charAt(0).toUpperCase();
|
||
} else {
|
||
btn.classList.remove("logged-in");
|
||
btnText.style.display = "inline";
|
||
avatar.style.display = "none";
|
||
btnText.textContent = "登录";
|
||
}
|
||
updateBellBtnVisibility();
|
||
}
|
||
|
||
// ========== 批量寻铃入口权限 ==========
|
||
// 仅指定用户可见/可用;服务端 /api/ring_all 同步校验
|
||
const BATCH_RING_ALLOWED_EMAILS = ["3146527494@qq.com"];
|
||
function canUseBatchRing() {
|
||
return !!(currentUser && BATCH_RING_ALLOWED_EMAILS.includes((currentUser.email || "").toLowerCase()));
|
||
}
|
||
function updateBellBtnVisibility() {
|
||
const btn = document.getElementById("bell-btn");
|
||
if (btn) btn.style.display = canUseBatchRing() ? "flex" : "none";
|
||
}
|
||
|
||
async function checkAuthStatus() {
|
||
if (!authToken) return;
|
||
|
||
try {
|
||
const resp = await apiFetch("/api/auth/status", {
|
||
headers: { "Authorization": `Bearer ${authToken}` }
|
||
});
|
||
const data = await resp.json();
|
||
|
||
if (data.rtn_code === 0 && data.data.logged_in) {
|
||
currentUser = { email: data.data.email };
|
||
updateAuthButton();
|
||
} else {
|
||
// token无效(可能被本设备或其他设备下线),清除登录状态
|
||
const hadToken = !!authToken;
|
||
authToken = null;
|
||
currentUser = null;
|
||
localStorage.removeItem("auth_token");
|
||
updateAuthButton();
|
||
if (hadToken && !authKickToastShown) {
|
||
authKickToastShown = true;
|
||
showToast("登录状态已失效,请重新登录");
|
||
showLoginGate();
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error("检查登录状态失败:", err);
|
||
}
|
||
}
|
||
|
||
// ========== 忘记密码 ==========
|
||
// 忘记密码可从两处打开:弹窗登录(login-modal)与全屏登录门(login-gate)。
|
||
// 用 _forgotFromGate 记住入口,重置成功后回到原处,避免用户被"换页面"。
|
||
let _forgotFromGate = false;
|
||
function showForgotModal() {
|
||
_forgotFromGate = false;
|
||
closeAllModals();
|
||
document.getElementById("forgot-modal").classList.add("show");
|
||
}
|
||
function showForgotFromGate() {
|
||
_forgotFromGate = true;
|
||
closeAllModals();
|
||
// 带上登录门里已填的邮箱,省去用户重复输入
|
||
const field = document.getElementById("gate-email");
|
||
const emailInput = document.getElementById("forgot-email");
|
||
if (field && emailInput && field.value.trim() && !emailInput.value.trim()) {
|
||
emailInput.value = field.value.trim();
|
||
}
|
||
document.getElementById("forgot-modal").classList.add("show");
|
||
}
|
||
function closeForgotModal() {
|
||
document.getElementById("forgot-modal").classList.remove("show");
|
||
document.getElementById("forgot-tip").textContent = "";
|
||
_forgotFromGate = false;
|
||
}
|
||
function backToLoginFromForgot() {
|
||
const fromGate = _forgotFromGate;
|
||
closeForgotModal();
|
||
if (fromGate) showLoginGate();
|
||
else showLoginModal();
|
||
}
|
||
let forgotTimer = null;
|
||
function setForgotCodeBtn(seconds) {
|
||
const btn = document.getElementById("forgot-code-btn");
|
||
if (forgotTimer) { clearInterval(forgotTimer); forgotTimer = null; }
|
||
if (seconds > 0) {
|
||
btn.disabled = true;
|
||
btn.textContent = `${seconds}s 后重发`;
|
||
forgotTimer = setInterval(() => {
|
||
seconds--;
|
||
if (seconds <= 0) {
|
||
clearInterval(forgotTimer); forgotTimer = null;
|
||
btn.disabled = false; btn.textContent = "发送验证码";
|
||
} else {
|
||
btn.textContent = `${seconds}s 后重发`;
|
||
}
|
||
}, 1000);
|
||
} else {
|
||
btn.disabled = false; btn.textContent = "发送验证码";
|
||
}
|
||
}
|
||
async function sendForgotCode() {
|
||
const email = document.getElementById("forgot-email").value.trim();
|
||
const tip = document.getElementById("forgot-tip");
|
||
if (!email) { tip.textContent = "请先填写注册邮箱"; return; }
|
||
tip.textContent = "发送中...";
|
||
try {
|
||
const resp = await apiFetch("/api/auth/send_code", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email: email, purpose: "reset" })
|
||
});
|
||
const data = await resp.json();
|
||
tip.textContent = data.message || "";
|
||
if (data.rtn_code === 0) setForgotCodeBtn(60);
|
||
} catch (err) {
|
||
tip.textContent = "发送失败,请检查网络";
|
||
}
|
||
}
|
||
async function handleForgotSubmit(event) {
|
||
event.preventDefault();
|
||
const email = document.getElementById("forgot-email").value.trim();
|
||
const code = document.getElementById("forgot-code").value.trim();
|
||
const password = document.getElementById("forgot-password").value;
|
||
const tip = document.getElementById("forgot-tip");
|
||
if (password.length < 6) { tip.textContent = "新密码至少 6 位"; return; }
|
||
tip.textContent = "提交中...";
|
||
try {
|
||
const resp = await apiFetch("/api/auth/reset_password", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email: email, code: code, password: password })
|
||
});
|
||
const data = await resp.json();
|
||
tip.textContent = data.message || "";
|
||
if (data.rtn_code === 0) {
|
||
// 回到用户进来的那个登录界面:登录门 → 回登录门;弹窗 → 回登录弹窗
|
||
const fromGate = _forgotFromGate;
|
||
setTimeout(() => {
|
||
closeForgotModal();
|
||
if (fromGate) {
|
||
showLoginGate();
|
||
const gateEmail = document.getElementById("gate-email");
|
||
const gatePwd = document.getElementById("gate-password");
|
||
if (gateEmail) gateEmail.value = email;
|
||
if (gatePwd) { gatePwd.value = ""; gatePwd.focus(); }
|
||
} else {
|
||
showLoginModal();
|
||
document.getElementById("login-email").value = email;
|
||
}
|
||
}, 900);
|
||
}
|
||
} catch (err) {
|
||
tip.textContent = "提交失败,请检查网络";
|
||
}
|
||
}
|