/**
 * API 封装模块
 * 与Flask后端通信的REST API接口
 */

const API = (() => {
    let BASE = (typeof App !== 'undefined' && App.CONFIG) ? App.CONFIG.apiBase : 'http://192.168.1.14:5000';

    async function request(url, options = {}) {
        // 每次请求时重新读取BASE，支持动态切换
        if (typeof App !== 'undefined' && App.CONFIG) BASE = App.CONFIG.apiBase;
        const fullUrl = url.startsWith('http') ? url : BASE + url;
        const resp = await fetch(fullUrl, {
            headers: { 'Content-Type': 'application/json' },
            ...options
        });
        if (!resp.ok) {
            const text = await resp.text();
            throw new Error(`HTTP ${resp.status}: ${text}`);
        }
        return resp.json();
    }

    // ===== 士兵位置 =====
    async function updateLocation(data) {
        return request('/api/soldier/location', {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    async function getSoldiers() {
        return request('/api/soldiers');
    }

    // ===== 需求上报 =====
    async function postDemand(demand) {
        return request('/api/demand', {
            method: 'POST',
            body: JSON.stringify(demand)
        });
    }

    async function getDemands(soldierId) {
        return request('/api/demands?soldier_id=' + encodeURIComponent(soldierId));
    }

    async function getDemand(id) {
        return request('/api/demands/' + id);
    }

    // ===== 投放点 =====
    async function getDropPoints() {
        // 如果后端不可用，返回模拟数据
        try {
            const data = await request('/api/drop-points');
            return data.drop_points || data;
        } catch (e) {
            return getMockDropPoints();
        }
    }

    async function postDropPoint(data) {
        return request('/api/drop-point', {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // ===== 任务 =====
    async function getCurrentTask(soldierId) {
        try {
            const data = await request('/api/task/current?soldier_id=' + encodeURIComponent(soldierId));
            return data.task || data;
        } catch (e) {
            return getMockTask();
        }
    }

    // ===== 无人机状态 =====
    async function getDroneStatus() {
        try {
            const data = await request('/api/drone/status');
            return data.status || data;
        } catch (e) {
            return getMockDroneStatus();
        }
    }

    async function getDroneLogs() {
        try {
            const data = await request('/api/drone/logs');
            return data.logs || data;
        } catch (e) {
            return getMockDroneLogs();
        }
    }

    // ===== SOS求救 =====
    async function sendSOS(data) {
        return request('/api/sos', {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // ===== 模拟数据（后端未就绪时使用） =====
    function getMockDropPoints() {
        return [
            { name: '安全点 #1', safety_score: 92, distance: 5, reason: '深掩体保护，视角盲区' },
            { name: '安全点 #2', safety_score: 85, distance: 12, reason: '钢筋混凝土建筑内部' },
            { name: '陷阱点 #3', safety_score: 35, distance: 20, reason: '孤立断墙，成瞄准点' }
        ];
    }

    function getMockTask() {
        return {
            id: '#2024-05-20-001',
            status: '执行中',
            progress: 60,
            eta: '12:30',
            remain_time: '12分钟',
            start_name: '后方阵地',
            target_name: 'A区街角12号背侧',
            safety_score: 92
        };
    }

    function getMockDroneStatus() {
        return {
            drone_id: '无人机-01',
            task_id: '#001',
            status: '飞行中',
            position: 'A区街角12号',
            battery: 85,
            eta: '12:30',
            speed: 8.5,
            altitude: 15,
            distance: 500,
            temperature: 38
        };
    }

    function getMockDroneLogs() {
        return [
            { time: '12:25:30', message: '到达投放点' },
            { time: '12:20:45', message: '接收任务指令' },
            { time: '12:10:00', message: '任务分配' }
        ];
    }

    return {
        updateLocation,
        getSoldiers,
        postDemand,
        getDemands,
        getDemand,
        getDropPoints,
        postDropPoint,
        getCurrentTask,
        getDroneStatus,
        getDroneLogs,
        sendSOS
    };
})();
