<template>
  <div class="container">
    <el-card class="control-panel">
      <div class="controls">
        <el-form label-width="100px">
          <el-form-item label="画布宽度">
            <el-input-number v-model="canvasWidth"
                             :min="100"
                             :max="2000"
                             :step="50" />
          </el-form-item>
          <el-form-item label="画布高度">
            <el-input-number v-model="canvasHeight"
                             :min="100"
                             :max="2000"
                             :step="50" />
          </el-form-item>
          <el-form-item label="间距(px)">
            <el-input-number v-model="svgSpacing"
                             :min="0"
                             :max="200"
                             :step="5" />
          </el-form-item>
        </el-form>

        <div class="action-buttons">
          <el-button @click="importSVG" type="primary">
            <el-icon><Upload /></el-icon>
            导入SVG文件
          </el-button>

          <el-button @click="clearAll" type="danger">
            <el-icon><Delete /></el-icon>
            清空画布
          </el-button>

          <el-button @click="exportSVG" type="success">
            <el-icon><Download /></el-icon>
            导出SVG文件
          </el-button>
        </div>
      </div>
    </el-card>

    <div class="canvas-container">
      <svg ref="svgCanvas"
           :width="canvasWidth"
           :height="canvasHeight"
           class="svg-canvas"
           xmlns="http://www.w3.org/2000/svg">
        <g id="svg-container"></g>
      </svg>
    </div>

  </div>
</template>

<script setup>
  import { ref, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Upload, Download, Delete } from '@element-plus/icons-vue'

  // 画布尺寸控制（默认800x600）
  const canvasWidth = ref(800)
  const canvasHeight = ref(550)
  const svgSpacing = ref(10) // SVG之间的间距

  // 引用SVG画布元素
  const svgCanvas = ref(null)

  // 存储导入的SVG数据
  const importedSVGs = ref([])

  // 更新SVG显示
  const updateSVGDisplay = () => {
    if (!svgCanvas.value) return

    const container = svgCanvas.value.querySelector('#svg-container')
    if (!container) return

    // 清空现有内容
    container.innerHTML = ''

    let currentX = 0

    // 按顺序渲染所有SVG
    importedSVGs.value.forEach(svgData => {
      if (svgData.content) {
        const wrapper = document.createElementNS('http://www.w3.org/2000/svg', 'g')
        wrapper.setAttribute('transform', `translate(${currentX},0)`)
        wrapper.innerHTML = svgData.content

        container.appendChild(wrapper)

        // 更新下一个SVG的位置
        currentX += svgData.width + svgSpacing.value
      }
    })

    // 调整画布宽度以适应所有SVG
    if (importedSVGs.value.length > 0) {
      const totalWidth = currentX - svgSpacing.value
      canvasWidth.value = Math.max(totalWidth, canvasWidth.value)
    }
  }

  // 导入SVG逻辑
  const importSVG = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.svg'
    input.multiple = true
    input.style.display = 'none'

    input.onchange = async (e) => {
      const files = Array.from(e.target.files)
      if (!files.length) return

      try {
        // 处理所有选中的SVG文件
        const newSVGs = await Promise.all(files.map(file =>
          new Promise((resolve) => {
            const reader = new FileReader()
            reader.onload = (event) => {
              const content = event.target.result

              // 获取SVG尺寸
              const div = document.createElement('div')
              div.innerHTML = content
              document.body.appendChild(div)
              const svgElement = div.querySelector('svg')
              let originalWidth = 100, originalHeight = 100

              if (svgElement) {
                originalWidth = svgElement.width.baseVal.value ||
                  svgElement.getBoundingClientRect().width || 100
                originalHeight = svgElement.height.baseVal.value ||
                  svgElement.getBoundingClientRect().height || 100
              }

              // 计算新尺寸，固定高度为100px，宽度按比例缩放
              const ratio = originalWidth / originalHeight || 1;
              const height = 100;
              const width = ratio * height;

              document.body.removeChild(div)

              // 创建一个独特的ID避免冲突
              const uniqueId = 'svg-' + Math.random().toString(36).substr(2, 9)
              const contentWithUniqueIds = content.replace(/id="([^"]+)"/g, `id="${uniqueId}-$1"`)
                .replace(/url$#([^)]+)$/g, `url(#${uniqueId}-$1)`)

              resolve({
                content: contentWithUniqueIds,
                width: width,
                height: height,
                name: file.name
              })
            }
            reader.readAsText(file)
          })
        ))

        // 添加到已导入列表
        importedSVGs.value = [...importedSVGs.value, ...newSVGs]
        updateSVGDisplay()

        ElMessage.success(`成功导入${files.length}个SVG文件`)
      } catch (error) {
        console.error('导入SVG失败:', error)
        ElMessage.error('导入SVG失败: ' + error.message)
      }

      document.body.removeChild(input)
    }

    document.body.appendChild(input)
    input.click()
  }

  // 清空所有SVG
  const clearAll = () => {
    importedSVGs.value = []
    updateSVGDisplay()
    ElMessage.success('画布已清空')
  }

  // 当间距变化时更新显示
  watch(svgSpacing, updateSVGDisplay)

  // SVG导出功能
  const exportSVG = () => {
    try {
      if (importedSVGs.value.length === 0) {
        ElMessage.warning('没有可导出的SVG内容')
        return
      }

      // 计算导出尺寸
      const totalWidth = importedSVGs.value.reduce(
        (sum, svg, index) => sum + svg.width + (index === 0 ? 0 : svgSpacing.value),
        0
      )

      const maxHeight = Math.max(...importedSVGs.value.map(svg => svg.height))

      // 获取所有SVG的组合内容
      const svgHeader = `<svg xmlns="http://www.w3.org/2000/svg"
                             width="${totalWidth}"
                             height="${maxHeight}"
                             viewBox="0 0 ${totalWidth} ${maxHeight}">`

      let currentX = 0
      let combinedContent = ''

      importedSVGs.value.forEach(svg => {
        combinedContent += `<g transform="translate(${currentX},0)">${svg.content}</g>`
        currentX += svg.width + svgSpacing.value
      })

      const fullSVG = `${svgHeader}${combinedContent}</svg>`

      // 创建Blob对象
      const blob = new Blob([fullSVG], { type: 'image/svg+xml;charset=utf-8' })

      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `combined-svg-${new Date().getTime()}.svg`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      ElMessage.success('SVG导出成功')
    } catch (error) {
      console.error('导出SVG失败:', error)
      ElMessage.error('导出SVG失败: ' + error.message)
    }
  }

  onMounted(() => {
    ElMessage.success('SVG画布已初始化')
  })
</script>

<style scoped>
  .container {
    display: flex;
    flex-direction: column;
    padding: 20px;
    background-color: #f5f7fa;
    height: calc(100vh - 100px);
  }

  .control-panel {
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
  }

  .action-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .canvas-container {
    flex: 1;
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: auto;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .svg-canvas {
    border: 1px solid #ebeef5;
    background-color: white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    background-image: linear-gradient(45deg, #f5f5f5 25%, transparent 25%), linear-gradient(-45deg, #f5f5f5 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f5f5f5 75%), linear-gradient(-45deg, transparent 75%, #f5f5f5 75%);
    background-size: 20px 20px;
    background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  }

  .imported-svg {
    cursor: move;
    transition: transform 0.2s;
  }
</style>
