/**
 * Admin Console - API
 * API 封装（请求拦截、错误处理、加载状态）
 */

// 全局加载状态管理（与小程序 wx.showLoading/hideLoading 保持一致）
const LoadingManager = {
    _count: 0,

    show(message = '加载中...') {
        this._count++;

        // 如果已存在，只更新文本
        let loading = document.getElementById('global-loading');
        if (loading) {
            const textEl = loading.querySelector('.global-loading-text');
            if (textEl) textEl.textContent = message;
            return;
        }

        loading = document.createElement('div');
        loading.id = 'global-loading';
        loading.className = 'global-loading';
        loading.innerHTML = `
            <div class="global-loading-mask"></div>
            <div class="global-loading-content">
                <div class="global-loading-spinner">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10" stroke-opacity="0.25"/>
                        <path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round">
                            <animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite"/>
                        </path>
                    </svg>
                </div>
                <div class="global-loading-text">${message}</div>
            </div>
        `;
        document.body.appendChild(loading);
    },

    hide() {
        this._count = Math.max(0, this._count - 1);
        // 只有所有请求都完成时才移除
        if (this._count <= 0) {
            const loading = document.getElementById('global-loading');
            if (loading) {
                loading.remove();
            }
            this._count = 0;
        }
    }
};

// 生成 Trace ID（简单实现，与小程序雪花算法保持一致的追踪功能）
function generateTraceId(url = '', method = 'GET') {
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).substr(2, 8);
    return `${timestamp}-${random}`;
}

const API = {
    // 基础配置 - 统一使用 /api/living 前缀（与小程序一致）
    baseURL: window.CONFIG?.API_BASE_URL || '/api/living',
    _refreshPromise: null,

    /**
     * 获取请求头（与小程序 getRequestHeaders 保持一致）
     * @param {string} url - 请求 URL
     * @param {string} method - 请求方法
     * @returns {Object}
     */
    getHeaders(url = '', method = 'GET') {
        const headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Traceid': generateTraceId(url, method)  // Trace ID 用于日志追踪
        };

        // 添加认证 token（与小程序保持一致：直接传 token，不使用 Bearer 前缀）
        const token = Auth.getToken();
        if (token) {
            headers['Authorization'] = token;
        }

        // 用户身份只以 JWT 为准，避免显式 openId 请求头被伪造后造成前后端误判。
        const userId = Auth.getUserId?.();
        if (userId) {
            headers['X-Userid'] = userId;
        }

        return headers;
    },

    /**
     * 发送请求（与小程序 request 保持一致：支持 loading 和错误处理）
     * @param {string} url - 请求地址
     * @param {Object} options - 请求选项
     * @param {boolean} showLoading - 是否显示加载提示，默认false
     * @returns {Promise}
     */
    async request(url, options = {}, showLoading = false, retryOnAuthFailure = true) {
        const fullURL = url.startsWith('http') ? url : `${this.baseURL}`;
        const method = options.method || 'GET';

        if (showLoading) {
            LoadingManager.show('加载中...');
        }

        const config = {
            method: method,
            headers: this.getHeaders(url, method),
            ...options
        };

        // 处理请求体
        if (config.body && typeof config.body === 'object' && !(config.body instanceof FormData)) {
            config.body = JSON.stringify(config.body);
        }

        try {
            const response = await fetch(fullURL, config);

            // 处理 HTTP 错误状态
            if (!response.ok) {
                if (response.status === 401) {
                    if (retryOnAuthFailure && !url.includes('/token/refresh')) {
                        const refreshed = await this.refreshAccessToken();
                        if (refreshed) {
                            return this.request(url, options, showLoading, false);
                        }
                    }
                    Auth.expireSession();
                    return Promise.reject(new Error('登录已过期，请重新登录'));
                }

                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();

            // 处理业务错误
            if (data.code !== 200 && data.code !== 0 && !data.success) {
                throw new Error(data.message || '请求失败');
            }

            return data;
        } catch (error) {
            console.error(`API请求失败 [${method}] :`, error);

            // 用户友好的错误提示（与小程序保持一致）
            // 优先使用后端返回的具体错误信息
            if (typeof Components !== 'undefined' && Components.showToast) {
                let toastMessage = '';
                const errorMessage = error.message || '';

                // 判断错误类型并显示对应的友好提示
                if (errorMessage.includes('Failed to fetch') || errorMessage.includes('NetworkError') || errorMessage.includes('network')) {
                    toastMessage = '网络请求失败，请检查网络连接';
                } else if (errorMessage.includes('401') || errorMessage.includes('登录已过期')) {
                    toastMessage = '登录已过期，请重新登录';
                } else if (errorMessage.includes('403')) {
                    toastMessage = '权限不足';
                } else if (errorMessage.includes('404')) {
                    toastMessage = '请求的资源不存在';
                } else if (errorMessage.includes('500') || errorMessage.includes('502') || errorMessage.includes('503') || errorMessage.includes('504')) {
                    toastMessage = '服务器错误，请稍后重试';
                } else if (errorMessage.includes('timeout')) {
                    toastMessage = '请求超时，请稍后重试';
                } else {
                    // 优先使用后端返回的具体错误信息
                    toastMessage = errorMessage || '请求失败';
                }

                Components.showToast(toastMessage, 'error');
            }

            // 重新抛出错误，让调用方也能处理
            throw error;
        } finally {
            if (showLoading) {
                LoadingManager.hide();
            }
        }
    },

    async refreshAccessToken() {
        const refreshToken = Auth.getRefreshToken();
        if (!refreshToken) {
            return false;
        }

        if (this._refreshPromise) {
            return this._refreshPromise;
        }

        this._refreshPromise = (async () => {
            try {
                const response = await fetch(`${this.baseURL}/token/refresh`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        token: Auth.getToken(),
                        refreshToken: refreshToken
                    })
                });

                const data = await response.json().catch(() => ({}));
                if (!response.ok || !data.success || !data.data?.token || !data.data?.refreshToken) {
                    return false;
                }

                Auth.setToken(data.data.token);
                Auth.setRefreshToken(data.data.refreshToken);
                return true;
            } catch (error) {
                console.error('刷新管理后台 token 失败:', error);
                return false;
            } finally {
                this._refreshPromise = null;
            }
        })();

        return this._refreshPromise;
    },

    /**
     * GET 请求
     * @param {string} url
     * @param {Object} params - 查询参数
     * @returns {Promise}
     */
    get(url, params = {}) {
        const queryString = Object.keys(params)
            .filter(key => params[key] !== undefined && params[key] !== null)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join('&');

        const fullURL = queryString ? `?${queryString}` : url;
        return this.request(fullURL, { method: 'GET' });
    },

    /**
     * POST 请求
     * @param {string} url
     * @param {Object} data
     * @returns {Promise}
     */
    post(url, data = {}) {
        return this.request(url, {
            method: 'POST',
            body: data
        });
    },

    /**
     * PUT 请求
     * @param {string} url
     * @param {Object} data
     * @returns {Promise}
     */
    put(url, data = {}) {
        return this.request(url, {
            method: 'PUT',
            body: data
        });
    },

    /**
     * DELETE 请求
     * @param {string} url
     * @returns {Promise}
     */
    delete(url) {
        return this.request(url, { method: 'DELETE' });
    },

    // ==================== 认证相关 API ====================
    auth: {
        /**
         * 管理员登录
         * @param {string} phone - 手机号
         * @param {string} password - 密码
         * @returns {Promise}
         */
        async login(phone, password) {
            const fullURL = `${API.baseURL}/admin/login`;

            try {
                const response = await fetch(fullURL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ phone, password })
                });

                const data = await response.json();

                // 登录失败返回401，但不触发expireSession
                if (!response.ok) {
                    return {
                        success: false,
                        message: data.message || '账号或密码错误'
                    };
                }

                return data;
            } catch (error) {
                console.error('登录请求失败:', error);
                return {
                    success: false,
                    message: '网络错误，请检查网络连接'
                };
            }
        },

        async logout() {
            const token = Auth.getToken();
            const refreshToken = Auth.getRefreshToken();
            if (!token && !refreshToken) {
                return { success: true };
            }

            try {
                return await API.post('/token/logout', {
                    token: token,
                    refreshToken: refreshToken
                });
            } catch (error) {
                return { success: false, message: error.message || '退出失败' };
            }
        },

        /**
         * 获取当前用户信息
         * @returns {Promise}
         */
        getCurrentUser() {
            return API.get('/admin/current-user');
        }
    },

    // ==================== 用户授权 API ====================
    users: {
        /**
         * 获取授权用户列表（参考小程序：roleAPI.getUsersByRoleName('AUTHORIZED')）
         * @param {Object} params
         * @returns {Promise}
         */
        async getList(params = {}) {
            const response = await API.get('/user/roles/role/AUTHORIZED/users', params);

            if (response.success && response.data) {
                const list = Array.isArray(response.data)
                    ? response.data
                    : (response.data.list || response.data.users || []);
                const total = response.meta?.pagination?.total || response.data.total || list.length;
                const pages = response.meta?.pagination?.totalPages
                    || response.data.pages
                    || response.data.totalPages
                    || Math.ceil(total / (params.limit || 10));

                return {
                    success: true,
                    data: {
                        list: list,
                        total: total,
                        pages: pages
                    }
                };
            }

            return response;
        },

        async getSalesList(params = {}) {
            const response = await API.get('/user/roles/sales-users', params);

            if (response.success && response.data) {
                const list = Array.isArray(response.data)
                    ? response.data
                    : (response.data.list || response.data.users || []);
                const total = response.meta?.pagination?.total || response.data.total || list.length;
                const pages = response.meta?.pagination?.totalPages
                    || response.data.pages
                    || response.data.totalPages
                    || Math.ceil(total / (params.limit || 10));

                return {
                    success: true,
                    data: {
                        list: list,
                        total: total,
                        pages: pages
                    }
                };
            }

            return response;
        },

        /**
         * 添加授权用户（参考小程序：roleAPI.assignRole）
         * 流程：1. 通过手机号搜索用户获取 openId  2. 分配 AUTHORIZED 角色
         * @param {Object} data - 包含 username(昵称), phone(手机号)
         * @returns {Promise}
         */
        async create(data) {
            // 1. 通过手机号搜索用户
            const searchResponse = await API.get('/user/search', { keyword: data.phone, page: 1, limit: 10 });

            if (!searchResponse.success || !searchResponse.data) {
                throw new Error('搜索用户失败');
            }

            const users = Array.isArray(searchResponse.data)
                ? searchResponse.data
                : (searchResponse.data.list || searchResponse.data.users || []);

            // 找到匹配手机号的用户
            const targetUser = users.find(u => u.phone === data.phone || u.phone === data.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'));

            if (!targetUser) {
                throw new Error('未找到该手机号的用户，请先让用户登录小程序');
            }

            // 2. 分配 AUTHORIZED 角色
            return API.post('/user/roles', {
                openId: targetUser.openId,
                roleName: 'AUTHORIZED'
            });
        },

        /**
         * 删除授权用户（参考小程序：roleAPI.removeRole）
         * @param {string} openId - 用户openId
         * @returns {Promise}
         */
        delete(openId) {
            return API.request('/user/roles', {
                method: 'DELETE',
                body: { openId: openId, roleName: 'AUTHORIZED' }
            });
        }
    },

    // ==================== 库存管理 API ====================
    inventory: {
        /**
         * 获取库存列表（使用商品API）
         * @param {Object} params
         * @returns {Promise}
         */
        async getList(params = {}) {
            const response = await API.get('/products', params);

            if (response.success && response.data) {
                const list = Array.isArray(response.data)
                    ? response.data
                    : (response.data.list || response.data.products || []);
                const total = response.meta?.pagination?.total || response.data.total || list.length;
                const pages = response.meta?.pagination?.totalPages
                    || response.data.pages
                    || response.data.totalPages
                    || Math.ceil(total / (params.limit || 10));

                return {
                    success: true,
                    data: {
                        list: list,
                        total: total,
                        pages: pages
                    }
                };
            }

            return response;
        },

        /**
         * 调整库存（使用商品库存更新API）
         * @param {number} productId
         * @param {Object} data
         * @returns {Promise}
         */
        adjust(productId, data) {
            // 根据类型处理不同的库存调整
            const { type, quantity, reservedQuantity, remark, threshold } = data;
            let stockData = {};

            if (type === 'SET_THRESHOLD') {
                // 设置阈值 - 使用报告API
                return API.post('/reports/inventory/threshold', { threshold });
            } else if (type === 'ADD') {
                // 增加总库存
                stockData = { stockDelta: quantity };
            } else if (type === 'SUBTRACT') {
                // 减少总库存
                stockData = { stockDelta: -quantity };
            } else if (type === 'SET') {
                // 设置总库存为指定值
                stockData = { stock: quantity };
            } else if (type === 'ADD_RESERVED') {
                // 增加预定量
                stockData = { reservedStockDelta: reservedQuantity };
            } else if (type === 'SUBTRACT_RESERVED') {
                // 减少预定量
                stockData = { reservedStockDelta: -reservedQuantity };
            } else if (type === 'SET_RESERVED') {
                // 设置预定量为指定值
                stockData = { reservedStock: reservedQuantity };
            }

            return API.put(`/products/${productId}/stock`, stockData);
        },

        /**
         * 批量更新商品库存
         * @param {Array} products - 商品更新列表 [{id, stockDelta, reservedStockDelta}]
         * @returns {Promise}
         */
        batchUpdate(products) {
            return API.put('/products/batch-stock', { products });
        },

        /**
         * 批量更新SKU库存
         * @param {Array} skus - SKU更新列表 [{productId, skuId, stockDelta, reservedStockDelta}]
         * @returns {Promise}
         */
        batchUpdateSku(skus) {
            return API.put('/products/batch-sku-stock', {
                skus: skus.map(sku => {
                    const item = {
                        productId: sku.productId,
                        skuId: sku.skuId,
                        stockDelta: sku.stockDelta
                    };
                    if (sku.reservedStockDelta !== undefined) {
                        item.reservedStockDelta = sku.reservedStockDelta;
                    }
                    if (sku.price !== undefined) {
                        item.price = sku.price;
                    }
                    return item;
                })
            });
        },

        /**
         * 调整单个SKU库存（支持库存和预留库存增量调整）
         * @param {string} productId 商品ID
         * @param {number} skuId SKU ID
         * @param {Object} data 调整数据 {stockDelta, reservedStockDelta}
         * @returns {Promise}
         */
        adjustSkuStock(productId, skuId, data) {
            return API.put(`/products/${productId}/sku/${skuId}/stock`, data);
        },

        /**
         * 设置预警阈值（使用报告API）
         * @param {number} threshold
         * @returns {Promise}
         */
        setThreshold(threshold) {
            return API.post('/reports/inventory/threshold', { threshold });
        },

        /**
         * 获取预警商品列表（使用商品API筛选低库存商品）
         * @returns {Promise}
         */
        async getWarnings() {
            // 获取所有商品，筛选出低库存商品
            const response = await API.get('/products', { page: 1, limit: 100 });

            // 后端返回格式：{ success: true, data: { list/products, ... } }
            if (response.success && response.data) {
                const data = response.data;
                const list = data.list || data.products || [];

                // 筛选低库存商品（availableStock <= threshold 或 availableStock <= 10）
                const warnings = list.filter(item => {
                    const stock = item.availableStock !== undefined ? item.availableStock : (item.currentStock || 0);
                    const threshold = item.threshold || 10;
                    return stock <= threshold;
                }).map(item => ({
                    productId: item.id,
                    productName: item.name,
                    productCode: item.id,
                    stock: item.availableStock !== undefined ? item.availableStock : (item.currentStock || 0),
                    threshold: item.threshold || 10,
                    status: item.status || 'ACTIVE',
                    updatedAt: item.updatedAt || item.createdAt
                }));

                return {
                    success: true,
                    data: warnings
                };
            }

            return response;
        }
    },

    // ==================== 订单管理 API ====================
    orders: {
        /**
         * 获取订单列表（参考小程序：GET /order/all）
         * @param {Object} params
         * @returns {Promise}
         */
        async getList(params = {}) {
            const response = await API.get('/order/all', params);

            // 后端返回格式：{ success: true, data: { orders, total, ... } }
            if (response.success && response.data) {
                const data = response.data;
                // 从 data 中获取订单列表
                const orders = data.orders || [];
                const total = data.total || 0;

                return {
                    success: true,
                    data: {
                        list: orders,
                        total: total,
                        totalPages: data.totalPages || Math.ceil(total / (params.limit || 10))
                    }
                };
            }

            return response;
        },

        /**
         * 获取订单详情（参考小程序）
         * @param {number} id
         * @returns {Promise}
         */
        async getDetail(id) {
            const response = await API.get(`/order/detail/com.livingstore:living-store-api:jar:0.2.0`);

            // 后端返回格式：{ success: true, data: { order, items } }
            if (response.success && response.data) {
                const data = response.data;
                return {
                    success: true,
                    data: {
                        order: data.order || {},
                        items: data.items || []
                    }
                };
            }

            return response;
        },

        /**
         * 更新订单状态（参考小程序）
         * @param {number} id
         * @param {string} status
         * @returns {Promise}
         */
        updateStatus(id, status) {
            return API.put(`/order/com.livingstore:living-store-api:jar:0.2.0/status`, { status });
        },

        /**
         * 分配销售人员（参考小程序）
         * @param {number} id
         * @param {number} salesId
         * @returns {Promise}
         */
        assignSales(id, salesId) {
            return API.put(`/order/com.livingstore:living-store-api:jar:0.2.0/assign`, { salesId });
        },

        /**
         * 处理订单（接单）- 支持修改商品单价
         * @param {number} id - 订单ID
         * @param {Object} data - 请求数据
         * @param {Array} data.items - 商品列表（含新单价）
         * @param {string} data.remark - 备注
         * @returns {Promise}
         */
        processOrder(id, data) {
            return API.post(`/order/com.livingstore:living-store-api:jar:0.2.0/process`, data);
        },

        /**
         * 更新已接单订单明细
         * @param {number} id - 订单ID
         * @param {Object} data - 请求数据
         * @returns {Promise}
         */
        updateItems(id, data) {
            return API.put(`/order/com.livingstore:living-store-api:jar:0.2.0/items`, data);
        },

        /**
         * 管理端代客户创建订单
         * @param {Object} data - {customerName, customerPhone, customerAddress, items, idempotencyKey}
         * @returns {Promise}
         */
        adminCreate(data) {
            return API.post('/order/admin-create', data);
        },

        /**
         * 配送订单
         * @param {number} id - 订单ID
         * @returns {Promise}
         */
        ship(id) {
            return API.post(`/order/com.livingstore:living-store-api:jar:0.2.0/ship`);
        },

        /**
         * 生成订单小票
         * @deprecated 请使用 getReceipt 代替
         * @param {number} id - 订单ID
         * @returns {Promise}
         */
        generateReceipt(id) {
            return API.post(`/order/com.livingstore:living-store-api:jar:0.2.0/generate-receipt`);
        },

        /**
         * 重新生成订单小票
         * @param {number} id - 订单ID
         * @returns {Promise}
         */
        regenerateReceipt(id) {
            return API.post(`/order/com.livingstore:living-store-api:jar:0.2.0/regenerate-receipt`);
        },

        getReceiptUrl(id) {
            return API.get(`/order/com.livingstore:living-store-api:jar:0.2.0/receipt-url`);
        },

        /**
         * 获取或生成订单小票 URL（统一接口）
         * @param {number} id - 订单ID
         * @returns {Promise}
         */
        getReceipt(id) {
            return API.get(`/order/com.livingstore:living-store-api:jar:0.2.0/receipt`);
        },

        /**
         * 获取后端渲染的小票预览 HTML
         * @param {number} id - 订单ID
         * @returns {Promise}
         */
        getReceiptPreview(id) {
            return API.get(`/order/com.livingstore:living-store-api:jar:0.2.0/receipt-preview`);
        }
    },

    // ==================== 报表 API ====================
    reports: {
        /**
         * 获取数据概览（参考小程序：ReportUtil.getOverview）
         * @param {Object} params
         * @returns {Promise}
         */
        async getOverview(params = {}) {
            const response = await API.get('/reports/overview', params);

            // 后端返回格式：{ success: true, data: { ... } }
            if (response.success && response.data) {
                const data = response.data;
                return {
                    success: true,
                    data: {
                        productTotal: data.productTotal || data.productCount || 0,
                        orderTotal: data.orderTotal || data.orderCount || 0,
                        salesToday: data.salesToday || data.todaySales || 0,
                        inventoryWarning: data.inventoryWarning || data.lowStockCount || 0
                    }
                };
            }

            return response;
        },

        /**
         * 获取商品分析（参考小程序：ReportUtil.getProductReport）
         * @param {Object} params
         * @returns {Promise}
         */
        async getProductAnalysis(params = {}) {
            const response = await API.get('/reports/products', params);

            // 后端返回格式：{ success: true, data: { ... } }
            if (response.success && response.data) {
                const data = response.data;

                // 处理分类数据
                const byCategory = (data.byCategory || [])
                    .map(item => ({
                        name: item.name || item.categoryName || '未分类',
                        count: item.count || item.productCount || 0,
                        percentage: item.percentage || 0
                    }));

                // 计算上下架数量
                const total = data.total || data.totalProducts || 0;
                const onSale = data.onSale || data.activeProducts || 0;
                const offSale = data.offSale || data.inactiveProducts || (total - onSale);

                return {
                    success: true,
                    data: {
                        total: total,
                        onSale: onSale,
                        offSale: offSale,
                        byCategory: byCategory,
                        inventory: {
                            total: data.inventory?.total || total,
                            warningCount: data.inventory?.warningCount || 0,
                            zeroCount: data.inventory?.zeroCount || 0,
                            healthyRate: data.inventory?.healthyRate || 0,
                            warningItems: data.inventory?.warningItems || []
                        }
                    }
                };
            }

            return response;
        },

        /**
         * 获取订单分析（参考小程序：ReportUtil.getOrderReport）
         * @param {Object} params
         * @returns {Promise}
         */
        async getOrderAnalysis(params = {}) {
            const response = await API.get('/reports/orders', params);

            // 后端返回格式：{ success: true, data: { ... } }
            if (response.success && response.data) {
                const data = response.data;

                // 处理状态分布
                const status = data.status || {};

                return {
                    success: true,
                    data: {
                        total: data.total || data.totalOrders || 0,
                        today: data.today || data.todayOrders || 0,
                        thisWeek: data.thisWeek || data.weekOrders || 0,
                        thisMonth: data.thisMonth || data.monthOrders || 0,
                        sales: {
                            total: data.sales?.total || data.totalAmount || 0,
                            today: data.sales?.today || data.todayAmount || 0,
                            thisWeek: data.sales?.thisWeek || data.weekAmount || 0,
                            thisMonth: data.sales?.thisMonth || data.monthAmount || 0,
                            average: data.sales?.average || data.avgAmount || 0
                        },
                        status: {
                            pending: status.pending || 0,
                            processing: status.processing || 0,
                            completed: status.completed || 0,
                            cancelled: status.cancelled || 0,
                            completionRate: status.completionRate || 0
                        },
                        trend: data.trend || []
                    }
                };
            }

            return response;
        },

        /**
         * 获取销售业绩（参考小程序：ReportUtil.getSalesReport）
         * @param {Object} params
         * @returns {Promise}
         */
        async getSalesPerformance(params = {}) {
            const response = await API.get('/reports/sales', params);

            // 后端返回格式：{ success: true, data: { rankings, ... } }
            if (response.success && response.data) {
                const data = response.data;

                // 处理排名数据
                const rankings = (data.rankings || [])
                    .map(item => ({
                        salesId: item.salesId || item.userId || 0,
                        userId: item.userId || item.salesId || 0,
                        salesName: item.salesName || item.userName || '未知',
                        userName: item.userName || item.salesName || '未知',
                        avatar: item.avatar || item.salesAvatar || item.userAvatar || null,
                        totalAmount: item.totalAmount || item.salesAmount || 0,
                        salesAmount: item.salesAmount || item.totalAmount || 0,
                        orderCount: item.orderCount || 0,
                        avgOrderValue: item.avgOrderValue || 0,
                        avgProcessTime: item.avgProcessTime || 0,
                        rank: item.rank || 0
                    }));

                return {
                    success: true,
                    data: {
                        totalSalesPerson: data.totalSalesPerson || rankings.length,
                        rankings: rankings
                    }
                };
            }

            return response;
        },

        /**
         * 导出报表（参考小程序：ReportUtil.exportReport）
         * @param {string} type - 报表类型
         * @param {Object} params
         * @returns {Promise}
         */
        exportReport(type, params = {}) {
            return API.post(`/reports/export/${type}`, params);
        },

        /**
         * 设置库存预警阈值（参考小程序：ReportUtil.setInventoryWarningThreshold）
         * @param {number} threshold
         * @returns {Promise}
         */
        setInventoryThreshold(threshold) {
            return API.post('/reports/inventory/threshold', { threshold });
        }
    },

    // ==================== 商品 API ====================
    products: {
        /**
         * 获取商品列表
         * @param {Object} params
         * @returns {Promise}
         */
        getList(params = {}) {
            return API.get('/products', params);
        },

        /**
         * 获取分类列表
         * @returns {Promise}
         */
        getCategories() {
            return API.get('/categories');
        },

        /**
         * 获取商品规格列表
         * @param {string} productId 商品ID
         * @returns {Promise}
         */
        getSkus(productId) {
            return API.get(`/products/${productId}/skus`);
        },

        /**
         * 批量更新SKU库存
         * @deprecated 请使用 API.inventory.batchUpdateSku 或 API.inventory.adjustSkuStock
         * @param {string} productId 商品ID
         * @param {Array} skuItems SKU库存列表 [{skuId, stock}]
         * @returns {Promise}
         */
        updateSkuStock(productId, skuItems) {
            return API.post(`/products/${productId}/skus/stock`, { skuItems });
        }
    },

    // ==================== 分类 API ====================
    categories: {
        /**
         * 获取分类列表
         * @returns {Promise}
         */
        getList() {
            return API.get('/categories');
        }
    },

    // ==================== 存储 API ====================
    storage: {
        /**
         * 获取文件预签名 URL
         * @param {string} relativePath - 文件相对路径
         * @param {number} expirationTime - 过期时间（秒），默认 3600
         * @returns {Promise} 预签名 URL
         */
        async getPresignedUrl(relativePath, expirationTime = 3600) {
            try {
                // 使用 GET 方法获取预签名 URL
                const response = await API.get('/storage/presigned-url', {
                    objectPath: relativePath,
                    expiration: expirationTime
                });
                // 后端返回格式：{ success: true, url: ... }
                if (response.success && response.url) {
                    const url = response.url || '';
                    if (!url) {
                        console.warn('获取预签名 URL 为空:', relativePath);
                    }
                    return url;
                }
                console.warn('获取预签名 URL 失败:', relativePath, response);
                return '';
            } catch (error) {
                console.error('获取预签名 URL 失败:', relativePath, error);
                return '';
            }
        }
    }
};

// 导出 API
window.API = API;
