const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');

class ProxyService {
    constructor() {
        this.proxyConfig = {
            host: 'd528.kdltps.com',
            port: '15818',
            username: 't13322192973984',
            password: '7ntreedr'
        };
        
        // 创建代理实例
        this.proxyAgent = new HttpsProxyAgent(`http://${this.proxyConfig.username}:${this.proxyConfig.password}@${this.proxyConfig.host}:${this.proxyConfig.port}`);
        
        // 创建axios实例
        this.client = axios.create({
            timeout: 30000,
            httpAgent: this.proxyAgent,
            httpsAgent: this.proxyAgent
        });
    }

    async proxyRequest(options) {
        try {
            const response = await this.client({
                url: options.url,
                method: options.method || 'post',
                headers: options.headers,
                validateStatus: function(status) {
                    return status >= 200 && status < 300;
                }
            });
            
            return response.data;
        } catch (error) {
            return this.handleError(error);
        }
    }

    handleError(error) {
        if (error.response) {
            // 服务器响应错误
            console.error('Response error:', {
                status: error.response.status,
                data: error.response.data
            });
        } else if (error.request) {
            // 请求发送失败
            console.error('Request error:', error.message);
        } else {
            // 其他错误
            console.error('Error:', error.message);
        }

        if (error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT') {
            console.error('Connection error:', error.code);
        }

        throw error;
    }

    // 添加重试机制
    async proxyRequestWithRetry(options, maxRetries = 3, delay = 1000) {
        for (let i = 0; i < maxRetries; i++) {
            try {
                return await this.proxyRequest(options);
            } catch (error) {
                if (i === maxRetries - 1) throw error;
                
                console.log(`Retry attempt ${i + 1} of ${maxRetries}`);
                await new Promise(resolve => setTimeout(resolve, delay * (i + 1)));
            }
        }
    }
}

// 使用示例
// async function example() {
//     const proxyService = new ProxyService();
    
//     try {
//         const result = await proxyService.proxyRequestWithRetry({
//             url: 'https://api.example.com/data',
//             method: 'post',
//             headers: {
//                 'Content-Type': 'application/json'
//             },
//             data: {
//                 key: 'value'
//             }
//         });
        
//         console.log('Success:', result);
//     } catch (error) {
//         console.error('Final error:', error);
//     }
// }

// // 批量请求处理
// class BatchProxyRequests {
//     constructor(proxyService) {
//         this.proxyService = proxyService;
//         this.queue = [];
//         this.concurrency = 3; // 并发数
//     }

//     addRequest(options) {
//         this.queue.push(options);
//     }

//     async processBatch() {
//         const results = [];
        
//         while (this.queue.length > 0) {
//             const batch = this.queue.splice(0, this.concurrency);
//             const promises = batch.map(options => 
//                 this.proxyService.proxyRequestWithRetry(options)
//                     .catch(error => ({ error }))
//             );
            
//             const batchResults = await Promise.all(promises);
//             results.push(...batchResults);
//         }
        
//         return results;
//     }
// }


module.exports = ProxyService;