/**
 * 客户端背景图片配置API连通性测试
 * 
 * 使用方法：
 * 1. 确保项目已启动并可以访问API端点
 * 2. 在浏览器开发者工具的控制台中执行这个测试
 * 3. 或者在项目中导入并调用测试函数
 */

import request from '/@/utils/request';

export class ApiConnectivityTest {
  private baseUrl = '/api/system/login-background/config/';
  
  /**
   * 测试API基础连通性
   */
  async testApiConnectivity() {
    console.log('🔌 开始测试API连通性...');
    
    try {
      // 1. 测试GET接口
      console.log('📡 测试GET接口...');
      const getResponse = await request({
        url: this.baseUrl,
        method: 'get',
        timeout: 5000, // 5秒超时
      });
      
      console.log('✅ GET接口连通正常:', getResponse);
      
      // 2. 测试POST接口（用测试数据）
      console.log('📡 测试POST接口...');
      const testData = {
        backgroundImage: 'test://connectivity-test.jpg',
        description: 'API连通性测试数据',
        enabled: false, // 设为false避免影响实际配置
      };
      
      const postResponse = await request({
        url: this.baseUrl,
        method: 'post',
        data: testData,
        timeout: 5000,
      });
      
      console.log('✅ POST接口连通正常:', postResponse);
      
      return {
        success: true,
        message: 'API连通性测试通过',
        getResponse,
        postResponse,
      };
      
    } catch (error: any) {
      console.error('❌ API连通性测试失败:', error);
      
      // 分析错误类型
      let errorType = '未知错误';
      let errorMessage = error.message || '未知错误';
      
      if (error.code === 'ECONNREFUSED' || error.message?.includes('Network Error')) {
        errorType = '网络连接错误';\n        errorMessage = '无法连接到服务器，请检查服务器是否启动';\n      } else if (error.code === 404 || error.response?.status === 404) {\n        errorType = '接口不存在';\n        errorMessage = '后端接口尚未实现或路径错误';\n      } else if (error.code === 401 || error.response?.status === 401) {\n        errorType = '认证失败';\n        errorMessage = '请检查登录状态或token是否有效';\n      } else if (error.code === 403 || error.response?.status === 403) {\n        errorType = '权限不足';\n        errorMessage = '当前用户没有访问此接口的权限';\n      } else if (error.code === 500 || error.response?.status === 500) {\n        errorType = '服务器内部错误';\n        errorMessage = '后端服务出现异常，请检查服务器日志';\n      } else if (error.message?.includes('timeout')) {\n        errorType = '请求超时';\n        errorMessage = '服务器响应超时，请检查网络或服务器状态';\n      }\n      \n      return {\n        success: false,\n        errorType,\n        errorMessage,\n        originalError: error,\n      };\n    }\n  }\n  \n  /**\n   * 测试依赖服务\n   */\n  async testDependencies() {\n    console.log('🔍 检查依赖服务...');\n    \n    const results = {\n      fileUpload: false,\n      authentication: false,\n      database: false,\n    };\n    \n    try {\n      // 测试文件上传服务\n      console.log('📁 测试文件上传服务...');\n      const fileResponse = await request({\n        url: '/api/system/file/',\n        method: 'get',\n        params: { limit: 1 },\n        timeout: 3000,\n      });\n      results.fileUpload = true;\n      console.log('✅ 文件上传服务正常');\n    } catch (error) {\n      console.log('❌ 文件上传服务异常:', error);\n    }\n    \n    try {\n      // 测试认证服务\n      console.log('🔐 测试认证服务...');\n      const authResponse = await request({\n        url: '/api/system/user/info/',\n        method: 'get',\n        timeout: 3000,\n      });\n      results.authentication = true;\n      console.log('✅ 认证服务正常');\n    } catch (error) {\n      console.log('❌ 认证服务异常:', error);\n    }\n    \n    return results;\n  }\n  \n  /**\n   * 生成测试报告\n   */\n  async generateTestReport() {\n    console.log('📊 生成API连通性测试报告...');\n    \n    const testResults = {\n      timestamp: new Date().toLocaleString(),\n      connectivity: null as any,\n      dependencies: null as any,\n      recommendations: [] as string[],\n    };\n    \n    // 执行连通性测试\n    testResults.connectivity = await this.testApiConnectivity();\n    \n    // 执行依赖测试\n    testResults.dependencies = await this.testDependencies();\n    \n    // 生成建议\n    if (!testResults.connectivity.success) {\n      const errorType = testResults.connectivity.errorType;\n      \n      switch (errorType) {\n        case '网络连接错误':\n          testResults.recommendations.push('检查后端服务是否启动');\n          testResults.recommendations.push('检查API基础URL配置是否正确');\n          break;\n        case '接口不存在':\n          testResults.recommendations.push('实现后端 /api/system/login-background/config/ 接口');\n          testResults.recommendations.push('检查路由配置是否正确');\n          break;\n        case '认证失败':\n          testResults.recommendations.push('检查用户登录状态');\n          testResults.recommendations.push('验证token是否有效');\n          break;\n        case '权限不足':\n          testResults.recommendations.push('为当前用户分配相应权限');\n          testResults.recommendations.push('检查接口权限配置');\n          break;\n        case '服务器内部错误':\n          testResults.recommendations.push('检查后端服务器日志');\n          testResults.recommendations.push('验证数据库连接');\n          break;\n        case '请求超时':\n          testResults.recommendations.push('检查网络连接');\n          testResults.recommendations.push('优化服务器响应性能');\n          break;\n      }\n    }\n    \n    if (!testResults.dependencies.fileUpload) {\n      testResults.recommendations.push('检查文件上传服务是否正常');\n    }\n    \n    if (!testResults.dependencies.authentication) {\n      testResults.recommendations.push('检查用户认证服务是否正常');\n    }\n    \n    // 输出报告\n    console.log('\\n📋 === API连通性测试报告 ===');\n    console.log('🕐 测试时间:', testResults.timestamp);\n    console.log('\\n🔌 连通性测试:');\n    if (testResults.connectivity.success) {\n      console.log('  ✅ 状态: 通过');\n    } else {\n      console.log('  ❌ 状态: 失败');\n      console.log('  🔍 错误类型:', testResults.connectivity.errorType);\n      console.log('  💬 错误信息:', testResults.connectivity.errorMessage);\n    }\n    \n    console.log('\\n🔧 依赖服务:');\n    console.log('  📁 文件上传服务:', testResults.dependencies.fileUpload ? '✅ 正常' : '❌ 异常');\n    console.log('  🔐 认证服务:', testResults.dependencies.authentication ? '✅ 正常' : '❌ 异常');\n    \n    if (testResults.recommendations.length > 0) {\n      console.log('\\n💡 建议:');\n      testResults.recommendations.forEach((rec, index) => {\n        console.log(`  ${index + 1}. ${rec}`);\n      });\n    }\n    \n    console.log('\\n===========================================\\n');\n    \n    return testResults;\n  }\n}\n\n// 导出测试实例\nexport const apiConnectivityTest = new ApiConnectivityTest();\n\n// 快速测试函数\nexport const quickApiTest = () => apiConnectivityTest.testApiConnectivity();\nexport const fullApiTest = () => apiConnectivityTest.generateTestReport();\n\n// 使用示例（在浏览器控制台中）:\n// \n// import { quickApiTest, fullApiTest } from '@/api/system/loginBackgroundConnectivityTest';\n// \n// // 快速测试\n// quickApiTest();\n//\n// // 完整测试报告\n// fullApiTest();