<template>
  <div class="page-designer">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="savePage">保存页面</el-button>
      <el-button @click="previewPage">预览</el-button>
      <el-button @click="exportConfig">导出配置</el-button>
      <el-button @click="clearCanvas">清空画布</el-button>
    </div>

    <div class="designer-container">
      <!-- 左侧组件库 -->
      <div class="component-library">
        <h3>组件库</h3>
        <div class="component-categories">
          <div 
            v-for="category in componentCategories" 
            :key="category.name"
            class="category"
          >
            <h4>{{ category.name }}</h4>
            <div class="component-list">
              <div 
                v-for="component in category.components" 
                :key="component.id"
                class="component-item"
                draggable="true"
                @dragstart="onDragStart($event, component)"
              >
                <i :class="component.icon"></i>
                <span>{{ component.name }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 设计画布 -->
      <div 
        ref="canvasRef"
        class="design-canvas"
        @dragover.prevent
        @drop="onDrop"
        @click="clearSelection"
      >
        <div 
          v-for="comp in pageComponents" 
          :key="comp.id"
          :class="['canvas-component', { selected: selectedComponent?.id === comp.id }]"
          :style="getComponentStyle(comp)"
          @mousedown="startDrag(comp, $event)"
          @click.stop="selectComponent(comp)"
        >
          <component :is="comp.component" v-bind="comp.props" />
          
          <!-- 控制手柄 -->
          <div v-if="selectedComponent?.id === comp.id" class="component-controls">
            <!-- 旋转手柄 -->
            <div class="rotate-handle" @mousedown.stop="startRotate(comp, $event)"></div>
            <!-- 缩放手柄 -->
            <div class="resize-handle resize-se" @mousedown.stop="startResize(comp, $event, 'se')"></div>
            <div class="resize-handle resize-sw" @mousedown.stop="startResize(comp, $event, 'sw')"></div>
            <div class="resize-handle resize-ne" @mousedown.stop="startResize(comp, $event, 'ne')"></div>
            <div class="resize-handle resize-nw" @mousedown.stop="startResize(comp, $event, 'nw')"></div>
          </div>
        </div>
      </div>

      <!-- 属性面板 -->
      <div class="property-panel">
        <h3>属性设置</h3>
        <div v-if="selectedComponent">
          <el-form :model="selectedComponent" label-width="80px">
            <el-form-item label="位置X">
              <el-input-number v-model="selectedComponent.position.x" :min="0" :max="2000" />
            </el-form-item>
            <el-form-item label="位置Y">
              <el-input-number v-model="selectedComponent.position.y" :min="0" :max="2000" />
            </el-form-item>
            <el-form-item label="旋转角度">
              <el-input-number 
                v-model="selectedComponent.rotation" 
                :min="0" 
                :max="360" 
                @change="normalizeRotation"
              />
            </el-form-item>
            <el-form-item label="组态名称">
              <el-input v-model="selectedComponent.props.title" placeholder="请输入组态名称" />
            </el-form-item>
            <el-form-item v-if="selectedComponent.props.iconSize !== undefined && selectedComponent.props.iconWidth === undefined" label="图标大小">
              <el-input-number v-model="selectedComponent.props.iconSize" :min="10" :max="500" />
            </el-form-item>
            <el-form-item v-if="selectedComponent.props.iconWidth !== undefined" label="图标宽度">
              <el-input-number v-model="selectedComponent.props.iconWidth" :min="10" :max="500" />
            </el-form-item>
            <el-form-item v-if="selectedComponent.props.iconHeight !== undefined" label="图标高度">
              <el-input-number v-model="selectedComponent.props.iconHeight" :min="10" :max="500" />
            </el-form-item>
            <el-form-item v-if="selectedComponent.props.iconSize === undefined && selectedComponent.props.iconWidth === undefined" label="缩放">
              <el-slider v-model="selectedComponent.scale" :min="0.1" :max="3" :step="0.1" />
            </el-form-item>
            <!-- 其他组件特定属性 -->
            <el-form-item v-if="selectedComponent.props.rotateAngle !== undefined" label="组件旋转">
              <el-input-number v-model="selectedComponent.props.rotateAngle" :min="0" :max="360" />
            </el-form-item>
            <el-form-item v-if="selectedComponent.props.isReverse !== undefined" label="反转">
              <el-switch v-model="selectedComponent.props.isReverse" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElButton, ElForm, ElFormItem, ElInputNumber, ElSlider, ElInput, ElSwitch } from 'element-plus'

// 导入所有GeneralComponents组件
import ValveComponent from '@/components/GeneralComponents/ValveComponent.vue'
import MTypeTankComponent from '@/components/GeneralComponents/MTypeTankComponent.vue'
import MTypeHollowTankComponent from '@/components/GeneralComponents/MTypeHollowTankComponent.vue'
import STypeTankComponent from '@/components/GeneralComponents/STypeTankComponent.vue'
import STypeHollowTankComponent from '@/components/GeneralComponents/STypeHollowTankComponent.vue'
import JTypeTankComponent from '@/components/GeneralComponents/JTypeTankComponent.vue'
import RTypeHollowTankComponent from '@/components/GeneralComponents/RTypeHollowTankComponent.vue'
import PumpComponent from '@/components/GeneralComponents/PumpComponent.vue'
import MixerComponent from '@/components/GeneralComponents/MixerComponent.vue'
import ArrowComponent from '@/components/GeneralComponents/ArrowComponent.vue'
import PipelineComponent from '@/components/GeneralComponents/PipelineComponent.vue'
import FlowMeterComponent from '@/components/GeneralComponents/FlowMeterComponent.vue'
import PressureGaugeComponent from '@/components/GeneralComponents/PressureGaugeComponent.vue'
import TempSliderComponent from '@/components/GeneralComponents/TempSliderComponent.vue'
import PhSliderComponent from '@/components/GeneralComponents/PhSliderComponent.vue'
import WaterLevelMapComponent from '@/components/GeneralComponents/WaterLevelMapComponent.vue'
import PageIconSHComponent from '@/components/GeneralComponents/PageIconSHComponent.vue'
import PageIconHNComponent from '@/components/GeneralComponents/PageIconHNComponent.vue'

// 组件库配置
const componentCategories = [
  {
    name: '储罐组件',
    components: [
      {
        id: 'mTypeTank',
        name: 'M型罐',
        icon: 'iconfont-colour icon-initialTank1',
        component: 'MTypeTankComponent',
        props: { title: '', iconSize: 200 }
      },
      {
        id: 'mTypeHollowTank',
        name: 'M型镂空罐',
        icon: 'iconfont-colour icon-initialTank1',
        component: 'MTypeHollowTankComponent',
        props: { title: '', iconSize: 200, isHollow: true }
      },
      {
        id: 'sTypeTank',
        name: 'S型罐',
        icon: 'iconfont-colour icon-initialTank1',
        component: 'STypeTankComponent',
        props: { title: '', iconSize: 200 }
      },
      {
        id: 'sTypeHollowTank',
        name: 'S型镂空罐',
        icon: 'iconfont-colour icon-initialTank1',
        component: 'STypeHollowTankComponent',
        props: { title: '', iconSize: 200, isHollow: true }
      },
      {
        id: 'jTypeTank',
        name: 'J型罐',
        icon: 'iconfont-colour icon-initialTank1',
        component: 'JTypeTankComponent',
        props: { title: '', iconSize: 200 }
      },
      {
        id: 'rTypeHollowTank',
        name: 'R型镂空罐',
        icon: 'iconfont-colour icon-initialTank1',
        component: 'RTypeHollowTankComponent',
        props: { title: '', iconSize: 200, iconWidth: 200, iconHeight: 200 }
      }
    ]
  },
  {
    name: '控制组件',
    components: [
      {
        id: 'valve',
        name: '阀门',
        icon: 'iconfont icon-waterValve',
        component: 'ValveComponent',
        props: { title: '', iconSize: 50, valveStatusArr: [true] }
      },
      {
        id: 'pump',
        name: '泵',
        icon: 'iconfont-colour icon_pump',
        component: 'PumpComponent',
        props: { title: '', iconSize: 100, pumpDataArr: [1, 10] }
      },
      {
        id: 'mixer',
        name: '搅拌器',
        icon: 'iconfont icon-mixer',
        component: 'MixerComponent',
        props: { title: '', iconSize: 80 }
      }
    ]
  },
  {
    name: '管道组件',
    components: [
      {
        id: 'pipeline',
        name: '管道',
        icon: 'iconfont icon-pipeline',
        component: 'PipelineComponent',
        props: { title: '', pipeStatus: true, strokeWidth: 5 }
      },
      {
        id: 'arrow',
        name: '箭头',
        icon: 'iconfont icon-rightArrow',
        component: 'ArrowComponent',
        props: { title: '', arrowText: '流向', iconSize: 60, specialCondition: { arrowRotate: 0 } }
      },
      {
        id: 'flowMeter',
        name: '流量计',
        icon: 'iconfont icon-flowmeter',
        component: 'FlowMeterComponent',
        props: { title: '', flowValue: 100, iconSize: 80 }
      }
    ]
  },
  {
    name: '仪表组件',
    components: [
      {
        id: 'pressureGauge',
        name: '压力表',
        icon: 'iconfont icon-pressure',
        component: 'PressureGaugeComponent',
        props: { title: '', pressureValue: 1.5, iconSize: 100 }
      },
      {
        id: 'tempSlider',
        name: '温度计',
        icon: 'iconfont icon-temperature',
        component: 'TempSliderComponent',
        props: { title: '', tempValue: 25, iconSize: 80 }
      },
      {
        id: 'phSlider',
        name: 'pH计',
        icon: 'iconfont icon-ph',
        component: 'PhSliderComponent',
        props: { title: '', phValue: 7, iconSize: 80 }
      },
      {
        id: 'waterLevelMap',
        name: '液位图',
        icon: 'iconfont icon-waterlevel',
        component: 'WaterLevelMapComponent',
        props: { title: '', waterLevel: 0.6, iconSize: 100 }
      }
    ]
  },
  {
    name: '图标组件',
    components: [
      {
        id: 'pageIconSH',
        name: '上海图标',
        icon: 'iconfont icon-shanghai',
        component: 'PageIconSHComponent',
        props: { title: '', iconSize: 60 }
      },
      {
        id: 'pageIconHN',
        name: '湖南图标',
        icon: 'iconfont icon-hunan',
        component: 'PageIconHNComponent',
        props: { title: '', iconSize: 60 }
      }
    ]
  },

]

// 组件映射表
const componentMap = {
  ValveComponent,
  MTypeTankComponent,
  MTypeHollowTankComponent,
  STypeTankComponent,
  STypeHollowTankComponent,
  JTypeTankComponent,
  RTypeHollowTankComponent,
  PumpComponent,
  MixerComponent,
  ArrowComponent,
  PipelineComponent,
  FlowMeterComponent,
  PressureGaugeComponent,
  TempSliderComponent,
  PhSliderComponent,
  WaterLevelMapComponent,
  PageIconSHComponent,
  PageIconHNComponent
}

// 画布上的组件
const pageComponents = ref([])

// 当前选中组件
const selectedComponent = ref(null)



// 拖拽相关
let dragOffset = { x: 0, y: 0 }
let resizing = false
let resizingComponent = null
let rotating = false
let rotatingComponent = null

const canvasRef = ref(null)

// 拖拽开始
const onDragStart = (event, component) => {
  event.dataTransfer.setData('component', JSON.stringify({
    ...component,
    component: component.component // 传递组件名称
  }))
}

// 拖拽到画布
const onDrop = (event) => {
  const componentData = JSON.parse(event.dataTransfer.getData('component'))
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  const newComponent = {
    id: Date.now() + Math.random(),
    component: componentMap[componentData.component],
    props: { ...componentData.props },
    position: { x, y },
    rotation: 0,
    scale: 1
  }
  
  // 根据组件类型设置默认属性
  if (!componentData.props.hasOwnProperty('iconSize') && 
      !componentData.props.hasOwnProperty('iconWidth') && 
      !componentData.props.hasOwnProperty('iconHeight')) {
    newComponent.scale = 1
  }
  

  
  pageComponents.value.push(newComponent)
}

// 组件样式
const getComponentStyle = (comp) => {
  const hasIconSize = comp.props.hasOwnProperty('iconSize')
  const hasIconWidth = comp.props.hasOwnProperty('iconWidth')
  const hasIconHeight = comp.props.hasOwnProperty('iconHeight')
  
  // 确定是否需要使用scale
  const useScale = !hasIconSize || (hasIconWidth || hasIconHeight)
  const transform = useScale 
    ? `rotate(${comp.rotation || 0}deg) scale(${comp.scale || 1})`
    : `rotate(${comp.rotation || 0}deg)`
  
  return {
    position: 'absolute',
    left: `${comp.position.x}px`,
    top: `${comp.position.y}px`,
    transform: transform,
    border: selectedComponent.value?.id === comp.id ? '2px solid #409EFF' : '1px solid #ccc',
    cursor: 'move',
    boxSizing: 'border-box',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    background: 'transparent',
    transformOrigin: 'center center'
  }
}

// 选中组件
const selectComponent = (comp) => {
  selectedComponent.value = comp
}

// 清除选择
const clearSelection = () => {
  selectedComponent.value = null
}

// 拖动组件
const startDrag = (comp, event) => {
  if (resizing || rotating) return
  dragOffset = {
    x: event.clientX - comp.position.x,
    y: event.clientY - comp.position.y
  }
  const onMouseMove = (e) => {
    comp.position.x = e.clientX - dragOffset.x
    comp.position.y = e.clientY - dragOffset.y
  }
  const onMouseUp = () => {
    window.removeEventListener('mousemove', onMouseMove)
    window.removeEventListener('mouseup', onMouseUp)
  }
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
}

// 旋转组件
const startRotate = (comp, event) => {
  rotating = true
  rotatingComponent = comp
  const rect = canvasRef.value.getBoundingClientRect()
  
  // 计算组件中心点
  const hasIconSize = comp.props.hasOwnProperty('iconSize')
  const hasIconWidth = comp.props.hasOwnProperty('iconWidth')
  const hasIconHeight = comp.props.hasOwnProperty('iconHeight')
  
  // 确定组件尺寸
  let componentSize = 100
  if (hasIconWidth && hasIconHeight) {
    componentSize = Math.max(comp.props.iconWidth || 100, comp.props.iconHeight || 100)
  } else if (hasIconSize) {
    componentSize = comp.props.iconSize || 100
  }
  
  const scale = comp.scale || 1
  const actualSize = componentSize * scale
  
  const centerX = comp.position.x + actualSize / 2
  const centerY = comp.position.y + actualSize / 2
  const startAngle = Math.atan2(event.clientY - centerY, event.clientX - centerX)
  
  const onMouseMove = (e) => {
    const angle = Math.atan2(e.clientY - centerY, e.clientX - centerX)
    let rotation = ((angle - startAngle) * 180 / Math.PI) + (comp.rotation || 0)
    
    // 将旋转角度限制在0-360度范围内
    rotation = rotation % 360
    if (rotation < 0) {
      rotation += 360
    }
    
    comp.rotation = rotation
  }
  const onMouseUp = () => {
    rotating = false
    rotatingComponent = null
    window.removeEventListener('mousemove', onMouseMove)
    window.removeEventListener('mouseup', onMouseUp)
  }
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
}

// 尺寸调整 - 支持多种缩放模式
const startResize = (comp, event, direction) => {
  resizing = true
  resizingComponent = comp
  const startX = event.clientX
  const startY = event.clientY
  
  // 检查组件的缩放模式
  const hasIconSize = comp.props.hasOwnProperty('iconSize')
  const hasIconWidth = comp.props.hasOwnProperty('iconWidth')
  const hasIconHeight = comp.props.hasOwnProperty('iconHeight')
  
  // 确定缩放模式
  let scaleMode = 'scale' // 默认使用scale
  if (hasIconSize && !hasIconWidth && !hasIconHeight) {
    scaleMode = 'iconSize'
  } else if (hasIconWidth || hasIconHeight) {
    scaleMode = 'iconWidthHeight'
  }
  
  const startIconSize = hasIconSize ? (comp.props.iconSize || 100) : 100
  const startIconWidth = hasIconWidth ? (comp.props.iconWidth || startIconSize) : startIconSize
  const startIconHeight = hasIconHeight ? (comp.props.iconHeight || startIconSize) : startIconSize
  const startPosX = comp.position.x
  const startPosY = comp.position.y
  
  const onMouseMove = (e) => {
    const deltaX = e.clientX - startX
    const deltaY = e.clientY - startY
    const delta = Math.max(deltaX, deltaY) // 使用较大的变化量来保持比例
    
    switch (scaleMode) {
      case 'iconSize':
        // 只使用iconSize的组件
        switch (direction) {
          case 'se':
            comp.props.iconSize = Math.max(20, startIconSize + delta)
            break
          case 'sw':
            comp.props.iconSize = Math.max(20, startIconSize - delta)
            comp.position.x = startPosX + delta
            break
          case 'ne':
            comp.props.iconSize = Math.max(20, startIconSize + delta)
            comp.position.y = startPosY - delta
            break
          case 'nw':
            comp.props.iconSize = Math.max(20, startIconSize - delta)
            comp.position.x = startPosX + delta
            comp.position.y = startPosY - delta
            break
        }
        break
        
      case 'iconWidthHeight':
        // 使用iconWidth和iconHeight的组件
        const newWidth = Math.max(20, startIconWidth + delta)
        const newHeight = Math.max(20, startIconHeight + delta)
        
        if (hasIconWidth) comp.props.iconWidth = newWidth
        if (hasIconHeight) comp.props.iconHeight = newHeight
        
        // 调整位置
        switch (direction) {
          case 'sw':
            comp.position.x = startPosX + delta
            break
          case 'ne':
            comp.position.y = startPosY - delta
            break
          case 'nw':
            comp.position.x = startPosX + delta
            comp.position.y = startPosY - delta
            break
        }
        break
        
      default:
        // 使用scale的组件
        const scale = Math.max(0.1, 1 + delta / 100)
        comp.scale = scale
        break
    }
  }
  const onMouseUp = () => {
    resizing = false
    resizingComponent = null
    window.removeEventListener('mousemove', onMouseMove)
    window.removeEventListener('mouseup', onMouseUp)
  }
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
}

// 标准化旋转角度到0-360度范围
const normalizeRotation = (value) => {
  if (selectedComponent.value) {
    let rotation = value % 360
    if (rotation < 0) {
      rotation += 360
    }
    selectedComponent.value.rotation = rotation
  }
}

// 清空画布
const clearCanvas = () => {
  pageComponents.value = []
  selectedComponent.value = null
}



// 保存/导出/预览
const savePage = () => {
  // 可将 pageComponents.value 发送到后端保存
  alert('页面已保存！')
}
const exportConfig = () => {
  const config = JSON.stringify(pageComponents.value, null, 2)
  navigator.clipboard.writeText(config)
  alert('配置已复制到剪贴板')
}
const previewPage = () => {
  // 可实现预览功能
  alert('预览功能开发中')
}
</script>

<style scoped>
.page-designer {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  padding: 10px;
  background: #f5f5f5;
  border-bottom: 1px solid #eee;
}

.designer-container {
  display: flex;
  flex: 1;
  height: 0;
}

.component-library {
  width: 220px;
  background: #fafbfc;
  border-right: 1px solid #eee;
  padding: 10px;
  overflow-y: auto;
}



.category {
  margin-bottom: 20px;
}

.category h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.component-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: grab;
  transition: all 0.2s;
}

.component-item:hover {
  background: #f0f9ff;
  border-color: #409EFF;
}

.component-item:active {
  cursor: grabbing;
}

.component-item i {
  font-size: 16px;
  color: #666;
}

.component-item span {
  font-size: 12px;
  color: #333;
}

.design-canvas {
  flex: 1;
  position: relative;
  background: #fff;
  min-height: 600px;
  border: 1px solid #eee;
  overflow: hidden;
}

.canvas-component {
  position: absolute;
  background: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  border-radius: 4px;
  user-select: none;
  transition: border-color 0.2s;
}

.canvas-component.selected {
  border: 2px solid #409EFF !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.component-controls {
  position: absolute;
  top: -30px;
  left: -30px;
  right: -30px;
  bottom: -30px;
  pointer-events: none;
}

.rotate-handle {
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 20px;
  background: #67c23a;
  border: 2px solid #fff;
  border-radius: 50%;
  cursor: grab;
  pointer-events: all;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rotate-handle::before {
  content: '↻';
  color: #fff;
  font-size: 12px;
  font-weight: bold;
}

.rotate-handle:active {
  cursor: grabbing;
}

.resize-handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #409EFF;
  border: 1px solid #fff;
  border-radius: 50%;
  pointer-events: all;
}

.resize-handle.resize-se {
  right: -4px;
  bottom: -4px;
  cursor: se-resize;
}

.resize-handle.resize-sw {
  left: -4px;
  bottom: -4px;
  cursor: sw-resize;
}

.resize-handle.resize-ne {
  right: -4px;
  top: -4px;
  cursor: ne-resize;
}

.resize-handle.resize-nw {
  left: -4px;
  top: -4px;
  cursor: nw-resize;
}

.property-panel {
  width: 260px;
  background: #fafbfc;
  border-left: 1px solid #eee;
  padding: 10px;
  overflow-y: auto;
}

.property-panel h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

/* 组件库滚动条样式 */
.component-library::-webkit-scrollbar {
  width: 6px;
}

.component-library::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.component-library::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.component-library::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 属性面板滚动条样式 */
.property-panel::-webkit-scrollbar {
  width: 6px;
}

.property-panel::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.property-panel::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.property-panel::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style> 