/**
 * 工作流设计器 Store
 * 管理工作流状态、节点类型、表单数据等
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type {
  WorkflowDefinition,
  WorkflowNode,
  WorkflowEdge,
  NodeTypeMetadata,
  VueFlowNode,
  VueFlowEdge,
} from '#/types/workflow'
import { MOCK_NODE_TYPES, getNodeTypeMetadata } from '../mock/nodeTypes'
import { EMPTY_WORKFLOW } from '../mock/workflows'

export const useWorkflowStore = defineStore('workflowDesigner', () => {
  // ============== 状态 ==============
  
  /** 当前工作流定义 */
  const workflow = ref<WorkflowDefinition>(JSON.parse(JSON.stringify(EMPTY_WORKFLOW)))
  
  /** 节点类型元数据列表 */
  const nodeTypes = ref<NodeTypeMetadata[]>(MOCK_NODE_TYPES)
  
  /** Vue Flow 节点列表（包含渲染状态） */
  const vueFlowNodes = ref<VueFlowNode[]>([])
  
  /** Vue Flow 边列表 */
  const vueFlowEdges = ref<VueFlowEdge[]>([])
  
  /** 当前选中的节点 ID */
  const selectedNodeId = ref<string | null>(null)
  
  /** 当前选中的边 ID */
  const selectedEdgeId = ref<string | null>(null)
  
  /** 历史记录（撤销/重做） */
  const history = ref<Array<{ nodes: WorkflowNode[]; edges: WorkflowEdge[] }>>([])
  
  /** 历史记录索引 */
  const historyIndex = ref(-1)
  
  /** 节点 ID 计数器 */
  const nodeIdCounter = ref(1)

  // ============== 计算属性 ==============
  
  /** 当前选中的节点 */
  const selectedNode = computed(() => {
    if (!selectedNodeId.value) return null
    return vueFlowNodes.value.find((n) => n.id === selectedNodeId.value)
  })
  
  /** 当前选中的节点类型元数据 */
  const selectedNodeMetadata = computed(() => {
    if (!selectedNode.value) return null
    return getNodeTypeMetadata(selectedNode.value.type)
  })
  
  /** 按分类分组的节点类型 */
  const nodeTypesByCategory = computed(() => {
    const grouped: Record<string, NodeTypeMetadata[]> = {}
    nodeTypes.value.forEach((nodeType) => {
      if (!grouped[nodeType.category]) {
        grouped[nodeType.category] = []
      }
      grouped[nodeType.category]!.push(nodeType)
    })
    return grouped
  })
  
  /** 是否可以撤销 */
  const canUndo = computed(() => historyIndex.value > 0)
  
  /** 是否可以重做 */
  const canRedo = computed(() => historyIndex.value < history.value.length - 1)

  // ============== 方法 ==============
  
  /**
   * 生成新的节点 ID
   */
  function generateNodeId(): string {
    return `n${nodeIdCounter.value++}`
  }
  
  /**
   * 加载工作流
   */
  function loadWorkflow(definition: WorkflowDefinition) {
    workflow.value = JSON.parse(JSON.stringify(definition))
    
    // 转换为 Vue Flow 节点
    vueFlowNodes.value = definition.nodes.map((node) => {
      const metadata = getNodeTypeMetadata(node.type)
      return {
        id: node.id,
        type: node.type,
        position: node.position,
        data: {
          name: node.name,
          type: node.type,
          config: node.config || {},
          metadata: metadata || undefined,
        },
      }
    })
    
    // 转换为 Vue Flow 边
    vueFlowEdges.value = definition.edges.map((edge, index) => ({
      id: `e${edge.source}-${edge.target}-${index}`,
      source: edge.source,
      target: edge.target,
      data: {
        condition: edge.condition,
      },
      type: edge.condition ? 'conditional' : 'default',
      animated: false,
    }))
    
    // 重置历史记录
    saveToHistory()
  }
  
  /**
   * 添加节点
   */
  function addNode(nodeTypeId: string, position: { x: number; y: number }) {
    const metadata = getNodeTypeMetadata(nodeTypeId)
    if (!metadata) {
      console.error(`未找到节点类型: ${nodeTypeId}`)
      return undefined
    }
    
    const nodeId = generateNodeId()
    const workflowNode: WorkflowNode = {
      id: nodeId,
      type: nodeTypeId,
      name: metadata.displayName,
      position,
      config: {},
    }
    
    const vueFlowNode: VueFlowNode = {
      id: nodeId,
      type: nodeTypeId,
      position,
      data: {
        name: metadata.displayName,
        type: nodeTypeId,
        config: {},
        metadata: metadata,
      },
    }
    
    workflow.value.nodes.push(workflowNode)
    vueFlowNodes.value.push(vueFlowNode)
    
    saveToHistory()
    return nodeId
  }
  
  /**
   * 删除节点
   */
  function deleteNode(nodeId: string) {
    // 删除节点
    workflow.value.nodes = workflow.value.nodes.filter((n) => n.id !== nodeId)
    vueFlowNodes.value = vueFlowNodes.value.filter((n) => n.id !== nodeId)
    
    // 删除相关的边
    workflow.value.edges = workflow.value.edges.filter(
      (e) => e.source !== nodeId && e.target !== nodeId,
    )
    vueFlowEdges.value = vueFlowEdges.value.filter(
      (e) => e.source !== nodeId && e.target !== nodeId,
    )
    
    // 清除选中状态
    if (selectedNodeId.value === nodeId) {
      selectedNodeId.value = null
    }
    
    saveToHistory()
  }
  
  /**
   * 更新节点配置
   */
  function updateNodeConfig(nodeId: string, config: Record<string, any>) {
    const workflowNode = workflow.value.nodes.find((n) => n.id === nodeId)
    const vueFlowNode = vueFlowNodes.value.find((n) => n.id === nodeId)
    
    if (workflowNode && vueFlowNode) {
      workflowNode.config = config
      vueFlowNode.data.config = config
      saveToHistory()
    }
  }
  
  /**
   * 更新节点名称
   */
  function updateNodeName(nodeId: string, name: string) {
    const workflowNode = workflow.value.nodes.find((n) => n.id === nodeId)
    const vueFlowNode = vueFlowNodes.value.find((n) => n.id === nodeId)
    
    if (workflowNode && vueFlowNode) {
      workflowNode.name = name
      vueFlowNode.data.name = name
      saveToHistory()
    }
  }
  
  /**
   * 更新节点位置
   */
  function updateNodePosition(nodeId: string, position: { x: number; y: number }) {
    const workflowNode = workflow.value.nodes.find((n) => n.id === nodeId)
    const vueFlowNode = vueFlowNodes.value.find((n) => n.id === nodeId)
    
    if (workflowNode && vueFlowNode) {
      workflowNode.position = position
      vueFlowNode.position = position
    }
  }
  
  /**
   * 添加边
   */
  function addEdge(source: string, target: string, condition?: string) {
    const edge: WorkflowEdge = {
      source,
      target,
      condition,
    }
    
    const vueEdge: VueFlowEdge = {
      id: `e${source}-${target}`,
      source,
      target,
      data: { condition },
      type: condition ? 'conditional' : 'default',
      animated: false,
    }
    
    workflow.value.edges.push(edge)
    vueFlowEdges.value.push(vueEdge)
    
    saveToHistory()
  }
  
  /**
   * 删除边
   */
  function deleteEdge(edgeId: string) {
    const vueEdge = vueFlowEdges.value.find((e) => e.id === edgeId)
    if (!vueEdge) return
    
    workflow.value.edges = workflow.value.edges.filter(
      (e) => !(e.source === vueEdge.source && e.target === vueEdge.target),
    )
    vueFlowEdges.value = vueFlowEdges.value.filter((e) => e.id !== edgeId)
    
    if (selectedEdgeId.value === edgeId) {
      selectedEdgeId.value = null
    }
    
    saveToHistory()
  }
  
  /**
   * 更新边的条件
   */
  function updateEdgeCondition(edgeId: string, condition?: string) {
    const vueEdge = vueFlowEdges.value.find((e) => e.id === edgeId)
    if (!vueEdge) return
    
    const workflowEdge = workflow.value.edges.find(
      (e) => e.source === vueEdge.source && e.target === vueEdge.target,
    )
    
    if (workflowEdge) {
      workflowEdge.condition = condition
      if (!vueEdge.data) {
        vueEdge.data = {}
      }
      vueEdge.data.condition = condition
      vueEdge.type = condition ? 'conditional' : 'default'
      saveToHistory()
    }
  }
  
  /**
   * 选中节点
   */
  function selectNode(nodeId: string | null) {
    selectedNodeId.value = nodeId
    selectedEdgeId.value = null
  }
  
  /**
   * 选中边
   */
  function selectEdge(edgeId: string | null) {
    selectedEdgeId.value = edgeId
    selectedNodeId.value = null
  }
  
  /**
   * 保存到历史记录
   */
  function saveToHistory() {
    const snapshot = {
      nodes: JSON.parse(JSON.stringify(workflow.value.nodes)),
      edges: JSON.parse(JSON.stringify(workflow.value.edges)),
    }
    
    // 删除当前索引之后的历史
    history.value = history.value.slice(0, historyIndex.value + 1)
    
    // 添加新快照
    history.value.push(snapshot)
    historyIndex.value++
    
    // 限制历史记录数量（最多保留 50 条）
    if (history.value.length > 50) {
      history.value.shift()
      historyIndex.value--
    }
  }
  
  /**
   * 撤销
   */
  function undo() {
    if (!canUndo.value) return
    
    historyIndex.value--
    restoreFromHistory()
  }
  
  /**
   * 重做
   */
  function redo() {
    if (!canRedo.value) return
    
    historyIndex.value++
    restoreFromHistory()
  }
  
  /**
   * 从历史记录恢复
   */
  function restoreFromHistory() {
    const snapshot = history.value[historyIndex.value]
    if (!snapshot) return
    
    workflow.value.nodes = JSON.parse(JSON.stringify(snapshot.nodes))
    workflow.value.edges = JSON.parse(JSON.stringify(snapshot.edges))
    
    // 重新构建 Vue Flow 节点和边
    vueFlowNodes.value = workflow.value.nodes.map((node) => {
      const metadata = getNodeTypeMetadata(node.type)
      return {
        id: node.id,
        type: node.type,
        position: node.position,
        data: {
          name: node.name,
          type: node.type,
          config: node.config || {},
          metadata: metadata || undefined,
        },
      }
    })
    
    vueFlowEdges.value = workflow.value.edges.map((edge, index) => ({
      id: `e${edge.source}-${edge.target}-${index}`,
      source: edge.source,
      target: edge.target,
      data: {
        condition: edge.condition,
      },
      type: edge.condition ? 'conditional' : 'default',
      animated: false,
    }))
  }
  
  /**
   * 清空工作流
   */
  function clearWorkflow() {
    workflow.value = JSON.parse(JSON.stringify(EMPTY_WORKFLOW))
    vueFlowNodes.value = []
    vueFlowEdges.value = []
    selectedNodeId.value = null
    selectedEdgeId.value = null
    history.value = []
    historyIndex.value = -1
    nodeIdCounter.value = 1
    saveToHistory()
  }
  
  /**
   * 获取工作流定义（用于保存）
   */
  function getWorkflowDefinition(): WorkflowDefinition {
    return {
      ...workflow.value,
      nodes: workflow.value.nodes.map((node) => ({
        id: node.id,
        type: node.type,
        name: node.name,
        position: node.position,
        config: node.config,
      })),
      edges: workflow.value.edges.map((edge) => ({
        source: edge.source,
        target: edge.target,
        condition: edge.condition,
      })),
    }
  }

  return {
    // 状态
    workflow,
    nodeTypes,
    vueFlowNodes,
    vueFlowEdges,
    selectedNodeId,
    selectedEdgeId,
    
    // 计算属性
    selectedNode,
    selectedNodeMetadata,
    nodeTypesByCategory,
    canUndo,
    canRedo,
    
    // 方法
    loadWorkflow,
    addNode,
    deleteNode,
    updateNodeConfig,
    updateNodeName,
    updateNodePosition,
    addEdge,
    deleteEdge,
    updateEdgeCondition,
    selectNode,
    selectEdge,
    undo,
    redo,
    clearWorkflow,
    getWorkflowDefinition,
  }
})

