<template>
  <div>
    <!-- 上传表单 -->
    <el-form
      :model="useOrReturnForm"
      :rules="useOrReturnFormRules"
      ref="useOrReturnFormRef"
      label-width="120px"
      v-show="!showLayerDialog"
    >
      <el-form-item label="所属项目" prop="projectId" v-show="false">
        <el-input v-model="useOrReturnForm.projectId" placeholder="请输入项目ID" />
      </el-form-item>
      <el-form-item label="模型URL" prop="modelUrl" v-show="false">
        <el-input v-model="useOrReturnForm.modelUrl" placeholder="上传后自动填充" />
      </el-form-item>
     <!-- <el-form-item label="模型名称" prop="modelName">
        <el-input v-model="useOrReturnForm.modelName" placeholder="请输入模型名称" />
      </el-form-item> -->
      <el-form-item label="模型文件" prop="files">
        <el-upload
          class="upload-demo"
          action="/dev-api/common/upload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :headers="uploadHeaders"
          :file-list="fileList"
          :limit="1"
          :auto-upload="true"
          :show-file-list="true"
          :disabled="fileList.length >= 1"
        >
          <div v-if="fileList.length < 1" class="upload-demo">
            <el-button size="small" icon="el-icon-paperclip">上传模型</el-button>
            <div class="upload-demo-tip">仅支持上传dxf文件</div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="goToNextStep" :disabled="!fileList.length">下一步</el-button>
      </el-form-item>
    </el-form>

    <!-- 图层和实体预览 -->
    <div v-if="showLayerDialog" class="layer-container">
      <div class="left-panel">
        <h3 class="panel-title">图层列表</h3>
        <el-menu
          default-active="0"
          @select="handleLayerSelect"
          :unique-opened="true"
          class="layer-menu"
          background-color="#f5f7fa"
          text-color="#606266"
          active-text-color="#409EFF"
        >
          <el-menu-item
            v-for="(layer, index) in layerList"
            :key="layer.layerName"
            :index="index.toString()"
            class="layer-menu-item"
          >
            {{ layer.layerName }} <span class="entity-count">({{ layer.entities.length }})</span>
          </el-menu-item>
        </el-menu>
      </div>

      <div class="right-panel">
        <h3 class="panel-title">图元列表</h3>
        <el-row :gutter="16" class="entity-row">
          <el-col
            v-for="(entity, i) in selectedLayerEntities"
            :key="entity.id || i"
            :span="8"
          >
            <el-card
              class="entity-card"
              :body-style="{ padding: '10px' }"
              :shadow="selectedEntities.includes(entity.id) ? 'hover' : 'never'"
              :class="{ active: selectedEntities.includes(entity.id) }"
              @click="selectEntity(entity)"
            >
              <div class="entity-info">
                <el-checkbox
                  v-model="entity.selected"
                  @click.stop
                  @change="selectEntity(entity)"
                ></el-checkbox>
				<div><strong>图层名称:</strong> {{ entity.layerName }}</div>
				<div><strong>类型:</strong> {{ entity.entityType }}</div>
				<div><strong>颜色:</strong> {{ entity.color }}</div>
				<div><strong>线宽:</strong> {{ entity.lineweight }}</div>
				<div><strong>厚度:</strong> {{ entity.thickness }}</div>
				<div><strong>起点:</strong> {{ entity.startPoint || '无' }}</div>
				<div><strong>终点:</strong> {{ entity.endPoint || '无' }}</div>
				<div><strong>中心点:</strong> {{ entity.centerPoint || '无' }}</div>
				<div><strong>半径:</strong> {{ entity.radius === null ? '无' : entity.radius }}</div>
				<div><strong>Points:</strong> {{ entity.points || '无' }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 图元预览 -->
        <div class="preview-container">
          <div class="preview-header">
            <h4>图元预览 ({{ previewEntities.length }})</h4>
            <div class="zoom-controls">
              <el-button size="small" @click="zoomOut" icon="el-icon-minus" circle></el-button>
              <span>{{ Math.round(zoomLevel * 100) }}%</span>
              <el-button size="small" @click="zoomIn" icon="el-icon-plus" circle></el-button>
              <el-button size="small" @click="fitToView">适应视图</el-button>
            </div>
          </div>
          <div class="preview-wrapper" ref="previewWrapper">
            <svg 
              class="preview-svg" 
              :width="svgSize" 
              :height="svgSize"
              @mousedown="startPan"
              @mousemove="pan"
              @mouseup="endPan"
              @mouseleave="endPan"
              @wheel="handleWheel"
            >
              <!-- 背景网格 -->
              <pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
                <path d="M 50 0 L 0 0 0 50" fill="none" stroke="#e0e0e0" stroke-width="0.5"/>
              </pattern>
              <rect width="100%" height="100%" fill="url(#grid)" />
              
              <!-- 坐标轴 -->
              <line x1="0" :y1="originY" x2="100%" :y2="originY" stroke="#999" stroke-width="1" stroke-dasharray="5,5" />
              <line :x1="originX" y1="0" :x2="originX" y2="100%" stroke="#999" stroke-width="1" stroke-dasharray="5,5" />
              
              <!-- 绘制图元 -->
              <g :transform="`scale(${zoomLevel}) translate(${panX}, ${panY})`">
                <!-- 圆 -->
                <circle 
                  v-for="(entity, index) in previewEntities" 
                  v-if="entity.entityType === 'CIRCLE'" 
                  :key="index"
                  :cx="entity.centerPoint.x" 
                  :cy="entity.centerPoint.y" 
                  :r="entity.radius" 
                  :fill="entity.color || '#409EFF'"
                  :stroke="entity.color || '#409EFF'"
                  stroke-width="1"
                  fill="none"
                />
                
                <!-- 直线 -->
                <line 
                  v-for="(entity, index) in previewEntities" 
                  v-if="entity.entityType === 'LINE'" 
                  :key="index"
                  :x1="entity.startPoint.x" 
                  :y1="entity.startPoint.y" 
                  :x2="entity.endPoint.x" 
                  :y2="entity.endPoint.y" 
                  :stroke="entity.color || '#409EFF'"
                  :stroke-width="entity.lineweight || 1"
                />
                
                <!-- 多段线 -->
                <polyline 
                  v-for="(entity, index) in previewEntities" 
                  v-if="entity.entityType === 'LWPOLYLINE' && entity.points" 
                  :key="index"
                  :points="getPolylinePoints(entity)" 
                  :stroke="entity.color || '#409EFF'"
                  :stroke-width="entity.lineweight || 1"
                  fill="none"
                />
                
                <!-- 点 -->
                <circle 
                  v-for="(entity, index) in previewEntities" 
                  v-if="entity.entityType === 'POINT'" 
                  :key="index"
                  :cx="entity.position.x" 
                  :cy="entity.position.y" 
                  r="2" 
                  :fill="entity.color || '#409EFF'"
                />
              </g>
              
              <!-- 原点标记 -->
              <circle :cx="originX" :cy="originY" r="3" fill="#f56c6c" />
              <text :x="originX + 5" :y="originY - 5" fill="#f56c6c" font-size="12">(0,0)</text>
            </svg>
          </div>
          
          <!-- 坐标指示器 -->
          <div class="coordinate-indicator">
            <span>当前视图: X:{{ viewBox.x.toFixed(2) }}, Y:{{ viewBox.y.toFixed(2) }}</span>
            <span>缩放: {{ Math.round(zoomLevel * 100) }}%</span>
          </div>
        </div>

        <div class="layer-footer">
          <el-button @click="showLayerDialog = false">上一步</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            :disabled="!selectedEntities.length"
          >
            提交 (已选择 {{ selectedEntities.length }} 个图元)
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addModel } from '@/api/basic/model'

export default {
  name: 'UseOrReturnForm',
  props: {
    projectId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      useOrReturnForm: {
        modelName: '',
        modelType: '',
        version: '',
        designer: '',
        user: '',
        files: [],
        modelUrl: '',
        projectId: ''
      },
      useOrReturnFormRules: {
        files: [{ required: true, message: '请上传模型文件', trigger: 'change' }]
      },
      fileList: [],
      showLayerDialog: false,
      layerList: [],
      selectedLayerEntities: [],
      selectedLayerIndex: 0,
      selectedEntities: [],
      cadData: [],
      svgSize: 400,
      zoomLevel: 1,
      panning: false,
      panStartX: 0,
      panStartY: 0,
      panX: 0,
      panY: 0,
      originX: 200,
      originY: 200,
      viewBox: { x: 0, y: 0 }
    }
  },
  computed: {
    uploadHeaders() {
      return {
        Authorization: 'Bearer ' + getToken()
      }
    },
    previewEntities() {
      return this.getAllSelectedEntities();
    }
  },
  mounted() {
    this.useOrReturnForm.projectId = this.projectId;
    window.addEventListener('resize', this.adjustSVGSize);
    this.adjustSVGSize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.adjustSVGSize);
  },
  methods: {
    adjustSVGSize() {
      if (this.$refs.previewWrapper) {
        const width = this.$refs.previewWrapper.clientWidth;
        this.svgSize = Math.min(600, Math.max(400, width - 40));
      }
    },
    
    getAllSelectedEntities() {
      const allEntities = [];
      this.layerList.forEach(layer => {
        layer.entities.forEach(entity => {
          if (this.selectedEntities.includes(entity.id)) {
            allEntities.push(entity);
          }
        });
      });
      return allEntities;
    },
    
    getPolylinePoints(entity) {
      if (!entity.points || !Array.isArray(entity.points)) return '';
      return entity.points.map(point => {
        return `${point.x},${point.y}`;
      }).join(' ');
    },
    
    zoomIn() {
      this.zoomLevel = Math.min(5, this.zoomLevel + 0.1);
    },
    
    zoomOut() {
      this.zoomLevel = Math.max(0.1, this.zoomLevel - 0.1);
    },
    
    handleWheel(event) {
      event.preventDefault();
      const delta = Math.sign(event.deltaY);
      if (delta > 0) {
        this.zoomOut();
      } else {
        this.zoomIn();
      }
    },
    
    fitToView() {
      this.zoomLevel = 1;
      this.panX = 0;
      this.panY = 0;
      this.viewBox = { x: 0, y: 0 };
    },
    
    startPan(event) {
      this.panning = true;
      this.panStartX = event.clientX;
      this.panStartY = event.clientY;
    },
    
    pan(event) {
      if (!this.panning) return;
      const dx = event.clientX - this.panStartX;
      const dy = event.clientY - this.panStartY;
      this.panX += dx / this.zoomLevel;
      this.panY += dy / this.zoomLevel;
      this.panStartX = event.clientX;
      this.panStartY = event.clientY;
      this.viewBox.x = -this.panX;
      this.viewBox.y = -this.panY;
    },
    
    endPan() {
      this.panning = false;
    },

    cancel() {
      this.$emit('closeUseOrReturnFormDialog')
    },

    goToNextStep() {
      this.showLayerDialog = true

      if (!this.cadData || !this.cadData.length) {
        this.$message.error('无效的CAD数据，无法进入下一步')
        return
      }

      const map = {}
      this.cadData.forEach((entity) => {
        if (!map[entity.layerName]) {
          map[entity.layerName] = { layerName: entity.layerName, entities: [] }
        }
        if (!entity.id) {
          entity.id = entity.layerName + '_' + Math.random().toString(36).substr(2, 9)
        }
        map[entity.layerName].entities.push(entity)
      })

      this.layerList = Object.values(map)
      this.selectedLayerIndex = 0
      this.selectedLayerEntities = this.layerList[0].entities || []
      this.selectedEntities = []
    },

    handleLayerSelect(index) {
      this.selectedLayerIndex = parseInt(index)
      this.selectedLayerEntities = this.layerList[this.selectedLayerIndex].entities
    },

    selectEntity(entity) {
      entity.selected = !entity.selected;
      const idx = this.selectedEntities.indexOf(entity.id)
	  console.log(JSON.stringify(this.selectedEntities))
      if (entity.selected) {
        if (idx === -1) this.selectedEntities.push(entity.id)
      } else {
        if (idx !== -1) this.selectedEntities.splice(idx, 1)
      }
    },

    async submitForm() {
      this.$refs.useOrReturnFormRef.validate(async (valid) => {
        if (!valid) return
		  const selectedEntities = [];
		  
		  this.layerList.forEach(layer => {
		    layer.entities.forEach(entity => {
		      if (entity.selected) {
		        selectedEntities.push({
		          entityId: entity.entityId || entity.id || '',         
		          entityType: entity.entityType || '',
		          color: entity.color || '',
		          lineweight: entity.lineweight || '',
		          thickness: entity.thickness || '',
		          startPoint: entity.startPoint || null,
		          endPoint: entity.endPoint || null,
		          centerPoint: entity.centerPoint || null,
		          radius: entity.radius != null ? entity.radius : null,
		         // points: entity.points || [],
		          geometry: entity.geometry || {},  // 你如果还有geometry字段也保留
		          layerName: layer.layerName || ''
		        });
		      }
		    });
		  });

		const formData = {
		  projectId: this.useOrReturnForm.projectId,
		  modelName: this.useOrReturnForm.modelName,
		  modelUrl: this.useOrReturnForm.modelUrl,
		  fileName: this.useOrReturnForm.fileName,
		  version: this.useOrReturnForm.version,
		  designer: this.useOrReturnForm.designer,
		  designerName: this.useOrReturnForm.designerName,
		  remark: this.useOrReturnForm.remark,
		  modelType: this.useOrReturnForm.modelType,
		  modelIds: this.useOrReturnForm.modelIds,
		  createBy: this.useOrReturnForm.createBy,
		  createTime: this.useOrReturnForm.createTime,
		  selectedEntities: selectedEntities
		};

        try {
          const res = await addModel(formData)
          if (res.code === 200) {
            this.$modal.msgSuccess('模型添加成功')
            this.$emit('closeUseOrReturnFormDialog')
            this.$emit('refreshParentList')
            this.resetForm()
          } else {
            this.$modal.msgError(res.msg || '提交失败')
          }
        } catch (error) {
          this.$modal.msgError('提交异常: ' + error.message)
        }
      })
    },

    resetForm() {
      this.$refs.useOrReturnFormRef.resetFields()
      this.fileList = []
      this.useOrReturnForm.files = []
      this.selectedEntities = []
      this.showLayerDialog = false
      this.fitToView()
    },

    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.cadData = response.cadData || []
        const uploaded = response.data || {
          name: file.name,
          url: response.fileUrl || response.url,
          uid: file.uid
        }
        this.fileList = fileList
        this.useOrReturnForm.files = [uploaded]
        this.useOrReturnForm.modelUrl = uploaded.url
        this.$refs.useOrReturnFormRef.validateField('files')
      } else {
        this.$message.error(response.msg || '文件上传失败')
        this.handleRemove(file)
      }
    },

    handleRemove(file, fileList) {
      this.fileList = fileList
      this.useOrReturnForm.files = []
      this.useOrReturnForm.modelUrl = ''
      this.cadData = []
      this.$refs.useOrReturnFormRef.validateField('files')
    },

    beforeUpload(file) {
      const isDxf = file.name.toLowerCase().endsWith('.dxf')
      if (!isDxf) this.$message.error('只能上传DXF格式的文件!')
      return isDxf
    }
  }
}
</script>

<style scoped>
.upload-demo {
  display: flex;
  align-items: center;
}
.upload-demo-tip {
  margin-left: 10px;
  color: #f56c6c;
}

.layer-container {
  display: flex;
  height: 650px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
  background-color: #fff;
}

.left-panel {
  width: 260px;
  background: #f7f9fc;
  border-right: 1px solid #dcdfe6;
  padding: 20px 15px;
  overflow-y: auto;
}

.panel-title {
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 6px;
}

.layer-menu {
  background: transparent;
  border: none;
}

.layer-menu-item {
  font-size: 15px;
  padding: 8px 15px !important;
  display: flex;
  justify-content: space-between;
  color: #606266;
  cursor: pointer;
}

.layer-menu-item:hover {
  background-color: #e6f2ff;
  color: #409EFF;
}

.el-menu-item.is-active {
  background-color: #409EFF !important;
  color: #fff !important;
  font-weight: 600;
}

.entity-count {
  color: #909399;
  font-weight: 400;
}

.right-panel {
  flex: 1;
  padding: 20px 25px;
  background: #fff;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.entity-row {
  margin-bottom: 15px;
  flex-wrap: wrap;
  display: flex;
  gap: 15px;
}

.entity-card {
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 0.05);
  width: 30%;
  min-width: 200px;
}

.entity-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.entity-card.active {
  border: 2px solid #409EFF;
  background-color: #f0f7ff;
}

.entity-info {
  font-size: 13px;
  color: #4a4a4a;
}

.entity-info div {
  margin-bottom: 4px;
  line-height: 1.3;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.preview-container {
  margin-top: 20px;
  padding: 15px;
  background: #f8fafc;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.zoom-controls span {
  min-width: 50px;
  text-align: center;
  font-size: 14px;
}

.preview-wrapper {
  height: 300px;
  width: 100%;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.preview-svg {
  width: 100%;
  height: 100%;
  background: #f9f9f9;
  cursor: move;
}

.coordinate-indicator {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.layer-footer {
  text-align: right;
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.layer-footer button {
  min-width: 100px;
  margin-left: 15px;
  font-weight: 600;
}
</style>