/**
 * 路由性能优化
 */
import type { Router, RouteLocationNormalized } from 'vue-router';
import { routePerformanceMonitor } from '@/utils/performance';
import { componentPreloader } from '@/utils/lazy-load';

// 路由预加载配置
const PRELOAD_ROUTES = [
  '/dashboard',
  '/user/profile',
  '/system/user',
  '/system/role'
];

// 路由性能优化类
export class RoutePerformanceOptimizer {
  private router: Router;
  private preloadTimer: number | null = null;
  
  constructor(router: Router) {
    this.router = router;
    this.setupOptimizations();
  }
  
  private setupOptimizations() {
    // 路由性能监控
    this.setupPerformanceMonitoring();
    
    // 路由预加载
    this.setupRoutePreloading();
    
    // 路由缓存优化
    this.setupRouteCaching();
  }
  
  // 设置性能监控
  private setupPerformanceMonitoring() {
    this.router.beforeEach((to, from) => {
      routePerformanceMonitor.startRouteTimer();
      return true;
    });
    
    this.router.afterEach((to, from) => {
      routePerformanceMonitor.endRouteTimer(to.path);
    });
  }
  
  // 设置路由预加载
  private setupRoutePreloading() {
    this.router.afterEach((to) => {
      // 延迟预加载相关路由
      if (this.preloadTimer) {
        clearTimeout(this.preloadTimer);
      }
      
      this.preloadTimer = window.setTimeout(() => {
        this.preloadRelatedRoutes(to);
      }, 2000); // 2秒后开始预加载
    });
  }
  
  // 预加载相关路由
  private preloadRelatedRoutes(currentRoute: RouteLocationNormalized) {
    const routesToPreload = this.getRelatedRoutes(currentRoute.path);
    
    routesToPreload.forEach(routePath => {
      const route = this.router.resolve(routePath);
      if (route.matched.length > 0) {
        const component = route.matched[route.matched.length - 1].components?.default;
        if (component && typeof component === 'function') {
          componentPreloader.preload(routePath, component as () => Promise<any>);
        }
      }
    });
  }
  
  // 获取相关路由
  private getRelatedRoutes(currentPath: string): string[] {
    const related: string[] = [];
    
    // 根据当前路径推断可能访问的路由
    if (currentPath === '/') {
      related.push(...PRELOAD_ROUTES);
    } else if (currentPath.startsWith('/system')) {
      related.push('/system/user', '/system/role', '/system/menu');
    } else if (currentPath.startsWith('/cms')) {
      related.push('/cms/dashboard', '/cms/setting');
    } else if (currentPath.startsWith('/bszx')) {
      related.push('/bszx/dashboard', '/bszx/ranking');
    }
    
    return related.filter(path => path !== currentPath);
  }
  
  // 设置路由缓存
  private setupRouteCaching() {
    // 这里可以实现路由级别的缓存策略
    // 例如缓存路由组件、路由数据等
  }
  
  // 清理资源
  destroy() {
    if (this.preloadTimer) {
      clearTimeout(this.preloadTimer);
    }
  }
}

// 路由懒加载优化
export function optimizedLazyRoute(loader: () => Promise<any>) {
  return async () => {
    // 检查是否已经预加载
    const preloaded = componentPreloader.get(loader.toString());
    if (preloaded) {
      return preloaded;
    }
    
    // 正常加载
    return loader();
  };
}

// 智能路由预取
export class SmartRoutePrefetcher {
  private router: Router;
  private prefetchQueue: Set<string> = new Set();
  private isIdle = true;
  
  constructor(router: Router) {
    this.router = router;
    this.setupIdleDetection();
  }
  
  // 设置空闲检测
  private setupIdleDetection() {
    let idleTimer: number;
    
    const resetIdleTimer = () => {
      this.isIdle = false;
      clearTimeout(idleTimer);
      idleTimer = window.setTimeout(() => {
        this.isIdle = true;
        this.processPrefetchQueue();
      }, 2000);
    };
    
    // 监听用户活动
    ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'].forEach(event => {
      document.addEventListener(event, resetIdleTimer, true);
    });
    
    resetIdleTimer();
  }
  
  // 添加到预取队列
  addToPrefetchQueue(routePath: string) {
    this.prefetchQueue.add(routePath);
    
    if (this.isIdle) {
      this.processPrefetchQueue();
    }
  }
  
  // 处理预取队列
  private async processPrefetchQueue() {
    if (!this.isIdle || this.prefetchQueue.size === 0) {
      return;
    }
    
    const routePath = this.prefetchQueue.values().next().value;
    this.prefetchQueue.delete(routePath);
    
    try {
      const route = this.router.resolve(routePath);
      if (route.matched.length > 0) {
        const component = route.matched[route.matched.length - 1].components?.default;
        if (component && typeof component === 'function') {
          await componentPreloader.preload(routePath, component as () => Promise<any>);
        }
      }
    } catch (error) {
      console.warn(`Failed to prefetch route ${routePath}:`, error);
    }
    
    // 继续处理队列
    if (this.isIdle && this.prefetchQueue.size > 0) {
      setTimeout(() => this.processPrefetchQueue(), 100);
    }
  }
}

// 路由性能分析器
export class RoutePerformanceAnalyzer {
  private router: Router;
  private performanceData: Map<string, number[]> = new Map();
  
  constructor(router: Router) {
    this.router = router;
    this.setupAnalysis();
  }
  
  private setupAnalysis() {
    let startTime: number;
    
    this.router.beforeEach((to) => {
      startTime = performance.now();
      return true;
    });
    
    this.router.afterEach((to) => {
      const duration = performance.now() - startTime;
      this.recordPerformance(to.path, duration);
    });
  }
  
  private recordPerformance(path: string, duration: number) {
    if (!this.performanceData.has(path)) {
      this.performanceData.set(path, []);
    }
    
    const data = this.performanceData.get(path)!;
    data.push(duration);
    
    // 只保留最近10次记录
    if (data.length > 10) {
      data.shift();
    }
  }
  
  // 获取性能报告
  getPerformanceReport() {
    const report: Record<string, any> = {};
    
    this.performanceData.forEach((durations, path) => {
      const avg = durations.reduce((sum, d) => sum + d, 0) / durations.length;
      const min = Math.min(...durations);
      const max = Math.max(...durations);
      
      report[path] = {
        average: Math.round(avg),
        min: Math.round(min),
        max: Math.round(max),
        count: durations.length
      };
    });
    
    return report;
  }
  
  // 获取慢路由
  getSlowRoutes(threshold: number = 1000) {
    const slowRoutes: Array<{ path: string; avgTime: number }> = [];
    
    this.performanceData.forEach((durations, path) => {
      const avg = durations.reduce((sum, d) => sum + d, 0) / durations.length;
      if (avg > threshold) {
        slowRoutes.push({ path, avgTime: Math.round(avg) });
      }
    });
    
    return slowRoutes.sort((a, b) => b.avgTime - a.avgTime);
  }
}

// 路由缓存管理器
export class RouteCacheManager {
  private cache = new Map<string, any>();
  private maxSize: number;
  
  constructor(maxSize: number = 20) {
    this.maxSize = maxSize;
  }
  
  // 缓存路由数据
  set(key: string, data: any) {
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    
    this.cache.set(key, {
      data,
      timestamp: Date.now()
    });
  }
  
  // 获取缓存数据
  get(key: string, maxAge: number = 5 * 60 * 1000) {
    const cached = this.cache.get(key);
    
    if (!cached) {
      return null;
    }
    
    if (Date.now() - cached.timestamp > maxAge) {
      this.cache.delete(key);
      return null;
    }
    
    return cached.data;
  }
  
  // 清除缓存
  clear() {
    this.cache.clear();
  }
  
  // 删除特定缓存
  delete(key: string) {
    return this.cache.delete(key);
  }
}
