import Taro from '@tarojs/taro';

/**
 * 网络连接检测工具
 */
export class NetworkChecker {
  /**
   * 检查网络连接状态
   */
  static async checkNetworkStatus(): Promise<{
    isConnected: boolean;
    networkType: string;
    message: string;
  }> {
    try {
      const networkInfo = await Taro.getNetworkType();
      const isConnected = networkInfo.networkType !== 'none';
      
      return {
        isConnected,
        networkType: networkInfo.networkType,
        message: isConnected 
          ? `网络连接正常 (${networkInfo.networkType})` 
          : '网络连接异常'
      };
    } catch (error) {
      console.error('检查网络状态失败:', error);
      return {
        isConnected: false,
        networkType: 'unknown',
        message: '无法检测网络状态'
      };
    }
  }

  /**
   * 测试API连接
   */
  static async testAPIConnection(baseUrl: string): Promise<{
    success: boolean;
    responseTime: number;
    message: string;
  }> {
    const startTime = Date.now();
    
    try {
      const response = await Taro.request({
        url: `${baseUrl}/health`,
        method: 'GET',
        timeout: 5000
      });
      
      const responseTime = Date.now() - startTime;
      
      return {
        success: response.statusCode === 200,
        responseTime,
        message: `API连接${response.statusCode === 200 ? '正常' : '异常'} (${responseTime}ms)`
      };
    } catch (error) {
      const responseTime = Date.now() - startTime;
      console.error('API连接测试失败:', error);
      
      return {
        success: false,
        responseTime,
        message: `API连接失败 (${responseTime}ms): ${error}`
      };
    }
  }

  /**
   * 综合网络诊断
   */
  static async diagnoseNetwork(baseUrl: string): Promise<{
    network: any;
    api: any;
    suggestions: string[];
  }> {
    console.log('🔍 开始网络诊断...');
    
    const network = await this.checkNetworkStatus();
    const api = await this.testAPIConnection(baseUrl);
    
    const suggestions: string[] = [];
    
    if (!network.isConnected) {
      suggestions.push('请检查网络连接');
      suggestions.push('尝试切换网络环境（WiFi/移动数据）');
    }
    
    if (!api.success) {
      suggestions.push('服务器可能暂时不可用');
      suggestions.push('请稍后重试');
      if (api.responseTime > 10000) {
        suggestions.push('网络响应较慢，建议检查网络质量');
      }
    }
    
    if (network.networkType === 'wifi') {
      suggestions.push('WiFi连接正常，如仍有问题请检查路由器');
    } else if (network.networkType === '4g' || network.networkType === '5g') {
      suggestions.push('移动网络连接，请确保有足够的流量');
    }
    
    console.log('📊 网络诊断结果:', { network, api, suggestions });
    
    return { network, api, suggestions };
  }

  /**
   * 显示网络诊断结果
   */
  static async showNetworkDiagnosis(baseUrl: string) {
    Taro.showLoading({ title: '诊断网络中...', mask: true });
    
    try {
      const diagnosis = await this.diagnoseNetwork(baseUrl);
      Taro.hideLoading();
      
      const content = [
        `网络状态: ${diagnosis.network.message}`,
        `API连接: ${diagnosis.api.message}`,
        '',
        '建议:',
        ...diagnosis.suggestions.map(s => `• ${s}`)
      ].join('\n');
      
      Taro.showModal({
        title: '网络诊断结果',
        content,
        showCancel: false,
        confirmText: '知道了'
      });
    } catch (error) {
      Taro.hideLoading();
      console.error('网络诊断失败:', error);
      
      Taro.showModal({
        title: '诊断失败',
        content: '无法完成网络诊断，请检查网络连接后重试',
        showCancel: false,
        confirmText: '知道了'
      });
    }
  }
}

/**
 * 便捷方法
 */
export const checkNetwork = () => NetworkChecker.checkNetworkStatus();
export const testAPI = (baseUrl: string) => NetworkChecker.testAPIConnection(baseUrl);
export const diagnoseNetwork = (baseUrl: string) => NetworkChecker.diagnoseNetwork(baseUrl);
export const showNetworkDiagnosis = (baseUrl: string) => NetworkChecker.showNetworkDiagnosis(baseUrl);
