const { createLocationReportFilter, shouldAcceptLocationReport } = require('./deliveryLocationFilter'); const REPORT_MIN_MS = 15000; let watchTimer = null; let watching = false; let lastReportAt = 0; let authPrompted = false; let bgAuthPrompted = false; let locationChangeBound = false; let reportFilter = createLocationReportFilter(); /** 最近一次被接受的上报点:结束配送时随请求带上,作为进圈判定的兜底样本 */ let lastAcceptedPoint = null; function resetLocationReportState() { lastReportAt = 0; reportFilter = createLocationReportFilter(); lastAcceptedPoint = null; } /** * 最近一次被接受的上报点(含时间)。 * 供「结束配送」把当前/最后的已知位置一并提交,避免途中上报断档导致进圈永远检测不到。 */ function getLastAcceptedPoint() { return lastAcceptedPoint ? { ...lastAcceptedPoint } : null; } function ensureLocationAuth() { return new Promise((resolve, reject) => { if (!wx.getSetting || !wx.authorize) { resolve(true); return; } wx.getSetting({ success(res) { if (res.authSetting && res.authSetting['scope.userLocation']) { resolve(true); return; } wx.authorize({ scope: 'scope.userLocation', success: () => resolve(true), fail: () => { if (!authPrompted) { authPrompted = true; wx.showModal({ title: '需要定位权限', content: '配送需使用精准位置,请在设置中开启位置信息', confirmText: '去设置', success(modal) { if (modal.confirm && wx.openSetting) wx.openSetting(); }, }); } reject(new Error('未授权定位')); }, }); }, fail: () => reject(new Error('无法读取定位权限')), }); }); } /** * 后台定位授权:scope.userLocationBackground【不能】用 wx.authorize 授予, * 必须用户在小程序「设置」中手动开启(且小程序需具备后台定位类目权限)。 * 旧实现直接 wx.authorize 恒失败,导致后台更新形同虚设。此处改为读取并引导去设置。 * 返回 Promise:是否已获得后台定位权限。 */ function ensureBackgroundLocationAuth() { return new Promise((resolve) => { if (!wx.getSetting) { resolve(false); return; } const guideToSetting = () => { if (bgAuthPrompted || !wx.openSetting) { resolve(false); return; } bgAuthPrompted = true; wx.showModal({ title: '建议开启后台定位', content: '配送途中切到地图/锁屏后仍会上报位置,用于记录到店时刻。请在设置中把「位置信息」改为「使用小程序期间和离开小程序后」。', confirmText: '去设置', success(modal) { if (modal.confirm && wx.openSetting) { wx.openSetting({ success(res) { const granted = !!(res && res.authSetting && res.authSetting['scope.userLocationBackground']); resolve(granted); }, fail: () => resolve(false), }); } else { resolve(false); } }, fail: () => resolve(false), }); }; wx.getSetting({ success(res) { const granted = !!(res && res.authSetting && res.authSetting['scope.userLocationBackground']); if (granted) { resolve(true); return; } guideToSetting(); }, fail: () => resolve(false), }); }); } function getHighAccuracyLocation() { return new Promise((resolve, reject) => { if (!wx.getLocation) { reject(new Error('当前基础库不支持定位')); return; } wx.getLocation({ type: 'gcj02', isHighAccuracy: true, highAccuracyExpireTime: 5000, success: resolve, fail: (err) => reject(new Error((err && err.errMsg) || '定位失败')), }); }); } /** * 带超时的定位取点:超时/失败一律 resolve(null),【绝不挂住调用方】。 * * 必要性:getHighAccuracyLocation 只在 wx.getLocation 的 success/fail 回调里结算。 * 若两个回调都不触发(定位服务卡住、权限弹窗被异常关闭等),Promise 永不 settle, * await 它的业务流程(如「结束配送」)会永久卡死。结束配送这类动作不能被定位拖住。 * * @param timeoutMs 超时毫秒;默认 3000 * @returns Promise<{lat,lng,accuracy,speed,heading}|null> */ function getHighAccuracyLocationWithin(timeoutMs) { const ms = Number(timeoutMs); const waitMs = Number.isFinite(ms) && ms > 0 ? ms : 3000; return new Promise((resolve) => { let settled = false; const finish = (value) => { if (settled) return; settled = true; resolve(value); }; const timer = setTimeout(() => finish(null), waitMs); getHighAccuracyLocation() .then((res) => { clearTimeout(timer); finish(pointFromLocation(res)); }) .catch(() => { clearTimeout(timer); finish(null); }); }); } function pointFromLocation(res) { const lat = Number(res && res.latitude); const lng = Number(res && res.longitude); if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null; return { lat, lng, accuracy: res.accuracy != null ? Number(res.accuracy) : null, speed: res.speed != null ? Number(res.speed) : null, heading: res.heading != null ? Number(res.heading) : null, }; } function shouldReportNow() { const now = Date.now(); if (now - lastReportAt < REPORT_MIN_MS) return false; lastReportAt = now; return true; } function emitPoint(onPoint, res) { const point = pointFromLocation(res); if (!point) return; const now = Date.now(); if (now - lastReportAt < REPORT_MIN_MS) return; lastReportAt = now; const decision = shouldAcceptLocationReport(reportFilter, point, now); if (!decision.accept) return; reportFilter = decision.nextState; lastAcceptedPoint = { lat: point.lat, lng: point.lng, accuracy: point.accuracy, at: now }; onPoint(point); } function startGetLocationFallback(onPoint) { const tick = () => { getHighAccuracyLocation() .then((res) => emitPoint(onPoint, res)) .catch(() => {}); }; tick(); watchTimer = setInterval(tick, REPORT_MIN_MS); } function bindLocationChange(onPoint) { if (locationChangeBound || !wx.onLocationChange) return; locationChangeBound = true; wx.onLocationChange((res) => emitPoint(onPoint, res)); } function unbindLocationChange() { if (!locationChangeBound) return; if (wx.offLocationChange) wx.offLocationChange(); locationChangeBound = false; } function stopDeliveryLocationWatch() { if (watchTimer) { clearInterval(watchTimer); watchTimer = null; } unbindLocationChange(); if (wx.stopLocationUpdate) { try { wx.stopLocationUpdate(); } catch (error) { /* ignore */ } } watching = false; resetLocationReportState(); } function startDeliveryLocationWatch(onPoint) { if (watching) return; watching = true; resetLocationReportState(); bindLocationChange(onPoint); // 【双保险】定时轮询一律启动: // 旧实现是「后台更新可用就不启轮询」,而后台定位授权实际拿不到, // 一旦小程序切到后台,wx.onLocationChange 与 JS 定时器都会停 → 上报归零 → 进圈检测失效。 // 现在轮询恒开(emitPoint 内有 15s 节流,不会重复上报),后台更新作为增量补充。 startGetLocationFallback(onPoint); // 后台更新通道:仅有权限时才可能生效,成功与否都不影响上面的轮询兜底。 ensureBackgroundLocationAuth() .then((granted) => { if (granted && wx.startLocationUpdateBackground) { wx.startLocationUpdateBackground({ type: 'gcj02', success: () => {}, fail: () => {} }); } }) .catch(() => {}); } module.exports = { ensureLocationAuth, getHighAccuracyLocation, getHighAccuracyLocationWithin, getLastAcceptedPoint, pointFromLocation, shouldReportNow, startDeliveryLocationWatch, stopDeliveryLocationWatch, };