/**
 * GPS定位模块
 * 使用Capacitor Geolocation获取设备位置
 */

const LocationModule = (() => {
    let lastPosition = null;
    let watchId = null;
    let reportTimer = null;

    // 检查是否在Capacitor环境
    function isCapacitor() {
        return typeof Capacitor !== 'undefined' && Capacitor.isNativePlatform && Capacitor.isNativePlatform();
    }

    // 获取Geolocation插件
    function getGeolocation() {
        if (isCapacitor() && Capacitor.Plugins && Capacitor.Plugins.Geolocation) {
            return Capacitor.Plugins.Geolocation;
        }
        return null;
    }

    // 获取当前位置
    async function getCurrentPosition() {
        try {
            const geo = getGeolocation();
            let pos;

            if (geo) {
                // Capacitor原生定位
                const result = await geo.getCurrentPosition({
                    enableHighAccuracy: true,
                    timeout: 10000
                });
                pos = {
                    lat: result.coords.latitude,
                    lng: result.coords.longitude,
                    accuracy: result.coords.accuracy,
                    timestamp: result.timestamp
                };
            } else {
                // 浏览器Geolocation API（用于开发调试）
                pos = await new Promise((resolve, reject) => {
                    navigator.geolocation.getCurrentPosition(
                        (result) => {
                            resolve({
                                lat: result.coords.latitude,
                                lng: result.coords.longitude,
                                accuracy: result.coords.accuracy,
                                timestamp: result.timestamp
                            });
                        },
                        (err) => reject(err),
                        { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
                    );
                });
            }

            lastPosition = pos;
            return pos;
        } catch (e) {
            console.error('定位失败:', e);
            // 返回默认位置（用于演示）
            lastPosition = { lat: 30.0000, lng: 120.0000, accuracy: 10 };
            return lastPosition;
        }
    }

    // 开始持续定位并上报
    async function startReporting(soldierId, name, intervalMs = 10000) {
        if (reportTimer) clearInterval(reportTimer);

        // 立即上报一次
        await reportOnce(soldierId, name);

        // 定时上报
        reportTimer = setInterval(async () => {
            await reportOnce(soldierId, name);
        }, intervalMs);
    }

    // 单次上报
    async function reportOnce(soldierId, name) {
        try {
            const pos = await getCurrentPosition();
            await API.updateLocation({
                id: soldierId,
                name: name,
                lat: pos.lat,
                lng: pos.lng
            });
            console.log('位置已上报:', pos.lat, pos.lng);
        } catch (e) {
            console.error('位置上报失败:', e);
        }
    }

    // 停止上报
    function stopReporting() {
        if (reportTimer) {
            clearInterval(reportTimer);
            reportTimer = null;
        }
    }

    // 获取最后已知位置
    function getLastPosition() {
        return lastPosition;
    }

    // 计算两点距离（米）
    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;
    }

    return {
        getCurrentPosition,
        startReporting,
        stopReporting,
        getLastPosition,
        calcDistance,
        isCapacitor
    };
})();
