<template>
  <div class="electronic-fence-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">电子围栏</h2>
      <p class="page-description">点击地图绘制围栏区域，最少需要三个点</p>
    </div>

    <!-- 地图容器 -->
    <div class="map-section">
      <!-- 绘制控制面板 -->
      <div class="drawing-controls">
        <div class="control-group">
          <a-button 
            type="primary" 
            :disabled="drawingState.isDrawing"
            @click="startDrawing"
            class="control-btn"
          >
            <template #icon>
              <EditOutlined />
            </template>
            开始绘制
          </a-button>
          
          <a-button 
            type="default" 
            :disabled="!drawingState.isDrawing || drawingState.currentPoints.length < 3"
            @click="completeDrawing"
            class="control-btn"
          >
            <template #icon>
              <CheckOutlined />
            </template>
            完成绘制
          </a-button>
          
          <a-button 
            type="default" 
            :disabled="!drawingState.isDrawing"
            @click="cancelDrawing"
            class="control-btn"
          >
            <template #icon>
              <CloseOutlined />
            </template>
            取消绘制
          </a-button>
        </div>
        
        <div class="drawing-status" v-if="drawingState.isDrawing">
          <a-alert 
            :message="getDrawingStatusMessage()"
            :type="getDrawingStatusType()"
            show-icon
          >
            <template #description>
              <div v-if="drawingState.currentPoints.length > 0">
                <p>围栏坐标点顺序：</p>
                <div class="point-sequence">
                  <a-tag 
                    v-for="(point, index) in drawingState.currentPoints" 
                    :key="point.id"
                    :color="index < 3 ? 'blue' : 'green'"
                    class="point-tag"
                  >
                    点{{ index + 1 }}: ({{ point.lng.toFixed(6) }}, {{ point.lat.toFixed(6) }})
                  </a-tag>
                </div>
              </div>
            </template>
          </a-alert>
        </div>
      </div>

      <!-- 围栏信息面板 -->
      <div class="fence-info-panel" v-if="selectedFence">
        <div class="panel-header">
          <h3>围栏信息</h3>
          <a-button type="text" @click="closeFenceInfo">
            <CloseOutlined />
          </a-button>
        </div>
        <div class="panel-content">
          <div class="info-item">
            <span class="label">围栏名称:</span>
            <span class="value">{{ selectedFence.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">围栏类型:</span>
            <span class="value">{{ getFenceTypeText(selectedFence.type) }}</span>
          </div>
          <div class="info-item">
            <span class="label">坐标点数量:</span>
            <span class="value">{{ selectedFence.coordinates?.length || 0 }}</span>
          </div>
          <!-- <div class="info-item">
            <span class="label">围栏面积:</span>
            <span class="value">{{ selectedFence.area ? (typeof selectedFence.area === 'number' ? selectedFence.area.toFixed(2) : selectedFence.area) + ' 平方米' : '未知' }}</span>
          </div> -->
        </div>
      </div>

      <!-- 围栏选择面板 -->
      <div class="fence-selector-panel">
        <div class="panel-header">
          <h3>围栏列表</h3>
        </div>
        <div class="panel-content">
          <div class="search-section">
            <a-input
              v-model="searchValue"
              placeholder="搜索围栏名称或描述"
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
            <a-select
              v-model="selectedFenceName"
              placeholder="选择围栏名称"
              class="fence-name-select"
              @change="handleFenceNameSelect"
              allowClear
              show-search
              :filter-option="filterFenceNameOption"
              :loading="fenceNamesLoading"
            >
              <a-select-option 
                v-for="fence in fenceList" 
                :key="fence.id" 
                :value="fence.name"
              >
                {{ fence.name }}
              </a-select-option>
            </a-select>

            <a-button 
              type="default" 
              @click="clearAllSearch"
              class="clear-search-btn"
              :disabled="!searchValue && !selectedFenceName && !searchType"
            >
              清除搜索
            </a-button>
          </div>
          <div class="fence-stats">
            <a-statistic 
              title="围栏总数" 
              :value="fenceList.length" 
              :value-style="{ fontSize: '16px' }"
            />
            <a-statistic 
              title="搜索结果" 
              :value="filteredFenceList.length" 
              :value-style="{ fontSize: '16px' }"
            />
          </div>
          <a-list
            :data-source="filteredFenceList"
            class="fence-list"
            size="small"
            :loading="loading"
          >
            <template #renderItem="{ item }">
              <a-list-item 
                @click="handleFenceItemClick(item, $event)"
                :class="{ 'selected': selectedFence?.id === item.id }"
                class="fence-item"
              >
                <a-list-item-meta>
                  <template #title>
                    <span class="fence-name">{{ item.name }}</span>
                    <a-tag :color="getFenceTypeColor(item.type)" class="fence-type-tag">
                      {{ getFenceTypeText(item.type) }}
                    </a-tag>
                  </template>
                  <template #description>
                    <span class="fence-description">{{ item.description || '无描述' }}</span>
                    <br>
                    <span class="fence-coords">{{ item.coordinates?.length || 0 }} 个坐标点</span>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-tooltip title="编辑围栏">
                    <a-button 
                      type="text" 
                      size="small" 
                      @click.stop.prevent="editFence(item)"
                      class="edit-btn"
                    >
                      <EditOutlined />
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="删除围栏">
                    <a-button 
                      type="text" 
                      size="small" 
                      danger 
                      @click.stop.prevent="deleteFence(item)"
                      class="delete-btn"
                    >
                      <DeleteOutlined />
                    </a-button>
                  </a-tooltip>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>

      <!-- 百度地图组件 -->
      <div class="map-wrapper">
        <BaiduMap
          :options="mapOptions"
          @map-ready="onMapReady"
          @map-click="onMapClick"
          class="baidu-map"
        />
      </div>
    </div>

    <!-- 围栏编辑模态框 -->
    <a-modal
      :open="fenceModalVisible"
      @update:open="(val) => fenceModalVisible = val"
      :title="editingFence ? '编辑围栏' : '新建围栏'"
      @ok="handleFenceSubmit"
      @cancel="handleFenceCancel"
      :confirm-loading="submitting"
    >
      <a-form :model="fenceForm" layout="vertical">
        <a-form-item label="围栏名称" required>
          <a-input 
            :value="fenceForm.name"
            @input="handleNameInput"
            @change="handleNameChange"
            placeholder="请输入围栏名称" 
          />
        </a-form-item>
        <a-form-item label="围栏类型" required>
          <a-select v-model="fenceForm.type" placeholder="请选择围栏类型">
            <a-select-option value="grazing">
              <span style="color: #52c41a;">🌿 放牧区</span>
            </a-select-option>
            <a-select-option value="safety">
              <span style="color: #1890ff;">🛡️ 安全区</span>
            </a-select-option>
            <a-select-option value="restricted">
              <span style="color: #ff4d4f;">⚠️ 限制区</span>
            </a-select-option>
            <a-select-option value="collector">
              <span style="color: #fa8c16;">📦 收集区</span>
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="围栏描述">
          <a-textarea v-model="fenceForm.description" placeholder="请输入围栏描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { EditOutlined, CheckOutlined, CloseOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons-vue'
import BaiduMap from '@/components/BaiduMap.vue'
import { api } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const fenceModalVisible = ref(false)
const searchValue = ref('')
const searchType = ref('')
const selectedFenceName = ref('')
const fenceNamesLoading = ref(false)
const selectedFence = ref(null)
const editingFence = ref(null)

// 绘制状态
const drawingState = reactive({
  isDrawing: false,
  isCompleted: false,
  currentPoints: [],
  tempPolygon: null,
  tempMarkers: []
})

// 围栏列表
const fenceList = ref([])

// 地图配置
const mapOptions = reactive({
  center: { lng: 106.27, lat: 38.47 }, // 宁夏中心坐标
  zoom: 8, // 适合宁夏全区域的缩放级别
  enableScrollWheelZoom: true,
  enableDoubleClickZoom: true,
  enableKeyboard: true,
  enableDragging: true,
  enableMapClick: true
})

// 围栏表单
const fenceForm = reactive({
  name: '',
  type: 'grazing',
  description: ''
})

// 地图实例
let baiduMap = null
let allPolygons = []
let allMarkers = []

// 计算属性
const filteredFenceList = computed(() => {
  let filtered = fenceList.value
  
  // 按围栏名称选择过滤
  if (selectedFenceName.value) {
    filtered = filtered.filter(fence => fence.name === selectedFenceName.value)
  }
  
  // 按名称和描述搜索（当没有选择具体围栏名称时）
  if (searchValue.value && !selectedFenceName.value) {
    const searchLower = searchValue.value.toLowerCase()
    filtered = filtered.filter(fence => 
      fence.name.toLowerCase().includes(searchLower) ||
      fence.description?.toLowerCase().includes(searchLower) ||
      fence.type.toLowerCase().includes(searchLower)
    )
  }
  
  // 按类型过滤
  if (searchType.value) {
    filtered = filtered.filter(fence => fence.type === searchType.value)
  }
  
  return filtered
})

// 围栏类型文本映射
const fenceTypeMap = {
  grazing: '放牧区',
  safety: '安全区',
  restricted: '限制区',
  collector: '收集区'
}

// 围栏类型颜色映射
const fenceTypeColors = {
  grazing: 'green',
  safety: 'blue',
  restricted: 'red',
  collector: 'orange'
}

// 获取围栏类型文本
const getFenceTypeText = (type) => {
  return fenceTypeMap[type] || type
}

// 获取围栏类型颜色
const getFenceTypeColor = (type) => {
  return fenceTypeColors[type] || 'default'
}

// 获取绘制状态消息
const getDrawingStatusMessage = () => {
  const pointCount = drawingState.currentPoints.length
  if (pointCount === 0) {
    return '请在地图上点击开始绘制围栏'
  } else if (pointCount < 3) {
    const remaining = 3 - pointCount
    return `已点击 ${pointCount} 个点，还需要 ${remaining} 个点才能完成绘制`
  } else {
    return `已点击 ${pointCount} 个点，可以完成绘制`
  }
}

// 获取绘制状态类型
const getDrawingStatusType = () => {
  const pointCount = drawingState.currentPoints.length
  if (pointCount === 0) {
    return 'info'
  } else if (pointCount < 3) {
    return 'warning'
  } else {
    return 'success'
  }
}

// 地图准备就绪
const onMapReady = (map) => {
  console.log('地图准备就绪')
  baiduMap = map
  
  // 设置地图中心为宁夏区域
  const ningxiaCenter = new BMap.Point(106.27, 38.47) // 宁夏中心坐标
  baiduMap.centerAndZoom(ningxiaCenter, 8) // 设置中心点和缩放级别
  
  // 监听地图加载完成事件
  baiduMap.addEventListener('tilesloaded', () => {
    console.log('地图瓦片加载完成，开始加载围栏数据')
    loadFenceData()
  })
  
  // 备用加载方案
  setTimeout(() => {
    if (baiduMap && fenceList.value.length === 0) {
      console.log('备用方案：延时加载围栏数据')
      loadFenceData()
    }
  }, 2000)
  
  console.log('地图初始化完成，中心点设置为宁夏区域:', ningxiaCenter)
}

// 地图点击事件
const onMapClick = (e) => {
  if (!drawingState.isDrawing) return
  
  const point = {
    lng: e.lnglat.lng,
    lat: e.lnglat.lat,
    id: Date.now() + Math.random(),
    order: drawingState.currentPoints.length // 添加顺序标识
  }
  
  drawingState.currentPoints.push(point)
  
  // 添加临时标记
  addTempMarker(point)
  
  // 更新临时多边形
  updateTempPolygon()
  
  console.log('点击坐标:', point)
  console.log('当前点数:', drawingState.currentPoints.length)
  console.log('围栏点顺序:', drawingState.currentPoints.map((p, index) => 
    `点${index + 1}(${p.lng.toFixed(6)}, ${p.lat.toFixed(6)})`
  ).join(' → '))
}

// 开始绘制
const startDrawing = () => {
  drawingState.isDrawing = true
  drawingState.isCompleted = false
  drawingState.currentPoints = []
  clearTempOverlays()
  
  message.info('请在地图上点击绘制围栏，最少需要3个点')
}

// 完成绘制
const completeDrawing = async () => {
  const pointCount = drawingState.currentPoints.length
  
  // 详细验证点数
  if (pointCount < 3) {
    const remainingPoints = 3 - pointCount
    message.warning({
      content: `围栏绘制不完整！当前只有 ${pointCount} 个点，还需要 ${remainingPoints} 个点才能完成绘制。请继续在地图上点击添加坐标点。`,
      duration: 5
    })
    return
  }
  
  // 验证围栏是否有效（检查面积是否过小）
  const area = calculatePolygonArea(drawingState.currentPoints)
  if (area < 100) { // 面积小于100平方米
    message.warning({
      content: `围栏面积过小（${area.toFixed(2)}平方米），建议重新绘制一个更大的区域。`,
      duration: 5
    })
    return
  }
  
  try {
    // 显示围栏信息摘要
    const center = calculatePolygonCenter(drawingState.currentPoints)
    console.log('围栏绘制完成:', {
      点数: pointCount,
      中心点: center,
      面积: area.toFixed(2) + '平方米',
      坐标点: drawingState.currentPoints
    })
    
    // 打开围栏信息编辑模态框
    editingFence.value = null
    Object.assign(fenceForm, {
      name: `围栏_${new Date().getTime()}`,
      type: 'grazing',
      description: `包含${pointCount}个坐标点的围栏区域，面积约${area.toFixed(2)}平方米`
    })
    fenceModalVisible.value = true
    
    drawingState.isCompleted = true
    message.success({
      content: `围栏绘制完成！共${pointCount}个坐标点，面积约${area.toFixed(2)}平方米。请填写围栏信息。`,
      duration: 3
    })
  } catch (error) {
    console.error('完成绘制失败:', error)
    message.error('完成绘制失败: ' + error.message)
  }
}

// 取消绘制
const cancelDrawing = () => {
  drawingState.isDrawing = false
  drawingState.isCompleted = false
  drawingState.currentPoints = []
  clearTempOverlays()
  
  message.info('已取消绘制')
}

// 添加临时标记
const addTempMarker = (point) => {
  if (!baiduMap) return
  
  const marker = new BMap.Marker(new BMap.Point(point.lng, point.lat))
  const pointNumber = drawingState.currentPoints.length
  marker.setLabel(new BMap.Label(`${pointNumber}`, {
    offset: new BMap.Size(0, -30),
    style: {
      color: '#fff',
      backgroundColor: '#1890ff',
      border: '1px solid #fff',
      borderRadius: '50%',
      padding: '2px 6px',
      fontSize: '12px',
      fontWeight: 'bold'
    }
  }))
  
  // 添加点击事件，显示坐标信息
  marker.addEventListener('click', () => {
    console.log(`点击了第${pointNumber}个点:`, point)
  })
  
  baiduMap.addOverlay(marker)
  drawingState.tempMarkers.push(marker)
}

// 更新临时多边形
const updateTempPolygon = () => {
  if (drawingState.currentPoints.length < 2) return
  
  // 清除之前的临时多边形
  if (drawingState.tempPolygon) {
    baiduMap.removeOverlay(drawingState.tempPolygon)
  }
  
  // 创建新的临时多边形 - 按顺序连接点
  const points = drawingState.currentPoints.map(p => new BMap.Point(p.lng, p.lat))
  
  // 根据点数设置不同的样式
  const pointCount = drawingState.currentPoints.length
  const isComplete = pointCount >= 3
  
  const polygon = new BMap.Polygon(points, {
    strokeColor: isComplete ? '#52c41a' : '#ff4d4f', // 完成时绿色，未完成时红色
    strokeWeight: 3,
    strokeOpacity: 0.8,
    fillColor: isComplete ? '#52c41a' : '#ff4d4f',
    fillOpacity: 0.1,
    strokeStyle: 'solid'
  })
  
  // 添加点击事件
  polygon.addEventListener('click', () => {
    console.log('点击了围栏区域，当前点数:', pointCount)
    console.log('围栏坐标点:', drawingState.currentPoints)
  })
  
  baiduMap.addOverlay(polygon)
  drawingState.tempPolygon = polygon
  
  // 添加连接线（如果点数大于2）
  if (pointCount > 2) {
    addConnectionLines()
  }
}

// 添加连接线显示点的连接顺序
const addConnectionLines = () => {
  if (drawingState.currentPoints.length < 3) return
  
  // 清除之前的连接线
  drawingState.tempMarkers.forEach(marker => {
    if (marker.connectionLine) {
      baiduMap.removeOverlay(marker.connectionLine)
    }
  })
  
  // 为每个点添加连接线到下一个点
  drawingState.currentPoints.forEach((point, index) => {
    if (index < drawingState.currentPoints.length - 1) {
      const nextPoint = drawingState.currentPoints[index + 1]
      const line = new BMap.Polyline([
        new BMap.Point(point.lng, point.lat),
        new BMap.Point(nextPoint.lng, nextPoint.lat)
      ], {
        strokeColor: '#1890ff',
        strokeWeight: 2,
        strokeOpacity: 0.6,
        strokeStyle: 'dashed'
      })
      
      baiduMap.addOverlay(line)
      // 将连接线存储到标记中
      if (drawingState.tempMarkers[index]) {
        drawingState.tempMarkers[index].connectionLine = line
      }
    }
  })
}

// 清除临时覆盖物
const clearTempOverlays = () => {
  if (!baiduMap) return
  
  // 清除临时标记
  drawingState.tempMarkers.forEach(marker => {
    baiduMap.removeOverlay(marker)
  })
  drawingState.tempMarkers = []
  
  // 清除临时多边形
  if (drawingState.tempPolygon) {
    baiduMap.removeOverlay(drawingState.tempPolygon)
    drawingState.tempPolygon = null
  }
}

// 处理围栏提交
const handleFenceSubmit = async () => {
  if (!fenceForm.name.trim()) {
    message.error('请输入围栏名称')
    return
  }
  
  if (!fenceForm.type) {
    message.error('请选择围栏类型')
    return
  }
  
  try {
    submitting.value = true
    console.log('=== 开始提交围栏数据 ===')
    console.log('当前fenceForm状态:', fenceForm)
    console.log('fenceForm.name:', fenceForm.name)
    console.log('fenceForm.type:', fenceForm.type)
    console.log('fenceForm.description:', fenceForm.description)
    
    if (editingFence.value) {
      // 编辑模式：只更新name和type字段
      console.log('=== 编辑模式：准备更新围栏数据 ===')
      console.log('editingFence.value:', editingFence.value)
      
      const updateData = {
        name: fenceForm.name.trim(),
        type: fenceForm.type,
        description: fenceForm.description?.trim() || ''
      }
      
      console.log('=== 提交的更新数据 ===')
      console.log('updateData:', updateData)
      console.log('围栏ID:', editingFence.value.id)
      
      const result = await api.electronicFence.updateFence(editingFence.value.id, updateData)
      
      if (result) {
        console.log('围栏数据更新成功:', result)
        message.success('围栏信息更新成功')
        
        // 重置编辑状态
        editingFence.value = null
        fenceModalVisible.value = false
        
        // 重新加载数据
        await loadFenceData()
      } else {
        console.error('更新围栏失败：返回数据格式错误')
        message.error('更新围栏失败：返回数据格式错误')
      }
    } else {
      // 创建模式：需要坐标点数据
      console.log('创建模式：准备创建新围栏')
      if (drawingState.currentPoints.length < 3) {
        message.error('至少需要3个点才能创建围栏')
        return
      }
      
      // 计算围栏中心点和面积
      const center = calculatePolygonCenter(drawingState.currentPoints)
      const area = calculatePolygonArea(drawingState.currentPoints)
      
      // 创建围栏数据
      const fenceData = {
        name: fenceForm.name.trim(),
        type: fenceForm.type,
        description: fenceForm.description?.trim() || '',
        coordinates: drawingState.currentPoints,
        center_lng: center.lng,
        center_lat: center.lat,
        area: area,
        farm_id: 1, // 默认农场ID
        is_active: true
      }
      
      console.log('提交的创建数据:', fenceData)
      // 保存围栏
      const result = await api.electronicFence.createFence(fenceData)
      
      if (result && result.data && result.data.id) {
        // 保存坐标点
        const pointsData = drawingState.currentPoints.map((point, index) => ({
          lng: point.lng,
          lat: point.lat,
          type: 'corner',
          description: `围栏点${index + 1}`
        }))
        
        try {
          await api.electronicFencePoints.createPoints({
            fence_id: result.data.id,
            points: pointsData
          })
          console.log('坐标点创建成功')
        } catch (pointError) {
          console.error('坐标点创建失败:', pointError)
          message.warning('围栏创建成功，但坐标点保存失败: ' + pointError.message)
        }
        
        console.log('围栏创建成功:', result)
        message.success('围栏创建成功')
        
        // 重置绘制状态
        drawingState.isDrawing = false
        drawingState.isCompleted = false
        drawingState.currentPoints = []
        clearTempOverlays()
        fenceModalVisible.value = false
        
        // 重新加载数据
        await loadFenceData()
      } else {
        message.error('创建围栏失败：返回数据格式错误')
      }
    }
  } catch (error) {
    console.error('处理围栏失败:', error)
    message.error('处理围栏失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 处理围栏取消
const handleFenceCancel = () => {
  fenceModalVisible.value = false
  editingFence.value = null
  Object.assign(fenceForm, {
    name: '',
    type: 'grazing',
    description: ''
  })
}

// 计算多边形中心点
const calculatePolygonCenter = (points) => {
  if (points.length === 0) return { lng: 0, lat: 0 }
  
  let lngSum = 0
  let latSum = 0
  
  points.forEach(point => {
    lngSum += point.lng
    latSum += point.lat
  })
  
  return {
    lng: lngSum / points.length,
    lat: latSum / points.length
  }
}

// 计算多边形面积（简化计算）
const calculatePolygonArea = (points) => {
  if (points.length < 3) return 0
  
  let area = 0
  const n = points.length
  
  for (let i = 0; i < n; i++) {
    const j = (i + 1) % n
    area += points[i].lng * points[j].lat
    area -= points[j].lng * points[i].lat
  }
  
  area = Math.abs(area) / 2
  
  // 转换为平方米（粗略计算）
  return area * 111000 * 111000
}

// 加载围栏数据
const loadFenceData = async () => {
  try {
    loading.value = true
    const result = await api.electronicFence.getFences({
      page: 1,
      limit: 100
    })
    
    console.log('围栏API响应:', result)
    
    // 处理API响应格式
    if (result && result.success && Array.isArray(result.data)) {
      fenceList.value = result.data
    } else if (Array.isArray(result)) {
      // 兼容旧格式
      fenceList.value = result
    } else {
      fenceList.value = []
      console.warn('围栏API返回数据格式异常:', result)
    }
    
    console.log('围栏数据加载成功:', fenceList.value)
    
    // 在地图上显示围栏
    displayFencesOnMap()
  } catch (error) {
    console.error('加载围栏数据失败:', error)
    message.error('加载围栏数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 在地图上显示围栏
const displayFencesOnMap = async () => {
  if (!baiduMap) return
  
  // 清除现有覆盖物
  allPolygons.forEach(polygon => baiduMap.removeOverlay(polygon))
  allMarkers.forEach(marker => baiduMap.removeOverlay(marker))
  allPolygons = []
  allMarkers = []
  
  // 显示每个围栏
  for (const fence of fenceList.value) {
    try {
      // 获取围栏坐标点
      const pointsResult = await api.electronicFencePoints.getByFenceId(fence.id)
      console.log('围栏坐标点API响应:', pointsResult)
      
      // 处理API响应格式
      let points = []
      if (pointsResult && pointsResult.success && Array.isArray(pointsResult.data)) {
        points = pointsResult.data
      } else if (Array.isArray(pointsResult)) {
        // 兼容旧格式
        points = pointsResult
      } else {
        points = []
        console.warn('围栏坐标点API返回数据格式异常:', pointsResult)
      }
      
      if (points.length >= 3) {
        // 创建多边形
        const polygonPoints = points.map(p => new BMap.Point(p.lng, p.lat))
        const polygon = new BMap.Polygon(polygonPoints, {
          strokeColor: getFenceTypeColor(fence.type) === 'green' ? '#00ff00' : 
                      getFenceTypeColor(fence.type) === 'blue' ? '#0000ff' :
                      getFenceTypeColor(fence.type) === 'red' ? '#ff0000' : '#ff8800',
          strokeWeight: 2,
          strokeOpacity: 0.8,
          fillColor: getFenceTypeColor(fence.type) === 'green' ? '#00ff00' : 
                    getFenceTypeColor(fence.type) === 'blue' ? '#0000ff' :
                    getFenceTypeColor(fence.type) === 'red' ? '#ff0000' : '#ff8800',
          fillOpacity: 0.2
        })
        
        // 添加点击事件
        polygon.addEventListener('click', () => selectFence(fence))
        
        baiduMap.addOverlay(polygon)
        allPolygons.push(polygon)
        
        // 添加中心点标记
        if (fence.center_lng && fence.center_lat) {
          const marker = new BMap.Marker(new BMap.Point(fence.center_lng, fence.center_lat))
          const label = new BMap.Label(fence.name, {
            offset: new BMap.Size(0, -30)
          })
          marker.setLabel(label)
          marker.addEventListener('click', () => selectFence(fence))
          
          baiduMap.addOverlay(marker)
          allMarkers.push(marker)
        }
      }
    } catch (error) {
      console.error(`加载围栏 ${fence.name} 坐标点失败:`, error)
    }
  }
}

// 选择围栏
const selectFence = async (fence) => {
  selectedFence.value = fence
  console.log('选择围栏:', fence)
  
  // 获取围栏坐标点并在地图上显示
  try {
    const pointsResult = await api.electronicFencePoints.getByFenceId(fence.id)
    console.log('选择围栏坐标点API响应:', pointsResult)
    
    // 处理API响应格式
    let points = []
    if (pointsResult && pointsResult.success && Array.isArray(pointsResult.data)) {
      points = pointsResult.data
    } else if (Array.isArray(pointsResult)) {
      // 兼容旧格式
      points = pointsResult
    } else {
      points = []
      console.warn('选择围栏坐标点API返回数据格式异常:', pointsResult)
    }
    
    if (points.length >= 3) {
      // 清除当前高亮的围栏
      clearHighlightedFence()
      
      // 创建围栏多边形并高亮显示
      const polygonPoints = points.map(p => new BMap.Point(p.lng, p.lat))
      const highlightPolygon = new BMap.Polygon(polygonPoints, {
        strokeColor: '#ff4d4f',
        strokeWeight: 4,
        strokeOpacity: 1,
        fillColor: '#ff4d4f',
        fillOpacity: 0.3,
        strokeStyle: 'solid'
      })
      
      // 添加到地图
      baiduMap.addOverlay(highlightPolygon)
      
      // 保存高亮围栏引用
      selectedFence.value.highlightPolygon = highlightPolygon
      
      // 计算围栏边界并调整地图视图
      const bounds = new BMap.Bounds()
      polygonPoints.forEach(point => bounds.extend(point))
      
      // 设置地图视图以完全显示围栏
      baiduMap.setViewport(polygonPoints, {
        margins: [50, 50, 50, 50],
        zoomFactor: 0.8
      })
      
      // 在围栏中心添加信息窗口
      if (fence.center_lng && fence.center_lat) {
        const centerPoint = new BMap.Point(fence.center_lng, fence.center_lat)
        const infoWindow = new BMap.InfoWindow(
          `<div style="padding: 10px;">
            <h4 style="margin: 0 0 8px 0; color: #1890ff;">${fence.name}</h4>
            <p style="margin: 4px 0;"><strong>类型:</strong> ${getFenceTypeText(fence.type)}</p>
            <p style="margin: 4px 0;"><strong>坐标点:</strong> ${points.length} 个</p>
            <p style="margin: 4px 0;"><strong>面积:</strong> ${fence.area ? (typeof fence.area === 'number' ? fence.area.toFixed(2) : fence.area) + ' 平方米' : '未知'}</p>
            <p style="margin: 4px 0;"><strong>描述:</strong> ${fence.description || '无描述'}</p>
          </div>`,
          {
            width: 280,
            height: 150,
            title: '围栏详情'
          }
        )
        
        // 显示信息窗口
        baiduMap.openInfoWindow(infoWindow, centerPoint)
        
        // 保存信息窗口引用
        selectedFence.value.infoWindow = infoWindow
      }
      
      message.success(`已定位到围栏"${fence.name}"，包含${points.length}个坐标点`)
    } else {
      message.warning(`围栏"${fence.name}"的坐标点数据不足，无法在地图上显示`)
    }
  } catch (error) {
    console.error('获取围栏坐标点失败:', error)
    message.error('获取围栏坐标点失败: ' + error.message)
  }
}

// 清除高亮的围栏
const clearHighlightedFence = () => {
  if (selectedFence.value?.highlightPolygon) {
    baiduMap.removeOverlay(selectedFence.value.highlightPolygon)
    selectedFence.value.highlightPolygon = null
  }
  
  if (selectedFence.value?.infoWindow) {
    baiduMap.closeInfoWindow(selectedFence.value.infoWindow)
    selectedFence.value.infoWindow = null
  }
}

// 关闭围栏信息面板
const closeFenceInfo = () => {
  clearHighlightedFence()
  selectedFence.value = null
  console.log('关闭围栏信息面板')
}

// 处理围栏列表项点击
const handleFenceItemClick = (item, event) => {
  console.log('围栏列表项点击:', item.name, event.target)
  
  // 检查点击的是否是按钮区域
  if (event.target.closest('.ant-btn') || event.target.closest('.ant-tooltip')) {
    console.log('点击的是按钮区域，不执行选择操作')
    return
  }
  
  console.log('执行围栏选择操作')
  selectFence(item)
}

// 编辑围栏
const editFence = (fence) => {
  console.log('=== 开始编辑围栏 ===')
  console.log('原始围栏数据:', fence)
  editingFence.value = fence
  
  // 处理类型映射 - 将中文类型转换为英文
  let fenceType = fence.type || 'grazing'
  console.log('原始类型:', fenceType)
  if (fenceType === '放牧围栏') fenceType = 'grazing'
  else if (fenceType === '安全围栏') fenceType = 'safety'
  else if (fenceType === '限制围栏') fenceType = 'restricted'
  else if (fenceType === '收集围栏') fenceType = 'collector'
  console.log('映射后类型:', fenceType)
  
  // 设置表单数据 - 强制更新响应式对象
  fenceForm.name = fence.name
  fenceForm.type = fenceType
  fenceForm.description = fence.description || ''
  
  // 强制触发响应式更新
  nextTick(() => {
    console.log('nextTick后的fenceForm:', fenceForm)
    console.log('nextTick后的fenceForm.name:', fenceForm.name)
  })
  
  fenceModalVisible.value = true
  
  console.log('=== 编辑围栏模态框已打开 ===')
  console.log('fenceForm对象:', fenceForm)
  console.log('fenceForm.name:', fenceForm.name)
  console.log('fenceForm.type:', fenceForm.type)
  console.log('fenceForm.description:', fenceForm.description)
  console.log('modalVisible:', fenceModalVisible.value)
}

// 处理名称输入
const handleNameInput = (e) => {
  console.log('=== 名称输入变化 ===')
  console.log('输入框值:', e.target.value)
  console.log('fenceForm.name:', fenceForm.name)
  console.log('fenceForm对象:', fenceForm)
  console.log('fenceForm是否响应式:', fenceForm.__v_isReactive)
  
  // 强制同步
  fenceForm.name = e.target.value
  console.log('强制同步后fenceForm.name:', fenceForm.name)
}

const handleNameChange = (e) => {
  console.log('=== 名称输入完成 ===')
  console.log('输入框值:', e.target.value)
  console.log('fenceForm.name:', fenceForm.name)
  console.log('fenceForm对象:', fenceForm)
}

// 删除围栏
const deleteFence = (fence) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除围栏"${fence.name}"吗？`,
    onOk: async () => {
      try {
        await api.electronicFence.deleteFence(fence.id)
        message.success('围栏删除成功')
        await loadFenceData()
      } catch (error) {
        console.error('删除围栏失败:', error)
        message.error('删除围栏失败: ' + error.message)
      }
    }
  })
}

// 搜索围栏
const handleSearch = () => {
  // 搜索逻辑在计算属性中处理
}

// 处理围栏名称选择
const handleFenceNameSelect = (value) => {
  selectedFenceName.value = value
  // 清空文本搜索，避免冲突
  if (value) {
    searchValue.value = ''
  }
}

// 过滤围栏名称选项
const filterFenceNameOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 清除所有搜索条件
const clearAllSearch = () => {
  searchValue.value = ''
  selectedFenceName.value = ''
  searchType.value = ''
}

// 初始化
onMounted(() => {
  console.log('电子围栏组件已挂载')
})
</script>

<style scoped>
.electronic-fence-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  color: #1890ff;
}

.page-description {
  margin: 8px 0 0 0;
  color: #666;
  font-size: 14px;
}

.map-section {
  flex: 1;
  display: flex;
  gap: 20px;
  min-height: 600px;
}

.drawing-controls {
  position: absolute;
  top: 80px; /* 增加top值避免遮挡菜单栏 */
  left: 20px;
  z-index: 1000;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  min-width: 320px;
  max-width: 400px;
  border: 1px solid #e8e8e8;
}

.control-group {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.control-btn {
  flex: 1;
}

.drawing-status {
  margin-top: 10px;
}

.point-sequence {
  margin-top: 8px;
  max-height: 120px;
  overflow-y: auto;
}

.point-tag {
  margin: 2px;
  font-size: 11px;
  font-family: monospace;
}

.fence-info-panel {
  position: absolute;
  top: 80px; /* 增加top值避免遮挡菜单栏 */
  right: 20px;
  z-index: 1000;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  min-width: 280px;
  max-width: 350px;
  border: 1px solid #e8e8e8;
}

.fence-selector-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 1000;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  width: 300px;
  max-height: 300px;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.panel-content {
  padding: 0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  padding: 4px 0;
}

.info-item .label {
  font-weight: 500;
  color: #666;
}

.info-item .value {
  color: #333;
}

.search-section {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.search-input {
  width: 100%;
}

.fence-name-select {
  width: 100%;
}

.type-filter {
  width: 100%;
}

.clear-search-btn {
  width: 100%;
  margin-top: 5px;
}

.fence-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.fence-stats .ant-statistic {
  text-align: center;
}

.fence-list {
  max-height: 200px;
  overflow-y: auto;
}

.fence-item {
  cursor: pointer;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.fence-item:hover {
  background-color: #f5f5f5;
}

.fence-item.selected {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.fence-name {
  font-weight: 500;
  margin-right: 8px;
}

.fence-type-tag {
  font-size: 12px;
}

.fence-description {
  color: #666;
  font-size: 12px;
}

.fence-coords {
  color: #999;
  font-size: 11px;
}

.map-wrapper {
  flex: 1;
  position: relative;
  min-height: 600px;
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

.baidu-map {
  width: 100%;
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-section {
    flex-direction: column;
  }
  
  .drawing-controls,
  .fence-info-panel,
  .fence-selector-panel {
    position: relative;
    top: auto;
    right: auto;
    bottom: auto;
    left: auto;
    width: 100%;
    margin-bottom: 10px;
  }
  
  .control-group {
    flex-direction: column;
  }
}
</style>