/**
 * 测试自动保存功能的工具函数
 * 用于验证表格配置的持久化存储
 */

// 模拟测试数据
const TEST_COMPANY_CODE = "600519.SH";
const TEST_ROW_IDS = ["revenue", "net_profit", "total_assets"];

/**
 * 测试配置保存和加载功能
 */
export function testAutoSave() {
  console.log("🧪 开始测试自动保存功能...");
  
  // 清理之前的测试数据
  const storageKey = `table_row_config_${TEST_COMPANY_CODE}`;
  localStorage.removeItem(storageKey);
  
  // 模拟配置数据
  const testConfig = {
    revenue: {
      rowId: "revenue",
      isVisible: true,
      displayOrder: 0
    },
    net_profit: {
      rowId: "net_profit", 
      isVisible: false,
      displayOrder: 1
    },
    total_assets: {
      rowId: "total_assets",
      isVisible: true,
      displayOrder: 2
    },
    separator_123: {
      rowId: "separator_123",
      isVisible: true,
      displayOrder: 3,
      isCustomRow: true,
      customRowType: "separator"
    }
  };
  
  const testCustomRows = {
    separator_123: {
      displayText: "测试分隔线",
      customRowType: "separator" as const
    }
  };
  
  // 保存测试配置
  const configWithVersion = {
    ...testConfig,
    _customRows: testCustomRows,
    _version: '1.0',
    _timestamp: Date.now()
  };
  
  localStorage.setItem(storageKey, JSON.stringify(configWithVersion));
  console.log("✅ 配置已保存到 localStorage");
  
  // 验证保存的数据
  const saved = localStorage.getItem(storageKey);
  if (saved) {
    const parsed = JSON.parse(saved);
    console.log("📄 保存的配置:", parsed);
    
    // 检查关键字段
    const checks = [
      { name: "版本信息", condition: parsed._version === '1.0' },
      { name: "时间戳", condition: typeof parsed._timestamp === 'number' },
      { name: "自定义行数据", condition: parsed._customRows && parsed._customRows.separator_123 },
      { name: "行配置", condition: parsed.revenue && parsed.net_profit && parsed.total_assets },
      { name: "分隔线配置", condition: parsed.separator_123 && parsed.separator_123.isCustomRow }
    ];
    
    checks.forEach(check => {
      console.log(check.condition ? "✅" : "❌", check.name);
    });
    
    if (checks.every(check => check.condition)) {
      console.log("🎉 自动保存功能测试通过！");
      return true;
    } else {
      console.log("❌ 自动保存功能测试失败！");
      return false;
    }
  } else {
    console.log("❌ 未找到保存的配置数据！");
    return false;
  }
}

/**
 * 测试配置恢复功能
 */
export function testAutoRestore() {
  console.log("🔄 测试配置恢复功能...");
  
  const storageKey = `table_row_config_${TEST_COMPANY_CODE}`;
  const saved = localStorage.getItem(storageKey);
  
  if (!saved) {
    console.log("❌ 没有找到保存的配置，请先运行 testAutoSave()");
    return false;
  }
  
  try {
    const parsed = JSON.parse(saved);
    
    // 验证恢复的数据结构
    const hasConfig = parsed.revenue && parsed.net_profit && parsed.total_assets;
    const hasCustomRows = parsed._customRows && parsed._customRows.separator_123;
    const hasVersion = parsed._version === '1.0';
    
    if (hasConfig && hasCustomRows && hasVersion) {
      console.log("✅ 配置恢复成功！");
      console.log("📊 恢复的行配置:", {
        revenue: parsed.revenue,
        net_profit: parsed.net_profit,
        total_assets: parsed.total_assets,
        separator_123: parsed.separator_123
      });
      console.log("🏷️ 恢复的自定义行:", parsed._customRows);
      return true;
    } else {
      console.log("❌ 配置恢复失败，数据不完整！");
      return false;
    }
  } catch (error) {
    console.log("❌ 配置恢复失败，JSON 解析错误:", error);
    return false;
  }
}

/**
 * 清理测试数据
 */
export function cleanupTestData() {
  const storageKey = `table_row_config_${TEST_COMPANY_CODE}`;
  localStorage.removeItem(storageKey);
  console.log("🧹 测试数据已清理");
}

/**
 * 运行完整的自动保存测试套件
 */
export function runAutoSaveTests() {
  console.log("🚀 开始运行自动保存测试套件...");
  console.log("=" .repeat(50));
  
  const saveTest = testAutoSave();
  const restoreTest = testAutoRestore();
  
  console.log("=" .repeat(50));
  console.log("📋 测试结果汇总:");
  console.log("保存功能:", saveTest ? "✅ 通过" : "❌ 失败");
  console.log("恢复功能:", restoreTest ? "✅ 通过" : "❌ 失败");
  
  const allPassed = saveTest && restoreTest;
  console.log("总体结果:", allPassed ? "🎉 全部通过" : "❌ 存在失败");
  
  // 清理测试数据
  cleanupTestData();
  
  return allPassed;
}

// 在开发环境下自动运行测试
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
  // 延迟执行，确保页面加载完成
  setTimeout(() => {
    console.log("🔧 开发环境检测到，可以在控制台运行以下命令测试自动保存功能:");
    console.log("import { runAutoSaveTests } from './src/utils/test-auto-save'; runAutoSaveTests();");
  }, 1000);
}