<template>
  <div class="mx-toolbar">
    <button @click="zoomIn"><span class="icon">+</span> 放大</button>
    <button @click="zoomOut"><span class="icon">-</span> 缩小</button>
    <button @click="zoomActual"><span class="icon">↻</span> 实际大小</button>
    <button @click="deleteSelected"><span class="icon">×</span> 删除</button>
    <button @click="saveGraph"><span class="icon">💾</span> 保存</button>
    <button @click="loadGraph"><span class="icon">📂</span> 加载</button>
    <button @click="exportXML"><span class="icon">📤</span> 导出XML</button>
    <button @click="importXML"><span class="icon">📥</span> 导入XML</button>
    <input ref="fileInput" type="file" accept=".xml" @change="handleFileUpload" style="display: none" />
  </div>
</template>

<script setup lang="ts">
import { inject } from 'vue'
import { myMxCodec, myMxGraph, myMxUtils } from '@/graph/mxGraph'

const graph = inject<Ref<InstanceType<typeof myMxGraph> | null>>('mxgraph-instance')
const fileInput = ref<HTMLInputElement | null>(null)
// 导出XML
function exportXML() {
  if (!graph?.value) return

  const encoder = new myMxCodec()
  const node = encoder.encode(graph.value.getModel())
  const xml = myMxUtils.getXml(node)

  // 创建下载链接
  const blob = new Blob([xml], { type: 'text/xml' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `graph-${new Date().toISOString().slice(0, 10)}.xml`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 触发文件选择
function importXML() {
  fileInput.value?.click()
}

// 处理文件上传
function handleFileUpload(event: Event) {
  const input = event.target as HTMLInputElement
  if (!input.files?.length || !graph?.value) return

  const file = input.files[0]
  const reader = new FileReader()

  reader.onload = e => {
    try {
      const xml = e.target?.result as string
      loadXML(xml)
    } catch (error) {
      alert('导入失败: ' + (error as Error).message)
    }
    // 重置input值，允许重复选择同一文件
    input.value = ''
  }

  reader.readAsText(file)
}

// 加载XML到图形
function loadXML(xml: string) {
  if (!graph?.value) return

  try {
    const doc = myMxUtils.parseXml(xml)
    const codec = new myMxCodec(doc)

    // 先清空现有图形
    graph.value.getModel().clear()

    // 导入新图形
    codec.decode(doc.documentElement, graph.value.getModel())
    alert('图形导入成功')
  } catch (error) {
    alert('导入失败: ' + (error as Error).message)
  }
}
function zoomIn() {
  graph?.value?.zoomIn()
}

function zoomOut() {
  graph?.value?.zoomOut()
}

function zoomActual() {
  graph?.value?.zoomActual()
}

function deleteSelected() {
  const cells = graph?.value?.getSelectionCells()
  if (cells && cells.length > 0) {
    graph?.value?.removeCells(cells)
  }
}

function saveGraph() {
  if (!graph?.value) return
  const encoder = new myMxCodec()
  const node = encoder.encode(graph.value.getModel())
  const xml = myMxUtils.getXml(node)
  console.log('Graph XML:', xml)
  alert('图形已保存到控制台(查看日志)')
}

function loadGraph() {
  if (!graph?.value) return
  const xml = prompt('请输入图形XML:')
  if (xml) {
    try {
      const doc = myMxUtils.parseXml(xml)
      const codec = new myMxCodec(doc)
      codec.decode(doc.documentElement, graph.value.getModel())
    } catch (e) {
      alert('加载失败: ' + (e as Error).message)
    }
  }
}
</script>
<style lang="scss" scoped>
.mx-toolbar {
  padding: 8px 12px;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  gap: 8px;
}

.mx-toolbar button {
  padding: 6px 12px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
}

.mx-toolbar button:hover {
  background: #f0f0f0;
}

.mx-toolbar .icon {
  font-size: 14px;
}
</style>
