/**
 * HTTP请求工具模块
 */

interface HttpRequestOptions {
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: any;
    header?: Record<string, string>;
    timeout?: number;
}

interface HttpResponse<T = any> {
    data: T;
    statusCode: number;
    header: Record<string, string>;
}

/**
 * 发起HTTP请求
 * @param options 请求配置
 * @returns Promise<HttpResponse<T>>
 */
export function request<T = any>(options: HttpRequestOptions): Promise<HttpResponse<T>> {
    return new Promise((resolve, reject) => {
        wx.request({
            url: options.url,
            method: options.method || 'GET',
            data: options.data,
            header: {
                'Content-Type': 'application/json',
                ...options.header
            },
            timeout: options.timeout || 10000,
            success: (res) => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve({
                        data: res.data as T,
                        statusCode: res.statusCode,
                        header: res.header as Record<string, string>
                    });
                } else {
                    reject(new Error(`HTTP ${res.statusCode}: ${res.data}`));
                }
            },
            fail: (err) => {
                reject(new Error(`请求失败: ${err.errMsg || '网络错误'}`));
            }
        });
    });
}

/**
 * GET请求
 * @param url 请求地址
 * @param options 额外配置
 * @returns Promise<HttpResponse<T>>
 */
export function get<T = any>(url: string, options?: Partial<HttpRequestOptions>): Promise<HttpResponse<T>> {
    return request<T>({
        url,
        method: 'GET',
        ...options
    });
}

/**
 * POST请求
 * @param url 请求地址
 * @param data 请求数据
 * @param options 额外配置
 * @returns Promise<HttpResponse<T>>
 */
export function post<T = any>(url: string, data?: any, options?: Partial<HttpRequestOptions>): Promise<HttpResponse<T>> {
    return request<T>({
        url,
        method: 'POST',
        data,
        ...options
    });
}

/**
 * 下载文件
 * @param url 文件地址
 * @param options 额外配置
 * @returns Promise<ArrayBuffer>
 */
export function download(url: string, options?: { timeout?: number }): Promise<ArrayBuffer> {
    return new Promise((resolve, reject) => {
        wx.downloadFile({
            url,
            timeout: options?.timeout || 10000,
            success: (res) => {
                if (res.statusCode === 200) {
                    // @ts-ignore
                    resolve(res.data);
                } else {
                    reject(new Error(`下载失败: HTTP ${res.statusCode}`));
                }
            },
            fail: (err) => {
                reject(new Error(`下载失败: ${err.errMsg || '网络错误'}`));
            }
        });
    });
}

/**
 * 获取JSON数据
 * @param url JSON文件地址
 * @param options 额外配置
 * @returns Promise<T>
 */
export async function getJson<T = any>(url: string, options?: Partial<HttpRequestOptions>): Promise<T> {
    try {
        const response = await get<T>(url, options);
        return response.data;
    } catch (error) {
        console.error('获取JSON数据失败:', error);
        throw error;
    }
}
