/**
 * 拓扑服务层 - 整合本地存储和后端API
 * 支持离线和在线两种模式
 */

import { Node, Edge } from '@vue-flow/core';
import * as TopoAPI from '@/api/ops/netarchTopo';

// 配置：是否使用后端API（可通过环境变量控制）
const USE_BACKEND_API = import.meta.env.VITE_USE_TOPO_API === 'true';

// 本地存储key
const STORAGE_KEY = 'topo-data';

/**
 * 拓扑数据服务类
 */
export class TopoService {
  private currentTopologyId: number | null = null;

  /**
   * 设置当前拓扑ID
   */
  setCurrentTopologyId(id: number) {
    this.currentTopologyId = id;
  }

  /**
   * 获取拓扑数据
   */
  async getTopoData(): Promise<{ nodes: Node[]; edges: Edge[] }> {
    if (USE_BACKEND_API && this.currentTopologyId) {
      // 从后端获取
      const graphData = await TopoAPI.fetchTopologyGraph(this.currentTopologyId);
      return this.graphToReactFlowData(graphData);
    } else {
      // 从本地存储获取
      return this.loadFromStorage();
    }
  }

  /**
   * 保存拓扑数据
   */
  async saveTopoData(nodes: Node[], edges: Edge[]): Promise<void> {
    // 同时保存到本地（作为缓存）
    this.saveToStorage(nodes, edges);
    
    // 后端API通过主组件直接调用，不在此服务层处理
  }

  /**
   * 创建链路
   */
  async createEdge(edge: Edge): Promise<void> {
    if (USE_BACKEND_API && this.currentTopologyId) {
      const params = {
        source: edge.source,
        target: edge.target,
        type: edge.data?.type || 'physical',
        label: edge.data?.label || '',
      };
      await TopoAPI.createLink(this.currentTopologyId, params);
    }
  }

  /**
   * 更新链路
   */
  async updateEdge(edge: Edge): Promise<void> {
    if (USE_BACKEND_API && this.currentTopologyId && edge.id) {
      const linkId = parseInt(edge.id.replace(/\D/g, ''));
      if (!isNaN(linkId)) {
        await TopoAPI.updateLink(this.currentTopologyId, linkId, {
          type: edge.data?.type as 'physical' | 'virtual',
          label: edge.data?.label,
          bandwidth: edge.data?.bandwidth,
          description: edge.data?.description,
        });
      }
    }
  }

  /**
   * 删除链路
   */
  async deleteEdge(edgeId: string): Promise<void> {
    if (USE_BACKEND_API && this.currentTopologyId) {
      await TopoAPI.deleteLink(this.currentTopologyId, edgeId);
    }
  }

  /**
   * 获取拓扑列表
   */
  async getTopologies(params: { page: number; size: number; keyword?: string; group_id?: number }): Promise<{ list: TopoAPI.Topology[] }> {
    if (USE_BACKEND_API) {
      const result = await TopoAPI.fetchTopologies(params);
      return { list: result.data?.list || [] };
    }
    return { list: [] };
  }

  /**
   * 创建拓扑
   */
  async createTopology(params: Partial<TopoAPI.Topology>): Promise<TopoAPI.Topology> {
    if (USE_BACKEND_API) {
      return await TopoAPI.createTopology(params);
    }
    throw new Error('Backend API not enabled');
  }

  /**
   * 触发拓扑发现
   */
  async discoverTopology(id: number): Promise<void> {
    if (USE_BACKEND_API) {
      await TopoAPI.discoverTopology(id);
    }
  }

  // ==================== 数据转换方法 ====================

  /**
   * 将后端图数据转换为Vue Flow数据
   */
  private graphToReactFlowData(graphData: any): { nodes: Node[]; edges: Edge[] } {
    const nodes: Node[] = [];
    const edges: Edge[] = [];

    if (graphData.code === 0) {
      // 处理节点数据
      const nodesFromGraph = graphData.details?.nodes || graphData.details?.data || graphData.data?.nodes || [];
      
      if (Array.isArray(nodesFromGraph)) {
        nodesFromGraph.forEach((node: any) => {
          nodes.push({
            id: node.id,
            type: 'custom',
            position: node.position || { x: Math.random() * 800, y: Math.random() * 600 },
            data: {
              label: node.label,
              type: node.type,
              ip: node.ip,
              status: node.status || 'normal',
              alerts: node.alerts || 0,
              traffic: node.traffic,
              description: node.description,
              parentId: node.parentId,
              level: node.level ?? 0,
              position: node.position,
            },
          });
        });
      }

      // 处理边数据
      const edgesFromGraph = graphData.details?.edges || graphData.data?.edges || [];
      
      edgesFromGraph.forEach((edge: any) => {
        edges.push({
          id: String(edge.id),
          source: edge.source,
          target: edge.target,
          type: edge.type || 'smoothstep',
          label: edge.label || '',
          data: { ...edge },
        });
      });
    }

    return { nodes, edges };
  }

  // ==================== 本地存储方法 ====================

  private loadFromStorage(): { nodes: Node[]; edges: Edge[] } {
    try {
      const data = localStorage.getItem(STORAGE_KEY);
      if (data) {
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('Failed to load topo data from storage:', error);
    }
    return { nodes: [], edges: [] };
  }

  private saveToStorage(nodes: Node[], edges: Edge[]): void {
    try {
      const data = { nodes, edges };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch (error) {
      console.error('Failed to save topo data to storage:', error);
    }
  }

  clearStorage(): void {
    localStorage.removeItem(STORAGE_KEY);
  }
}

// 导出单例
export const topoService = new TopoService();
