import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useFlowStore = defineStore('flow', () => {
  // 状态
  const nodes = ref([]);
  const edges = ref([]);
  const hasUnsavedChanges = ref(false);
  const selectedNodeId = ref(null);
  const selectedEdgeId = ref(null);
  
  // 历史记录管理
  const history = ref([]);
  const currentHistoryIndex = ref(-1);
  const maxHistorySize = ref(50);
  
  // Jingrow 上下文
  const frm = ref(null);
  const page = ref(null);
  const pagetype = ref(null);
  
  // 计算属性
  const selectedNode = computed(() => {
    return nodes.value.find(node => node.id === selectedNodeId.value);
  });
  
  const selectedEdge = computed(() => {
    return edges.value.find(edge => edge.id === selectedEdgeId.value);
  });
  
  const nodeCount = computed(() => nodes.value.length);
  const edgeCount = computed(() => edges.value.length);
  
  // 历史记录相关计算属性
  const canUndo = computed(() => currentHistoryIndex.value > 0);
  const canRedo = computed(() => currentHistoryIndex.value < history.value.length - 1);
  
  // 节点操作
  const addNode = (node) => {
    saveToHistory();
    nodes.value.push(node);
    markDirty();
  };
  
  const removeNode = (nodeId) => {
    saveToHistory();
    // 移除节点
    nodes.value = nodes.value.filter(node => node.id !== nodeId);
    
    // 移除相关的边
    edges.value = edges.value.filter(edge => 
      edge.source !== nodeId && edge.target !== nodeId
    );
    
    // 取消选择
    if (selectedNodeId.value === nodeId) {
      selectedNodeId.value = null;
    }
    
    markDirty();
  };
  
  const updateNode = (nodeId, updates) => {
    const nodeIndex = nodes.value.findIndex(node => node.id === nodeId);
    if (nodeIndex !== -1) {
      nodes.value[nodeIndex] = { ...nodes.value[nodeIndex], ...updates };
      markDirty();
    }
  };
  
  const updateNodeData = (nodeId, newData) => {
    const nodeIndex = nodes.value.findIndex(node => node.id === nodeId);
    if (nodeIndex !== -1) {
      const updatedNode = {
        ...nodes.value[nodeIndex],
        data: {
          ...nodes.value[nodeIndex].data,
          ...(newData.label !== undefined ? { label: newData.label } : {}),
          ...(newData.inputs !== undefined ? { inputs: { ...nodes.value[nodeIndex].data.inputs, ...newData.inputs } } : {}),
          config: { ...nodes.value[nodeIndex].data.config, ...(newData.config || {}) }
        }
      };
      const newNodes = [...nodes.value];
      newNodes.splice(nodeIndex, 1, updatedNode);
      nodes.value = newNodes;
      markDirty();
    }
  };
  
  const updateNodePosition = (nodeId, position) => {
    const nodeIndex = nodes.value.findIndex(node => node.id === nodeId);
    if (nodeIndex !== -1) {
      nodes.value[nodeIndex].position = position;
      markDirty();
    }
  };

  // 查找方法
  const findNode = (nodeId) => {
    return nodes.value.find(node => node.id === nodeId);
  };

  const findEdge = (edgeId) => {
    return edges.value.find(edge => edge.id === edgeId);
  };
  
  // 检查连接是否已存在
  const hasConnection = (source, target, sourceHandle = 'output', targetHandle = 'input') => {
    return edges.value.some(edge => 
      edge.source === source && 
      edge.target === target &&
      edge.sourceHandle === sourceHandle &&
      edge.targetHandle === targetHandle
    );
  };
  
  // 边操作
  const addEdge = (edge) => {
    saveToHistory();
    edges.value.push(edge);
    markDirty();
  };
  
  const removeEdge = (edgeId) => {
    saveToHistory();
    edges.value = edges.value.filter(edge => edge.id !== edgeId);
    
    // 取消选择
    if (selectedEdgeId.value === edgeId) {
      selectedEdgeId.value = null;
    }
    
    markDirty();
  };
  
  const updateEdge = (edgeId, updates) => {
    const edgeIndex = edges.value.findIndex(edge => edge.id === edgeId);
    if (edgeIndex !== -1) {
      edges.value[edgeIndex] = { ...edges.value[edgeIndex], ...updates };
      markDirty();
    }
  };
  
  // 选择操作
  const selectNode = (nodeId) => {
    selectedNodeId.value = nodeId;
    selectedEdgeId.value = null;
  };
  
  const selectEdge = (edgeId) => {
    selectedEdgeId.value = edgeId;
    selectedNodeId.value = null;
  };
  
  const clearSelection = () => {
    selectedNodeId.value = null;
    selectedEdgeId.value = null;
  };
  
  // 流程数据操作
  const loadFlowData = (flowData) => {
    
    if (flowData) {
      nodes.value = flowData.nodes || [];
      edges.value = flowData.edges || [];
      hasUnsavedChanges.value = false;
    } else {
      nodes.value = [];
      edges.value = [];
      hasUnsavedChanges.value = false;
    }
    
    // 初始化历史记录
    clearHistory();
    saveToHistory();
  };
  
  const getFlowData = () => {
    return {
      nodes: nodes.value,
      edges: edges.value,
      metadata: {
        nodeCount: nodeCount.value,
        edgeCount: edgeCount.value,
        createdAt: new Date().toISOString(),
        version: '1.0.0'
      }
    };
  };
  
  const resetFlow = () => {
    // 保存当前状态到历史记录
    saveToHistory()
    // 重置数据
    nodes.value = []
    edges.value = []
    selectedNodeId.value = null
    selectedEdgeId.value = null
    hasUnsavedChanges.value = false
    // 保存重置后的状态到历史记录
    saveToHistory()
  }
  
  // 状态管理
  const markDirty = () => {
    hasUnsavedChanges.value = true;
  };
  
  const markClean = () => {
    hasUnsavedChanges.value = false;
  };
  
  // 历史记录管理
  const saveToHistory = () => {
    const currentState = {
      nodes: JSON.parse(JSON.stringify(nodes.value)),
      edges: JSON.parse(JSON.stringify(edges.value)),
      timestamp: Date.now()
    };
    
    // 如果当前不在历史记录的末尾，删除当前位置之后的所有记录
    if (currentHistoryIndex.value < history.value.length - 1) {
      history.value = history.value.slice(0, currentHistoryIndex.value + 1);
    }
    
    // 添加新的历史记录
    history.value.push(currentState);
    currentHistoryIndex.value = history.value.length - 1;
    
    // 限制历史记录大小
    if (history.value.length > maxHistorySize.value) {
      history.value.shift();
      currentHistoryIndex.value--;
    }
  };
  
  const undo = () => {
    if (canUndo.value) {
      currentHistoryIndex.value--;
      const previousState = history.value[currentHistoryIndex.value];
      nodes.value = JSON.parse(JSON.stringify(previousState.nodes));
      edges.value = JSON.parse(JSON.stringify(previousState.edges));
      markDirty();
    }
  };
  
  const redo = () => {
    if (canRedo.value) {
      currentHistoryIndex.value++;
      const nextState = history.value[currentHistoryIndex.value];
      nodes.value = JSON.parse(JSON.stringify(nextState.nodes));
      edges.value = JSON.parse(JSON.stringify(nextState.edges));
      markDirty();
    }
  };
  
  const clearHistory = () => {
    history.value = [];
    currentHistoryIndex.value = -1;
  };
  
  // 本地存储
  const saveToStorage = () => {
    const flowData = getFlowData();
    localStorage.setItem('ai-agent-flow-data', JSON.stringify(flowData));
  };
  
  const loadFromStorage = () => {
    try {
      const savedData = localStorage.getItem('ai-agent-flow-data');
      if (savedData) {
        const flowData = JSON.parse(savedData);
        loadFlowData(flowData);
      }
    } catch (error) {
      // console.error('Failed to load flow data from storage:', error);
    }
  };
  
  // 数据验证
  const validateFlow = () => {
    const errors = [];
    
    // 检查孤立节点
    const connectedNodes = new Set();
    edges.value.forEach(edge => {
      connectedNodes.add(edge.source);
      connectedNodes.add(edge.target);
    });
    
    const isolatedNodes = nodes.value.filter(node => 
      !connectedNodes.has(node.id) && nodes.value.length > 1
    );
    
    if (isolatedNodes.length > 0) {
      errors.push(`Found ${isolatedNodes.length} isolated node(s)`);
    }
    
    return {
      isValid: errors.length === 0,
      errors
    };
  };
  
  return {
    // 状态
    nodes,
    edges,
    hasUnsavedChanges,
    selectedNodeId,
    selectedEdgeId,
    frm,
    page,
    pagetype,
    
    // 计算属性
    selectedNode,
    selectedEdge,
    nodeCount,
    edgeCount,
    canUndo,
    canRedo,
    
    // 节点操作
    addNode,
    removeNode,
    updateNode,
    updateNodeData,
    updateNodePosition,
    findNode,
    findEdge,
    hasConnection,
    
    // 边操作
    addEdge,
    removeEdge,
    updateEdge,
    
    // 选择操作
    selectNode,
    selectEdge,
    clearSelection,
    
    // 流程数据操作
    loadFlowData,
    getFlowData,
    resetFlow,
    
    // 状态管理
    markDirty,
    markClean,
    saveToHistory,
    undo,
    redo,
    clearHistory,
    
    // 本地存储
    saveToStorage,
    loadFromStorage,
    
    // 数据验证
    validateFlow
  };
}); 