const axios = require('axios');
const qs = require('querystring');
const dns = require('dns').promises;
const net = require('net');


class AdminSession {
    constructor(options = {}) {
        this.baseURL = 'https://admin.wqxsw.com';
        this.dnsServers = options.dnsServers || ['8.8.8.8', '8.8.4.4', '223.5.5.5', '223.6.6.6'];
        this.maxRetries = options.maxRetries || 3;
        this.currentRetry = 0;

        this.axiosInstance = axios.create({
            baseURL: this.baseURL,
            timeout: options.timeout || 15000,
            headers: {
                'accept': 'application/json, text/javascript, */*; q=0.01',
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'x-requested-with': 'XMLHttpRequest'
            }
        });
    }

    async checkDNS() {
        console.log('开始DNS诊断...');
        
        for (const server of this.dnsServers) {
            try {
                // 临时设置DNS服务器
                dns.setServers([server]);
                console.log(`尝试使用DNS服务器 ${server}...`);
                
                const result = await dns.resolve4('admin.wqxsw.com');
                console.log(`使用DNS ${server} 解析成功:`, result);
                return result[0]; // 返回第一个IP地址
            } catch (error) {
                console.log(`DNS ${server} 解析失败:`, error.message);
            }
        }
        throw new Error('所有DNS服务器解析失败');
    }

    async tryDirectIP() {
        // 已知的备用IP地址列表
        const knownIPs = [
            '47.94.253.153',   // 示例IP，需要替换为实际的IP
            '47.94.253.154'    // 备用IP
        ];

        for (const ip of knownIPs) {
            try {
                console.log(`尝试直接使用IP: ${ip}`);
                const response = await axios.get(`http://${ip}`, {
                    headers: {
                        'Host': 'admin.wqxsw.com'
                    },
                    timeout: 5000
                });
                if (response.status === 200) {
                    console.log(`IP ${ip} 连接成功`);
                    return ip;
                }
            } catch (error) {
                console.log(`IP ${ip} 连接失败:`, error.message);
            }
        }
        return null;
    }

    async login(username = 'zydx16', password = 'Xuan6963') {
        try {
            // 先进行DNS检查
            let targetHost = this.baseURL;
            try {
                const ip = await this.checkDNS();
                console.log('DNS解析成功，使用解析后的IP:', ip);
                targetHost = `https://${ip}`;
            } catch (error) {
                console.log('DNS解析失败，尝试使用直连IP...');
                const directIP = await this.tryDirectIP();
                if (directIP) {
                    targetHost = `https://${directIP}`;
                }
            }

            // 更新axios实例的baseURL
            this.axiosInstance.defaults.baseURL = targetHost;

            // 添加重要的请求头
            const headers = {
                'Host': 'admin.wqxsw.com',
                'Referer': `${this.baseURL}/admin/index/login?url=%2Fadmin%2Fnotice%2Findex%3Fref%3Daddtabs`,
                'Cookie': 'PHPSESSID=vi938g4mfaqjeelunmjmfa68tn'
            };

            // 发送登录请求
            const response = await this.axiosInstance.post(
                '/admin/index/login',
                qs.stringify({
                    __token__: 'ef1d4c4197af8484b14c26108ba41d1c',
                    username,
                    password,
                    keeplogin: 1
                }),
                {
                    headers,
                    params: {
                        url: '/admin/notice/index?ref=addtabs'
                    }
                }
            );

            return response.data;
        } catch (error) {
            if (this.currentRetry < this.maxRetries) {
                this.currentRetry++;
                console.log(`登录失败，第 ${this.currentRetry} 次重试...`);
                await new Promise(resolve => setTimeout(resolve, 2000));
                return this.login(username, password);
            }

            const errorInfo = {
                message: error.message,
                code: error.code,
                config: error.config,
                timestamp: new Date().toISOString()
            };

            if (error.response) {
                errorInfo.status = error.response.status;
                errorInfo.data = error.response.data;
            }

            console.error('登录失败:', errorInfo);
            throw error;
        }
    }
}

// 使用示例
async function main() {
    const session = new AdminSession({
        maxRetries: 3,
        timeout: 15000
    });

    try {
        console.log('开始登录...');
        const result = await session.login();
        console.log('登录结果:', result);
    } catch (error) {
        console.error('登录失败:', error.message);
        
        // 提供解决建议
        console.log('\n可能的解决方案:');
        console.log('1. 检查网络连接是否正常');
        console.log('2. 检查本地hosts文件');
        console.log('3. 尝试清除DNS缓存:');
        console.log('   Windows: ipconfig /flushdns');
        console.log('   Linux: sudo systemctl restart systemd-resolved');
        console.log('   Mac: sudo killall -HUP mDNSResponder');
        console.log('4. 尝试使用其他DNS服务器');
        console.log('5. 检查服务器是否可访问');
    }
}

// 运行测试

function login(){
    main().catch(console.error);
}
module.exports = {login};