<template>
  <div class="workflow-editor">
    <!-- 左侧节点面板 -->
    <aside class="node-panel">
      <div class="panel-header">
        <h3>节点库</h3>
      </div>
      <div class="node-categories">
        <div class="category" v-for="category in categories" :key="category.key">
          <div class="category-title">{{ category.label }}</div>
          <div class="node-list">
            <div
              v-for="nodeType in getNodesByCategory(category.key)"
              :key="nodeType.type"
              class="node-item"
              draggable="true"
              @dragstart="onDragStart($event, nodeType)"
            >
              <div class="node-icon" :style="{ background: nodeType.color }">
                {{ nodeType.icon }}
              </div>
              <span class="node-label">{{ nodeType.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </aside>

    <!-- 画布区域 -->
    <main class="canvas-container">
      <!-- 工具栏 -->
      <div class="canvas-toolbar">
        <el-button-group>
          <el-button size="small" @click="zoomIn">
            <el-icon><ZoomIn /></el-icon>
          </el-button>
          <el-button size="small" @click="zoomOut">
            <el-icon><ZoomOut /></el-icon>
          </el-button>
          <el-button size="small" @click="resetZoom">
            <el-icon><FullScreen /></el-icon>
          </el-button>
        </el-button-group>
        <el-button size="small" type="danger" @click="clearCanvas">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
      </div>

      <!-- 画布 -->
      <div
        ref="canvasRef"
        class="canvas"
        :style="canvasStyle"
        @drop="onDrop"
        @dragover.prevent
        @click="onCanvasClick"
        @mousedown="onCanvasMouseDown"
        @mousemove="onCanvasMouseMove"
        @mouseup="onCanvasMouseUp"
      >
        <!-- 网格背景 -->
        <svg class="grid-background" width="100%" height="100%">
          <defs>
            <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
              <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#e5e7eb" stroke-width="0.5"/>
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#grid)" />
        </svg>

        <!-- 连接线 -->
        <svg class="connections-layer" width="100%" height="100%">
          <g v-for="conn in connections" :key="conn.id">
            <path
              :d="getConnectionPath(conn)"
              fill="none"
              stroke="#94a3b8"
              stroke-width="2"
              class="connection-line"
              @click="onConnectionClick(conn)"
            />
          </g>
          <!-- 临时连接线 -->
          <path
            v-if="tempConnection"
            :d="tempConnectionPath"
            fill="none"
            stroke="#7c3aed"
            stroke-width="2"
            stroke-dasharray="5,5"
          />
        </svg>

        <!-- 节点 -->
        <div
          v-for="node in nodes"
          :key="node.id"
          class="workflow-node"
          :class="{ selected: selectedNodeId === node.id }"
          :style="getNodeStyle(node)"
          @mousedown.stop="onNodeMouseDown($event, node)"
        >
          <div class="node-header" :style="{ background: node.color }">
            <span class="node-icon">{{ node.icon }}</span>
            <span class="node-title">{{ node.label }}</span>
            <el-icon class="delete-btn" @click.stop="deleteNode(node.id)"><Close /></el-icon>
          </div>
          <div class="node-body">
            <!-- 输入端口 -->
            <div
              v-for="input in node.inputs"
              :key="input.id"
              class="port input-port"
              @mousedown.stop="onPortMouseDown($event, node, input, 'input')"
              @mouseup.stop="onPortMouseUp($event, node, input, 'input')"
            >
              <div class="port-dot"></div>
            </div>
            <!-- 输出端口 -->
            <div
              v-for="output in node.outputs"
              :key="output.id"
              class="port output-port"
              @mousedown.stop="onPortMouseDown($event, node, output, 'output')"
            >
              <div class="port-dot"></div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 右侧属性面板 -->
    <aside class="property-panel" v-if="selectedNode">
      <div class="panel-header">
        <h3>节点属性</h3>
        <el-icon class="close-btn" @click="selectNode(null)"><Close /></el-icon>
      </div>
      <div class="property-content">
        <el-form label-position="top" size="small">
          <el-form-item label="节点类型">
            <el-input :value="selectedNode.label" disabled />
          </el-form-item>
          <el-form-item label="节点ID">
            <el-input :value="selectedNode.id" disabled />
          </el-form-item>
          <el-form-item label="位置 X">
            <el-input-number v-model="selectedNode.x" :step="10" />
          </el-form-item>
          <el-form-item label="位置 Y">
            <el-input-number v-model="selectedNode.y" :step="10" />
          </el-form-item>
        </el-form>
      </div>
    </aside>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useWorkflowStore } from '@/stores/workflow'
import { ZoomIn, ZoomOut, FullScreen, Delete, Close } from '@element-plus/icons-vue'

const workflowStore = useWorkflowStore()

// 响应式数据
const canvasRef = ref(null)
const scale = ref(1)
const panOffset = ref({ x: 0, y: 0 })
const isDragging = ref(false)
const dragNode = ref(null)
const dragOffset = ref({ x: 0, y: 0 })
const tempConnection = ref(null)
const isPanning = ref(false)
const panStart = ref({ x: 0, y: 0 })

// 节点分类
const categories = [
  { key: 'control', label: '流程控制' },
  { key: 'ai', label: 'AI 能力' },
  { key: 'logic', label: '逻辑处理' },
  { key: 'integration', label: '集成' },
  { key: 'transform', label: '数据转换' }
]

// 计算属性
const nodes = computed(() => workflowStore.nodes)
const connections = computed(() => workflowStore.connections)
const selectedNodeId = computed(() => workflowStore.selectedNodeId)
const selectedNode = computed(() => workflowStore.getNode(selectedNodeId.value))
const nodeTypes = computed(() => workflowStore.nodeTypes)

const canvasStyle = computed(() => ({
  transform: `scale(${scale.value}) translate(${panOffset.value.x}px, ${panOffset.value.y}px)`
}))

// 根据分类获取节点
const getNodesByCategory = (category) => {
  return nodeTypes.value.filter(n => n.category === category)
}

// 节点样式
const getNodeStyle = (node) => ({
  left: `${node.x}px`,
  top: `${node.y}px`,
  width: `${node.width}px`
})

// 连接线路径
const getConnectionPath = (conn) => {
  const sourceNode = workflowStore.getNode(conn.sourceNodeId)
  const targetNode = workflowStore.getNode(conn.targetNodeId)
  if (!sourceNode || !targetNode) return ''
  
  const startX = sourceNode.x + sourceNode.width
  const startY = sourceNode.y + 30
  const endX = targetNode.x
  const endY = targetNode.y + 30
  
  const controlPointOffset = Math.abs(endX - startX) / 2
  return `M ${startX} ${startY} C ${startX + controlPointOffset} ${startY}, ${endX - controlPointOffset} ${endY}, ${endX} ${endY}`
}

// 临时连接线路径
const tempConnectionPath = computed(() => {
  if (!tempConnection.value) return ''
  const { startX, startY, endX, endY } = tempConnection.value
  const controlPointOffset = Math.abs(endX - startX) / 2
  return `M ${startX} ${startY} C ${startX + controlPointOffset} ${startY}, ${endX - controlPointOffset} ${endY}, ${endX} ${endY}`
})

// 拖拽开始
const onDragStart = (event, nodeType) => {
  event.dataTransfer.setData('nodeType', nodeType.type)
}

// 放置节点
const onDrop = (event) => {
  const nodeType = event.dataTransfer.getData('nodeType')
  if (!nodeType) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = (event.clientX - rect.left) / scale.value - panOffset.value.x
  const y = (event.clientY - rect.top) / scale.value - panOffset.value.y
  
  workflowStore.addNode(nodeType, { x, y })
}

// 画布点击
const onCanvasClick = () => {
  workflowStore.selectNode(null)
}

// 画布拖拽
const onCanvasMouseDown = (event) => {
  if (event.button === 1 || event.shiftKey) {
    isPanning.value = true
    panStart.value = { x: event.clientX, y: event.clientY }
  }
}

const onCanvasMouseMove = (event) => {
  // 节点拖拽
  if (isDragging.value && dragNode.value) {
    const rect = canvasRef.value.getBoundingClientRect()
    const x = (event.clientX - rect.left) / scale.value - dragOffset.value.x
    const y = (event.clientY - rect.top) / scale.value - dragOffset.value.y
    workflowStore.updateNodePosition(dragNode.value.id, x, y)
  }
  
  // 画布平移
  if (isPanning.value) {
    const dx = event.clientX - panStart.value.x
    const dy = event.clientY - panStart.value.y
    panOffset.value.x += dx / scale.value
    panOffset.value.y += dy / scale.value
    panStart.value = { x: event.clientX, y: event.clientY }
  }
  
  // 连接线拖拽
  if (tempConnection.value) {
    const rect = canvasRef.value.getBoundingClientRect()
    tempConnection.value.endX = (event.clientX - rect.left) / scale.value
    tempConnection.value.endY = (event.clientY - rect.top) / scale.value
  }
}

const onCanvasMouseUp = () => {
  isDragging.value = false
  dragNode.value = null
  isPanning.value = false
  tempConnection.value = null
}

// 节点拖拽
const onNodeMouseDown = (event, node) => {
  workflowStore.selectNode(node.id)
  isDragging.value = true
  dragNode.value = node
  
  const rect = canvasRef.value.getBoundingClientRect()
  dragOffset.value = {
    x: (event.clientX - rect.left) / scale.value - node.x,
    y: (event.clientY - rect.top) / scale.value - node.y
  }
}

// 端口操作
const onPortMouseDown = (event, node, port, portType) => {
  if (portType === 'output') {
    tempConnection.value = {
      sourceNodeId: node.id,
      sourcePortId: port.id,
      startX: node.x + node.width,
      startY: node.y + 30,
      endX: node.x + node.width,
      endY: node.y + 30
    }
  }
}

const onPortMouseUp = (event, node, port, portType) => {
  if (portType === 'input' && tempConnection.value) {
    workflowStore.addConnection(
      tempConnection.value.sourceNodeId,
      tempConnection.value.sourcePortId,
      node.id,
      port.id
    )
  }
  tempConnection.value = null
}

// 连接线点击
const onConnectionClick = (conn) => {
  workflowStore.deleteConnection(conn.id)
}

// 删除节点
const deleteNode = (nodeId) => {
  workflowStore.deleteNode(nodeId)
}

// 选择节点
const selectNode = (nodeId) => {
  workflowStore.selectNode(nodeId)
}

// 缩放
const zoomIn = () => {
  scale.value = Math.min(scale.value + 0.1, 2)
}

const zoomOut = () => {
  scale.value = Math.max(scale.value - 0.1, 0.5)
}

const resetZoom = () => {
  scale.value = 1
  panOffset.value = { x: 0, y: 0 }
}

// 清空画布
const clearCanvas = () => {
  workflowStore.clearCanvas()
}
</script>

<style lang="scss" scoped>
.workflow-editor {
  display: flex;
  height: 100%;
  background: #f8fafc;
}

// 左侧节点面板
.node-panel {
  width: 240px;
  background: #fff;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  
  .panel-header {
    padding: 16px;
    border-bottom: 1px solid #e5e7eb;
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #1f2937;
    }
  }
  
  .node-categories {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
  }
  
  .category {
    margin-bottom: 16px;
    
    .category-title {
      font-size: 12px;
      color: #6b7280;
      margin-bottom: 8px;
      font-weight: 500;
    }
  }
  
  .node-list {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }
  
  .node-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    background: #f9fafb;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    cursor: grab;
    transition: all 0.2s;
    
    &:hover {
      border-color: #7c3aed;
      box-shadow: 0 2px 8px rgba(124, 58, 237, 0.15);
    }
    
    &:active {
      cursor: grabbing;
    }
    
    .node-icon {
      width: 28px;
      height: 28px;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 14px;
    }
    
    .node-label {
      font-size: 13px;
      color: #374151;
    }
  }
}

// 画布区域
.canvas-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .canvas-toolbar {
    padding: 12px 16px;
    background: #fff;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .canvas {
    flex: 1;
    position: relative;
    overflow: hidden;
    transform-origin: 0 0;
    
    .grid-background {
      position: absolute;
      top: 0;
      left: 0;
      pointer-events: none;
    }
    
    .connections-layer {
      position: absolute;
      top: 0;
      left: 0;
      pointer-events: none;
      
      .connection-line {
        pointer-events: stroke;
        cursor: pointer;
        
        &:hover {
          stroke: #ef4444;
          stroke-width: 3;
        }
      }
    }
  }
}

// 工作流节点
.workflow-node {
  position: absolute;
  background: #fff;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: move;
  user-select: none;
  
  &.selected {
    border-color: #7c3aed;
    box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.2);
  }
  
  .node-header {
    padding: 8px 12px;
    border-radius: 6px 6px 0 0;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
    
    .node-icon {
      font-size: 14px;
    }
    
    .node-title {
      flex: 1;
      font-size: 13px;
      font-weight: 500;
    }
    
    .delete-btn {
      cursor: pointer;
      opacity: 0.7;
      
      &:hover {
        opacity: 1;
      }
    }
  }
  
  .node-body {
    padding: 8px 12px;
    min-height: 20px;
    position: relative;
  }
  
  .port {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    
    &.input-port {
      left: -8px;
    }
    
    &.output-port {
      right: -8px;
    }
    
    .port-dot {
      width: 12px;
      height: 12px;
      background: #fff;
      border: 2px solid #94a3b8;
      border-radius: 50%;
      cursor: crosshair;
      transition: all 0.2s;
      
      &:hover {
        background: #7c3aed;
        border-color: #7c3aed;
        transform: scale(1.3);
      }
    }
  }
}

// 右侧属性面板
.property-panel {
  width: 280px;
  background: #fff;
  border-left: 1px solid #e5e7eb;
  
  .panel-header {
    padding: 16px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #1f2937;
    }
    
    .close-btn {
      cursor: pointer;
      color: #6b7280;
      
      &:hover {
        color: #1f2937;
      }
    }
  }
  
  .property-content {
    padding: 16px;
  }
}
</style>
