<template>
  <div>
    <svg width="800" height="600">
      <path
        v-for="(curve, index) in curves"
        :key="index"
        :d="getCurvePath(curve)"
        :stroke="curve.isSelected ? 'red' : 'blue'"
        stroke-width="2"
        fill="none"
        @mousedown="selectCurve(index)"
      />
      <circle
        v-for="(curve, index) in curves"
        :key="'start-' + index"
        :cx="curve.beginControlX"
        :cy="curve.beginControlY"
        r="5"
        fill="green"
        @mousedown="startDrag(index, 'start')"
      />
      <circle
        v-for="(curve, index) in curves"
        :key="'end-' + index"
        :cx="curve.endControlX"
        :cy="curve.endControlY"
        r="5"
        fill="green"
        @mousedown="startDrag(index, 'end')"
      />
    </svg>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 初始点位数据
const curves = ref([
  {
    startPointX: 100,
    startPointY: 100,
    endPointX: 300,
    endPointY: 100,
    beginControlX: 100,
    beginControlY: 100,
    endControlX: 300,
    endControlY: 100,
    isSelected: false
  },
  {
    startPointX: 200,
    startPointY: 200,
    endPointX: 400,
    endPointY: 200,
    beginControlX: 200,
    beginControlY: 200,
    endControlX: 400,
    endControlY: 200,
    isSelected: false
  }
])

// 当前拖动的曲线索引和控制点类型
const dragging = ref({
  index: null,
  type: null
})

// 获取曲线的路径字符串
const getCurvePath = (curve) => {
  return `M${curve.startPointX},${curve.startPointY} C${curve.beginControlX},${curve.beginControlY} ${curve.endControlX},${curve.endControlY} ${curve.endPointX},${curve.endPointY}`
}

// 选中曲线
const selectCurve = (index) => {
  curves.value.forEach((curve, i) => {
    curve.isSelected = i === index
  })
  console.log('Selected curve:', curves.value[index])
}

// 开始拖动控制点
const startDrag = (index, type) => {
  dragging.value = { index, type }
  window.addEventListener('mousemove', handleDrag)
  window.addEventListener('mouseup', endDrag)
}

// 处理拖动事件
const handleDrag = (event) => {
  if (dragging.value.index !== null) {
    const curve = curves.value[dragging.value.index]
    if (dragging.value.type === 'start') {
      curve.beginControlX = event.offsetX
      curve.beginControlY = event.offsetY
    } else {
      curve.endControlX = event.offsetX
      curve.endControlY = event.offsetY
    }
  }
}

// 结束拖动
const endDrag = () => {
  dragging.value = { index: null, type: null }
  window.removeEventListener('mousemove', handleDrag)
  window.removeEventListener('mouseup', endDrag)
}
</script>
