/**
 * 百度地图API测试工具
 * 用于诊断和修复百度地图API加载问题
 */

export class BaiduMapTester {
  constructor() {
    this.testResults = [];
    this.isLoading = false;
  }

  /**
   * 运行完整的API测试
   */
  async runFullTest() {
    console.log('🔍 开始百度地图API完整测试...');
    this.testResults = [];
    
    try {
      // 测试1: 检查当前BMap状态
      await this.testCurrentBMapStatus();
      
      // 测试2: 测试API加载
      await this.testApiLoading();
      
      // 测试3: 测试BMap对象功能
      await this.testBMapFunctionality();
      
      // 测试4: 测试地图创建
      await this.testMapCreation();
      
      // 输出测试结果
      this.outputTestResults();
      
    } catch (error) {
      console.error('❌ 测试过程中出现错误:', error);
      this.testResults.push({
        name: '测试过程错误',
        status: 'error',
        message: error.message
      });
    }
    
    return this.testResults;
  }

  /**
   * 测试当前BMap状态
   */
  async testCurrentBMapStatus() {
    console.log('📋 测试1: 检查当前BMap状态');
    
    const result = {
      name: 'BMap状态检查',
      status: 'info',
      details: {}
    };
    
    result.details.bMapExists = typeof window.BMap !== 'undefined';
    result.details.bMapType = typeof window.BMap;
    result.details.bMapValue = window.BMap;
    
    if (window.BMap) {
      result.details.bMapVersion = window.BMap.version || '未知';
      result.details.mapConstructor = typeof window.BMap.Map;
      result.details.pointConstructor = typeof window.BMap.Point;
      result.details.markerConstructor = typeof window.BMap.Marker;
      result.details.infoWindowConstructor = typeof window.BMap.InfoWindow;
      
      if (typeof window.BMap.Map === 'function') {
        result.status = 'success';
        result.message = 'BMap对象已存在且功能完整';
      } else {
        result.status = 'warning';
        result.message = 'BMap对象存在但功能不完整';
      }
    } else {
      result.status = 'error';
      result.message = 'BMap对象不存在，需要加载API';
    }
    
    this.testResults.push(result);
    console.log(`✅ 测试1完成: ${result.message}`);
  }

  /**
   * 测试API加载
   */
  async testApiLoading() {
    console.log('📋 测试2: 测试API加载');
    
    const result = {
      name: 'API加载测试',
      status: 'info',
      details: {}
    };
    
    try {
      // 检查是否已有BMap
      if (typeof window.BMap !== 'undefined') {
        result.status = 'success';
        result.message = 'BMap已存在，跳过API加载测试';
        this.testResults.push(result);
        return;
      }
      
      // 尝试加载API
      result.details.loadingStarted = true;
      const loadPromise = this.loadBMapApi();
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('API加载超时')), 10000)
      );
      
      await Promise.race([loadPromise, timeoutPromise]);
      
      result.status = 'success';
      result.message = 'API加载成功';
      result.details.loadingCompleted = true;
      
    } catch (error) {
      result.status = 'error';
      result.message = `API加载失败: ${error.message}`;
      result.details.error = error.message;
    }
    
    this.testResults.push(result);
    console.log(`✅ 测试2完成: ${result.message}`);
  }

  /**
   * 测试BMap对象功能
   */
  async testBMapFunctionality() {
    console.log('📋 测试3: 测试BMap对象功能');
    
    const result = {
      name: 'BMap功能测试',
      status: 'info',
      details: {}
    };
    
    try {
      if (typeof window.BMap === 'undefined') {
        throw new Error('BMap对象不存在');
      }
      
      // 测试Point创建
      const point = new window.BMap.Point(106.27, 38.47);
      result.details.pointTest = {
        success: true,
        lng: point.lng,
        lat: point.lat
      };
      
      // 测试Marker创建
      const marker = new window.BMap.Marker(point);
      result.details.markerTest = {
        success: true,
        position: marker.getPosition()
      };
      
      // 测试InfoWindow创建
      const infoWindow = new window.BMap.InfoWindow('<div>测试</div>');
      result.details.infoWindowTest = {
        success: true,
        type: typeof infoWindow
      };
      
      result.status = 'success';
      result.message = 'BMap对象功能测试通过';
      
    } catch (error) {
      result.status = 'error';
      result.message = `BMap功能测试失败: ${error.message}`;
      result.details.error = error.message;
    }
    
    this.testResults.push(result);
    console.log(`✅ 测试3完成: ${result.message}`);
  }

  /**
   * 测试地图创建
   */
  async testMapCreation() {
    console.log('📋 测试4: 测试地图创建');
    
    const result = {
      name: '地图创建测试',
      status: 'info',
      details: {}
    };
    
    try {
      if (typeof window.BMap === 'undefined') {
        throw new Error('BMap对象不存在');
      }
      
      // 创建测试容器
      const testContainer = document.createElement('div');
      testContainer.style.width = '100px';
      testContainer.style.height = '100px';
      testContainer.style.position = 'absolute';
      testContainer.style.top = '-1000px';
      testContainer.style.left = '-1000px';
      document.body.appendChild(testContainer);
      
      // 创建地图
      const map = new window.BMap.Map(testContainer);
      result.details.mapCreated = true;
      result.details.mapType = typeof map;
      
      // 测试地图基本功能
      const center = new window.BMap.Point(106.27, 38.47);
      map.centerAndZoom(center, 10);
      result.details.mapConfigured = true;
      
      // 清理测试容器
      document.body.removeChild(testContainer);
      
      result.status = 'success';
      result.message = '地图创建测试通过';
      
    } catch (error) {
      result.status = 'error';
      result.message = `地图创建测试失败: ${error.message}`;
      result.details.error = error.message;
    }
    
    this.testResults.push(result);
    console.log(`✅ 测试4完成: ${result.message}`);
  }

  /**
   * 加载百度地图API
   */
  loadBMapApi() {
    return new Promise((resolve, reject) => {
      if (this.isLoading) {
        reject(new Error('API正在加载中'));
        return;
      }
      
      this.isLoading = true;
      
      const script = document.createElement('script');
      script.src = 'https://api.map.baidu.com/api?v=3.0&ak=fLz8UwJSM3ayYl6dtsWYp7TQ8993R6kC&callback=initBMapTest';
      
      window.initBMapTest = () => {
        this.isLoading = false;
        delete window.initBMapTest;
        resolve();
      };
      
      script.onerror = () => {
        this.isLoading = false;
        delete window.initBMapTest;
        reject(new Error('API脚本加载失败'));
      };
      
      document.head.appendChild(script);
    });
  }

  /**
   * 输出测试结果
   */
  outputTestResults() {
    console.log('\n📊 百度地图API测试结果:');
    console.log('='.repeat(50));
    
    this.testResults.forEach((result, index) => {
      const statusIcon = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
      }[result.status] || '❓';
      
      console.log(`${index + 1}. ${statusIcon} ${result.name}: ${result.message}`);
      
      if (result.details && Object.keys(result.details).length > 0) {
        console.log('   详细信息:', result.details);
      }
    });
    
    console.log('='.repeat(50));
    
    const successCount = this.testResults.filter(r => r.status === 'success').length;
    const totalCount = this.testResults.length;
    
    console.log(`📈 测试总结: ${successCount}/${totalCount} 项测试通过`);
    
    if (successCount === totalCount) {
      console.log('🎉 所有测试通过！百度地图API工作正常。');
    } else {
      console.log('⚠️ 部分测试失败，请检查上述错误信息。');
    }
  }

  /**
   * 获取修复建议
   */
  getFixSuggestions() {
    const suggestions = [];
    
    this.testResults.forEach(result => {
      if (result.status === 'error') {
        switch (result.name) {
          case 'BMap状态检查':
            suggestions.push('1. 检查网络连接是否正常');
            suggestions.push('2. 检查百度地图API密钥是否有效');
            suggestions.push('3. 检查域名白名单配置');
            break;
          case 'API加载测试':
            suggestions.push('1. 尝试刷新页面');
            suggestions.push('2. 检查浏览器控制台是否有CORS错误');
            suggestions.push('3. 尝试使用备用API密钥');
            break;
          case 'BMap功能测试':
            suggestions.push('1. 等待API完全加载后再使用');
            suggestions.push('2. 检查API版本兼容性');
            break;
          case '地图创建测试':
            suggestions.push('1. 确保容器元素存在且有尺寸');
            suggestions.push('2. 检查容器是否被隐藏');
            break;
        }
      }
    });
    
    return suggestions;
  }
}

// 导出单例实例
export const baiduMapTester = new BaiduMapTester();
