// =============================================
// API 通信模块 + 离线支持
// =============================================

const API = {
    // 服务器 API 根地址（末尾含 /）
    baseUrl: 'http://www.csplan.cn/kehu/api/',

    // 最后同步时间
    lastSyncTime: null,

    // 离线队列（存储在 localStorage）
    get offlineQueue() {
        try {
            return JSON.parse(localStorage.getItem('crv_offline_queue') || '[]');
        } catch { return []; }
    },
    set offlineQueue(val) {
        localStorage.setItem('crv_offline_queue', JSON.stringify(val));
    },

    // 网络状态
    isOnline: navigator.onLine,

    // =============================================
    // 通用请求方法（带离线降级）
    // =============================================
    async request(endpoint, options = {}) {
        // 离线时，写操作入队，读操作走本地
        if (!API.isOnline) {
            const method = (options.method || 'GET').toUpperCase();
            if (method === 'POST') {
                API._enqueueOffline(endpoint, options);
                return { success: true, offline: true };
            }
            throw new Error('当前离线，无法读取远程数据');
        }

        const url = API.baseUrl + endpoint;
        const config = {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            ...options
        };

        if (config.body && typeof config.body === 'object') {
            config.body = JSON.stringify(config.body);
        }

        try {
            const controller = new AbortController();
            const timer = setTimeout(() => controller.abort(), 15000); // 15s 超时
            config.signal = controller.signal;

            const response = await fetch(url, config);
            clearTimeout(timer);

            let data;
            const text = await response.text();
            try {
                data = JSON.parse(text);
            } catch {
                throw new Error(`服务器返回了非 JSON 内容: ${text.substring(0, 100)}`);
            }

            if (!response.ok) {
                throw new Error(data.error || `HTTP ${response.status}`);
            }

            return data;
        } catch (error) {
            if (error.name === 'AbortError') {
                throw new Error('请求超时，请检查网络');
            }
            // 网络断开时，写操作入队
            if (!navigator.onLine || error.message.includes('Failed to fetch')) {
                const method = (options.method || 'GET').toUpperCase();
                if (method === 'POST') {
                    API._enqueueOffline(endpoint, options);
                    return { success: true, offline: true };
                }
            }
            console.error('API 请求错误:', error);
            throw error;
        }
    },

    // =============================================
    // 离线操作队列管理
    // =============================================
    _enqueueOffline(endpoint, options) {
        const queue = API.offlineQueue;
        queue.push({
            id: Date.now() + '_' + Math.random().toString(36).substr(2, 6),
            endpoint,
            options: {
                method: options.method,
                body: options.body
            },
            timestamp: new Date().toISOString()
        });
        API.offlineQueue = queue;
        console.log('[离线队列] 已加入:', endpoint, '队列长度:', queue.length);
        API._notifyOfflineQueued();
    },

    _notifyOfflineQueued() {
        // 通知 UI 显示"离线数据已暂存"提示
        if (typeof window !== 'undefined') {
            window.dispatchEvent(new CustomEvent('crv:offline-queued', {
                detail: { count: API.offlineQueue.length }
            }));
        }
    },

    // 重连后自动刷新离线队列
    async flushOfflineQueue() {
        const queue = API.offlineQueue;
        if (queue.length === 0) return { flushed: 0 };

        console.log('[离线队列] 开始回放', queue.length, '条操作...');
        const failed = [];
        let flushed = 0;

        for (const item of queue) {
            try {
                await API.request(item.endpoint, item.options);
                flushed++;
            } catch (e) {
                console.warn('[离线队列] 回放失败:', item.endpoint, e.message);
                failed.push(item);
            }
        }

        API.offlineQueue = failed;
        console.log(`[离线队列] 完成: 成功 ${flushed} 条，失败 ${failed.length} 条`);
        return { flushed, failed: failed.length };
    },

    // =============================================
    // 客户信息
    // =============================================
    customers: {
        async getList(lastSync = '') {
            const params = lastSync ? `?action=list&last_sync=${encodeURIComponent(lastSync)}` : '?action=list';
            return await API.request(`customers.php${params}`);
        },
        async get(id) {
            return await API.request(`customers.php?action=get&id=${encodeURIComponent(id)}`);
        },
        async save(customer) {
            return await API.request('customers.php?action=save', { method: 'POST', body: customer });
        },
        async delete(id) {
            return await API.request('customers.php?action=delete', { method: 'POST', body: { id } });
        },
        async sync(customers) {
            return await API.request('customers.php?action=sync', { method: 'POST', body: { customers } });
        }
    },

    // =============================================
    // 行业方案
    // =============================================
    schemes: {
        async getList(lastSync = '') {
            const params = lastSync ? `?action=list&last_sync=${encodeURIComponent(lastSync)}` : '?action=list';
            return await API.request(`schemes.php${params}`);
        },
        async get(id) {
            return await API.request(`schemes.php?action=get&id=${encodeURIComponent(id)}`);
        },
        async save(scheme) {
            return await API.request('schemes.php?action=save', { method: 'POST', body: scheme });
        },
        async delete(id) {
            return await API.request('schemes.php?action=delete', { method: 'POST', body: { id } });
        },
        async sync(schemes) {
            return await API.request('schemes.php?action=sync', { method: 'POST', body: { schemes } });
        }
    },

    // =============================================
    // 产品
    // =============================================
    products: {
        async getList() {
            return await API.request('products.php?action=list');
        },
        async get(id) {
            return await API.request(`products.php?action=get&id=${encodeURIComponent(id)}`);
        },
        async save(product) {
            return await API.request('products.php?action=save', { method: 'POST', body: product });
        },
        async delete(id) {
            return await API.request('products.php?action=delete', { method: 'POST', body: { id } });
        },
        async sync(products) {
            return await API.request('products.php?action=sync', { method: 'POST', body: { products } });
        }
    },

    // =============================================
    // 话术脚本
    // =============================================
    scripts: {
        async getList() {
            return await API.request('scripts.php?action=list');
        },
        async save(script) {
            return await API.request('scripts.php?action=save', { method: 'POST', body: script });
        },
        async delete(id) {
            return await API.request('scripts.php?action=delete', { method: 'POST', body: { id } });
        },
        async sync(scripts) {
            return await API.request('scripts.php?action=sync', { method: 'POST', body: { scripts } });
        }
    },

    // =============================================
    // 回访记录
    // =============================================
    visits: {
        async getList(customerId = '') {
            const params = customerId ? `?action=list&customer_id=${encodeURIComponent(customerId)}` : '?action=list';
            return await API.request(`visits.php${params}`);
        },
        async save(record) {
            return await API.request('visits.php?action=save', { method: 'POST', body: record });
        },
        async delete(id) {
            return await API.request('visits.php?action=delete', { method: 'POST', body: { id } });
        },
        async sync(records) {
            return await API.request('visits.php?action=sync', { method: 'POST', body: { records } });
        }
    },

    // =============================================
    // 同步功能
    // =============================================
    sync: {
        // 推送本地数据到服务器
        async push(appInstance) {
            try {
                const customers = await appInstance.dbGetAll('customers');
                if (customers.length > 0) await API.customers.sync(customers);

                const products = await appInstance.dbGetAll('products');
                if (products.length > 0) await API.products.sync(products);

                const scripts = await appInstance.dbGetAll('scripts');
                if (scripts.length > 0) await API.scripts.sync(scripts);

                const schemes = await appInstance.dbGetAll('industry_schemes');
                if (schemes.length > 0) await API.schemes.sync(schemes);

                const visits = await appInstance.dbGetAll('visit_records');
                if (visits.length > 0) await API.visits.sync(visits);

                API.lastSyncTime = new Date().toISOString();
                localStorage.setItem('lastSyncTime', API.lastSyncTime);
                return { success: true, syncTime: API.lastSyncTime };
            } catch (error) {
                console.error('推送失败:', error);
                return { success: false, error: error.message };
            }
        },

        // 从服务器拉取最新数据
        async pull(appInstance) {
            try {
                const lastSync = localStorage.getItem('lastSyncTime') || '';

                // 拉取客户
                const customersResult = await API.customers.getList(lastSync);
                if (customersResult.data?.length > 0) {
                    for (const c of customersResult.data) await appInstance.dbPut('customers', c);
                }

                // 拉取产品（容错）
                try {
                    const productsResult = await API.products.getList();
                    if (productsResult.data?.length > 0) {
                        for (const p of productsResult.data) await appInstance.dbPut('products', p);
                    }
                } catch (e) { console.warn('拉取产品失败:', e.message); }

                // 拉取话术（容错）
                try {
                    const scriptsResult = await API.scripts.getList();
                    if (scriptsResult.data?.length > 0) {
                        for (const s of scriptsResult.data) await appInstance.dbPut('scripts', s);
                    }
                } catch (e) { console.warn('拉取话术失败:', e.message); }

                // 拉取行业方案
                try {
                    const schemesResult = await API.schemes.getList(lastSync);
                    if (schemesResult.data?.length > 0) {
                        for (const s of schemesResult.data) await appInstance.dbPut('industry_schemes', s);
                    }
                } catch (e) { console.warn('拉取方案失败:', e.message); }

                // 拉取回访记录
                try {
                    const visitsResult = await API.visits.getList();
                    if (visitsResult.data?.length > 0) {
                        for (const v of visitsResult.data) await appInstance.dbPut('visit_records', v);
                    }
                } catch (e) { console.warn('拉取回访记录失败:', e.message); }

                API.lastSyncTime = customersResult.sync_time || new Date().toISOString();
                localStorage.setItem('lastSyncTime', API.lastSyncTime);
                return { success: true, syncTime: API.lastSyncTime };
            } catch (error) {
                console.error('拉取数据失败:', error);
                return { success: false, error: error.message };
            }
        }
    }
};

// =============================================
// 网络状态监听（断网/重连自动处理）
// =============================================
(function initNetworkMonitor() {
    API.lastSyncTime = localStorage.getItem('lastSyncTime');
    API.isOnline = navigator.onLine;

    window.addEventListener('online', async () => {
        API.isOnline = true;
        console.log('[网络] 已恢复联网');
        window.dispatchEvent(new CustomEvent('crv:online'));

        // 重连后自动回放离线队列
        const result = await API.flushOfflineQueue();
        if (result.flushed > 0) {
            window.dispatchEvent(new CustomEvent('crv:offline-flushed', { detail: result }));
        }
    });

    window.addEventListener('offline', () => {
        API.isOnline = false;
        console.log('[网络] 已断网，切换为离线模式');
        window.dispatchEvent(new CustomEvent('crv:offline'));
    });
})();
