<template>
  <div class="er-diagram">
    <el-empty v-if="!graph.nodes.length" description="生成数据库后可查看 ER 图" />
    <template v-else>
      <div class="er-toolbar">
        <div class="relation-builder">
          <el-select v-model="relationForm.source" placeholder="来源表">
            <el-option v-for="node in graph.nodes" :key="node.id" :label="node.title" :value="node.id" />
          </el-select>
          <el-select v-model="relationForm.sourceField" placeholder="来源字段">
            <el-option v-for="field in sourceFields" :key="field.id" :label="field.name" :value="field.name" />
          </el-select>
          <span class="relation-arrow">→</span>
          <el-select v-model="relationForm.target" placeholder="目标表">
            <el-option v-for="node in graph.nodes" :key="node.id" :label="node.title" :value="node.id" />
          </el-select>
          <el-select v-model="relationForm.targetField" placeholder="目标字段">
            <el-option v-for="field in targetFields" :key="field.id" :label="field.name" :value="field.name" />
          </el-select>
          <el-button type="primary" :icon="Plus" @click="addRelation">添加关系</el-button>
        </div>
        <el-button :icon="Picture" @click="exportPng">导出图片</el-button>
      </div>

      <div class="er-scroll">
      <svg ref="svgRef" class="er-canvas" :viewBox="`0 0 ${canvas.width} ${canvas.height}`" :style="canvasStyle">
        <defs>
          <marker
            id="er-arrow"
            markerWidth="10"
            markerHeight="10"
            refX="8"
            refY="3"
            orient="auto"
            markerUnits="strokeWidth"
          >
            <path d="M0,0 L0,6 L8,3 z" fill="#8aa0bc" />
          </marker>
        </defs>

        <g class="edge-layer">
          <g v-for="edge in edgeViews" :key="edge.id">
            <path class="relation-line" :class="{ manual: !edge.inferred }" :d="edge.path" marker-end="url(#er-arrow)" />
            <text class="relation-label" :x="edge.labelX" :y="edge.labelY">{{ edge.fieldName }}</text>
            <g class="edge-delete" :transform="`translate(${edge.labelX + 44}, ${edge.labelY - 13})`" @click="removeRelation(edge)">
              <circle r="9" />
              <path d="M-4,-4 L4,4 M4,-4 L-4,4" />
            </g>
          </g>
        </g>

        <g class="node-layer">
          <foreignObject
            v-for="node in graph.nodes"
            :key="node.id"
            :x="node.x"
            :y="node.y"
            :width="node.width"
            :height="node.height"
          >
            <div xmlns="http://www.w3.org/1999/xhtml" class="entity-node" @pointerdown="startDrag($event, node)">
              <div class="entity-head">
                <strong>{{ node.title }}</strong>
                <span v-if="node.comment">{{ node.comment }}</span>
              </div>
              <div class="field-list">
                <div v-for="field in node.fields" :key="field.id" class="field-row">
                  <span v-if="field.primary" class="field-badge primary">PK</span>
                  <span v-else-if="field.required" class="field-badge required">*</span>
                  <span v-else class="field-badge muted">-</span>
                  <span class="field-name">{{ field.name }}</span>
                  <small v-if="field.comment">{{ field.comment }}</small>
                </div>
                <div v-if="!node.fields.length" class="field-empty">暂无字段</div>
              </div>
            </div>
          </foreignObject>
        </g>
      </svg>
    </div>
    </template>
  </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Plus } from '@element-plus/icons-vue'
import { buildErExportSvg } from '@/utils/erExport'
import { buildErGraph } from '@/utils/erGraph'
import { saveBlob } from '@/utils/download'

const FIELD_HEIGHT = 28
const HEADER_HEIGHT = 60

const props = defineProps({
  tables: {
    type: Array,
    default: () => []
  },
  draft: {
    type: Object,
    default: () => ({ positions: {}, relations: [], deletedEdgeIds: [] })
  }
})

const emit = defineEmits(['update:draft'])
const svgRef = ref(null)
const relationForm = reactive({
  source: '',
  sourceField: '',
  target: '',
  targetField: ''
})
const dragging = ref(null)

const draftValue = computed(() => normalizeDraft(props.draft))
const graph = computed(() => buildErGraph(props.tables, draftValue.value))

const nodeMap = computed(() => {
  const map = new Map()
  graph.value.nodes.forEach((node) => map.set(node.id, node))
  return map
})

const canvas = computed(() => {
  const nodes = graph.value.nodes
  const width = Math.max(900, ...nodes.map((node) => node.x + node.width + 48))
  const height = Math.max(480, ...nodes.map((node) => node.y + node.height + 48))
  return { width, height }
})

const canvasStyle = computed(() => ({
  width: `${canvas.value.width}px`,
  height: `${canvas.value.height}px`
}))

const sourceFields = computed(() => fieldsOf(relationForm.source))
const targetFields = computed(() => fieldsOf(relationForm.target))

watch(
  () => graph.value.nodes.map((node) => node.id).join(','),
  () => ensureRelationDefaults(),
  { immediate: true }
)

watch(
  () => relationForm.source,
  () => {
    relationForm.sourceField = sourceFields.value[0]?.name || ''
  }
)

watch(
  () => relationForm.target,
  () => {
    relationForm.targetField = targetFields.value[0]?.name || ''
  }
)

function normalizeDraft(value) {
  const source = value && typeof value === 'object' ? value : {}
  return {
    positions: source.positions && typeof source.positions === 'object' ? source.positions : {},
    relations: Array.isArray(source.relations) ? source.relations : [],
    deletedEdgeIds: Array.isArray(source.deletedEdgeIds) ? source.deletedEdgeIds : []
  }
}

function emitDraft(patch) {
  emit('update:draft', {
    ...draftValue.value,
    ...patch
  })
}

function fieldsOf(nodeId) {
  return nodeMap.value.get(nodeId)?.fields || []
}

function ensureRelationDefaults() {
  const nodes = graph.value.nodes
  if (!relationForm.source && nodes[0]) {
    relationForm.source = nodes[0].id
  }
  if (!relationForm.target && nodes[1]) {
    relationForm.target = nodes[1].id
  }
  if (!relationForm.target && nodes[0]) {
    relationForm.target = nodes[0].id
  }
  if (!relationForm.sourceField) {
    relationForm.sourceField = sourceFields.value[0]?.name || ''
  }
  if (!relationForm.targetField) {
    relationForm.targetField = targetFields.value[0]?.name || ''
  }
}

function fieldY(node, fieldName) {
  const index = Math.max(0, node.fields.findIndex((field) => field.name === fieldName))
  return node.y + HEADER_HEIGHT + index * FIELD_HEIGHT + FIELD_HEIGHT / 2
}

function edgeAnchors(edge) {
  const source = nodeMap.value.get(edge.source)
  const target = nodeMap.value.get(edge.target)
  if (!source || !target) return null

  const sourceOnLeft = source.x <= target.x
  const sourceX = sourceOnLeft ? source.x + source.width : source.x
  const targetX = sourceOnLeft ? target.x : target.x + target.width
  return {
    sourceX,
    sourceY: fieldY(source, edge.fieldName),
    targetX,
    targetY: fieldY(target, edge.targetFieldName),
    curve: Math.max(56, Math.abs(targetX - sourceX) / 2)
  }
}

function addRelation() {
  if (!relationForm.source || !relationForm.target || !relationForm.sourceField || !relationForm.targetField) {
    ElMessage.warning('请选择关系两端的表和字段')
    return
  }
  if (relationForm.source === relationForm.target) {
    ElMessage.warning('关系两端不能是同一张表')
    return
  }

  const relation = {
    id: `manual_${Date.now()}_${Math.random().toString(16).slice(2)}`,
    source: relationForm.source,
    target: relationForm.target,
    fieldName: relationForm.sourceField,
    targetFieldName: relationForm.targetField
  }
  emitDraft({ relations: [...draftValue.value.relations, relation] })
}

function removeRelation(edge) {
  if (edge.inferred) {
    emitDraft({ deletedEdgeIds: Array.from(new Set([...draftValue.value.deletedEdgeIds, edge.id])) })
    return
  }
  emitDraft({ relations: draftValue.value.relations.filter((relation) => relation.id !== edge.id) })
}

function startDrag(event, node) {
  dragging.value = {
    id: node.id,
    startX: event.clientX,
    startY: event.clientY,
    x: node.x,
    y: node.y
  }
  event.currentTarget.setPointerCapture?.(event.pointerId)
  window.addEventListener('pointermove', handleDrag)
  window.addEventListener('pointerup', stopDrag, { once: true })
}

function handleDrag(event) {
  if (!dragging.value) return

  const nextX = Math.max(0, Math.round(dragging.value.x + event.clientX - dragging.value.startX))
  const nextY = Math.max(0, Math.round(dragging.value.y + event.clientY - dragging.value.startY))
  emitDraft({
    positions: {
      ...draftValue.value.positions,
      [dragging.value.id]: { x: nextX, y: nextY }
    }
  })
}

function stopDrag() {
  dragging.value = null
  window.removeEventListener('pointermove', handleDrag)
}

async function exportPng() {
  const svgText = buildErExportSvg({
    width: canvas.value.width,
    height: canvas.value.height,
    nodes: graph.value.nodes,
    edges: edgeViews.value
  })
  const svgBlob = new Blob([svgText], { type: 'image/svg+xml;charset=utf-8' })
  const url = URL.createObjectURL(svgBlob)
  const image = new Image()
  image.decoding = 'async'

  try {
    await new Promise((resolve, reject) => {
      image.onload = resolve
      image.onerror = reject
      image.src = url
    })
    const canvasElement = document.createElement('canvas')
    canvasElement.width = canvas.value.width
    canvasElement.height = canvas.value.height
    const context = canvasElement.getContext('2d')
    context.fillStyle = '#f8fafc'
    context.fillRect(0, 0, canvasElement.width, canvasElement.height)
    context.drawImage(image, 0, 0)
    const blob = await new Promise((resolve) => canvasElement.toBlob(resolve, 'image/png'))
    if (blob) {
      saveBlob(blob, 'er-diagram.png')
    }
  } finally {
    URL.revokeObjectURL(url)
  }
}

const edgeViews = computed(() => graph.value.edges
  .map((edge) => {
    const anchors = edgeAnchors(edge)
    if (!anchors) return null

    const direction = anchors.sourceX <= anchors.targetX ? 1 : -1
    const c1x = anchors.sourceX + anchors.curve * direction
    const c2x = anchors.targetX - anchors.curve * direction
    return {
      ...edge,
      path: `M ${anchors.sourceX} ${anchors.sourceY} C ${c1x} ${anchors.sourceY}, ${c2x} ${anchors.targetY}, ${anchors.targetX} ${anchors.targetY}`,
      labelX: (anchors.sourceX + anchors.targetX) / 2,
      labelY: (anchors.sourceY + anchors.targetY) / 2 - 8
    }
  })
  .filter(Boolean))
</script>

<style scoped lang="scss">
.er-diagram {
  min-height: 430px;
  background: #f8fafc;
}

.er-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 14px 18px;
  border-bottom: 1px solid #e3e8f0;
  background: #ffffff;
}

.relation-builder {
  display: grid;
  grid-template-columns: minmax(120px, 170px) minmax(120px, 170px) auto minmax(120px, 170px) minmax(120px, 170px) auto;
  align-items: center;
  gap: 10px;
}

.relation-arrow {
  color: #64748b;
  font-weight: 700;
}

.er-scroll {
  overflow: auto;
  min-height: 430px;
  padding: 24px;
}

.er-canvas {
  display: block;
}

.relation-line {
  fill: none;
  stroke: #8aa0bc;
  stroke-width: 1.6;
  stroke-dasharray: 6 5;
}

.relation-line.manual {
  stroke: #2563eb;
  stroke-dasharray: none;
}

.edge-delete {
  cursor: pointer;

  circle {
    fill: #ffffff;
    stroke: #e2e8f0;
  }

  path {
    stroke: #ef4444;
    stroke-width: 1.8;
    stroke-linecap: round;
  }
}

.relation-label {
  fill: #64748b;
  font-size: 12px;
  paint-order: stroke;
  stroke: #f8fafc;
  stroke-width: 4px;
  text-anchor: middle;
}

.entity-node {
  overflow: hidden;
  height: 100%;
  border: 1px solid #d6e0ee;
  border-radius: 8px;
  background: #ffffff;
  box-shadow: 0 8px 20px rgba(15, 23, 42, 0.08);
  cursor: move;
  user-select: none;
}

.entity-head {
  display: grid;
  gap: 4px;
  padding: 12px 14px;
  border-bottom: 1px solid #e7edf5;
  background: #eef5ff;

  strong {
    overflow: hidden;
    color: #0f172a;
    font-size: 15px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  span {
    overflow: hidden;
    color: #64748b;
    font-size: 12px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.field-list {
  padding: 8px 10px 10px;
}

.field-row {
  display: grid;
  grid-template-columns: 34px minmax(0, 1fr) minmax(0, 0.9fr);
  align-items: center;
  gap: 6px;
  min-height: 28px;
  color: #334155;
  font-size: 13px;

  small {
    overflow: hidden;
    color: #94a3b8;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.field-badge {
  display: inline-grid;
  min-width: 26px;
  height: 18px;
  place-items: center;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 700;
}

.field-badge.primary {
  color: #1d4ed8;
  background: #dbeafe;
}

.field-badge.required {
  color: #b45309;
  background: #fef3c7;
}

.field-badge.muted {
  color: #cbd5e1;
}

.field-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.field-empty {
  padding: 18px 0;
  color: #94a3b8;
  text-align: center;
}

@media (max-width: 1080px) {
  .er-toolbar {
    align-items: flex-start;
    flex-direction: column;
  }

  .relation-builder {
    grid-template-columns: minmax(140px, 1fr) minmax(140px, 1fr);
    width: 100%;
  }

  .relation-arrow {
    display: none;
  }
}
</style>
