<template>
    <div class="event-editor-container">
      <dv-border-box-8>
        <div class="editor-content">
            <!-- 左侧视频区域 -->
            <div class="video-section">
                <!-- 上部视频预览区域 (55%) -->
                <div class="video-preview">
                     <div class="video-placeholder" ref="videoContainer">
                        <svg viewBox="0 0 24 24" width="60" height="60">
                            <path fill="#7cd0ff"
                                d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z" />
                        </svg>
                        <p>视频区域</p>
                        <!-- 绘制蒙版层 -->
                         <div class="drawing-mask" v-if="activeEvent.fenceArea === '自定义画面'">
                              <div class="mask-background"></div>
                              <canvas 
                                  ref="drawingCanvas" 
                                  @click="handleCanvasClick"
                                  @contextmenu.prevent="handleRightClick"
                                  @mousemove="handleMouseMove"
                              ></canvas>
                          </div>
                    </div>
                    <div class="video-actions">
                        <el-radio-group v-model="drawMode" size="small">
                            <el-radio-button label="polygon">多边形</el-radio-button>
                            <el-radio-button label="line">直线</el-radio-button>
                        </el-radio-group>
                        <el-button class="upload-btn" @click="handleUploadClick">
                            <el-icon><UploadFilled /></el-icon>
                            上传模拟视频
                        </el-button>
                        <el-button class="clear-btn" @click="resetDrawing">
                            <el-icon><Delete /></el-icon>
                            清空模拟视频
                        </el-button>
                    </div>
                </div>

                <!-- 下部设备信息区域 (45%) -->
                <div class="device-info">
                    <h4>设备默认信息显示区域</h4>
                    <div class="info-item">
                        <span class="label">分组：</span>
                        <span class="value">港口区</span>
                    </div>
                    <div class="info-item">
                        <span class="label">摄像头ID：</span>
                        <span class="value">VIDEO_214IOISHEK454</span>
                    </div>
                    <div class="info-item">
                        <span class="label">设备状态：</span>
                        <span class="value">在线</span>
                    </div>
                    <div class="info-item">
                        <span class="label">IP地址：</span>
                        <span class="value">192.168.5.44</span>
                    </div>
                </div>
            </div>

            <!-- 右侧事件设置区域 -->
            <div class="event-section">
                <!-- 顶部标题和新增按钮 -->
                <div class="section-header">
                    <h3>事件绑定与算法绑定</h3>
                    <el-button class="add-event-btn" @click="addEventGroup">
                        <svg viewBox="0 0 24 24" width="16" height="16">
                            <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
                        </svg>
                        新增事件
                    </el-button>
                </div>

                <!-- 事件组列表 -->
                <div class="event-group-list">
                    <div 
                        class="event-group" 
                        v-for="(event, index) in eventGroups" 
                        :key="index"
                        :class="{ 'active': activeIndex === index }"
                        @click="switchEvent(index)"
                    >
                        <!-- 第一行：事件名称、电子围栏区域、告警等级 -->
                        <div class="form-row">
                            <div class="form-item">
                                <label>事件名称:</label>
                                <el-select v-model="event.name" placeholder="请选择事件类型">
                                    <el-option label="船舶靠泊" value="船舶靠泊" />
                                    <el-option label="船舶离泊" value="船舶离泊" />
                                    <el-option label="人员登轮" value="人员登轮" />
                                    <el-option label="人员离轮" value="人员离轮" />
                                    <el-option label="电脑弹窗" value="电脑弹窗" />
                                </el-select>
                            </div>

                            <div class="form-item">
                                <label>电子围栏区域:</label>
                                <el-switch
                                    v-model="event.fenceArea"
                                    active-text="整个监控画面"
                                    inactive-text="自定义画面"
                                    active-value="整个监控画面"
                                    inactive-value="自定义画面"
                                />
                            </div>

                            <div class="form-item">
                                <label>告警等级:</label>
                                <el-select v-model="event.level" placeholder="P0紧急告警">
                                    <el-option label="P0紧急告警" value="P0" />
                                    <el-option label="P1重要告警" value="P1" />
                                    <el-option label="P2一般告警" value="P2" />
                                    <el-option label="P3提示告警" value="P3" />
                                </el-select>
                            </div>
                        </div>

                        <!-- 动态生成的电子围栏配置区域 -->
                        <div class="form-row" v-for="(fence, fenceIndex) in event.fenceAreas" :key="fenceIndex">
                            <div class="form-item" style="width: 20%;">
                                <label>电子围栏名称:</label>
                                <el-input v-model="fence.name" placeholder="请输入" />
                            </div>
                            <div class="form-item" style="width: 30%;">
                                <label>算法绑定:</label>
                                <el-select v-model="fence.algorithm" placeholder="算法XXX001">
                                    <el-option v-for="alg in algorithms" 
                                        :key="alg.id" 
                                        :label="alg.name" 
                                        :value="alg.id" />
                                </el-select>
                            </div>
                            <div class="form-item" tyle="width: 50%;">
                                <label>算法条件:</label>
                                <label style="width:80%;">{{fence.condition}}</label>
                            </div>
                        </div>

                        <!-- 第三行：交叉区域名称、交集算法绑定 -->
                        <div class="form-row">
                            <div class="form-item" style="width: 20%;">
                                <label>交叉区域名称:</label>
                                <el-input v-model="event.crossAreaName" placeholder="请输入" />
                            </div>

                            <div class="form-item" tyle="width: 30%;">
                                <label>交集算法绑定:</label>
                                <el-select v-model="event.crossAlgorithm" placeholder="算法XXX001">
                                    <el-option v-for="alg in algorithms" :key="alg.id" :label="alg.name" :value="alg.id" />
                                </el-select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 底部操作按钮 -->
                <div class="editor-footer">
                    <el-button class="preview-btn">
                        <svg viewBox="0 0 24 24" width="16" height="16">
                            <path fill="currentColor"
                                d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" />
                        </svg>
                        查看模拟效果
                    </el-button>
                    <el-button class="save-btn" @click="saveEvent">
                        保存应用设置
                    </el-button>
                    <el-button 
                        class="delete-polygon-btn" 
                        @click="deleteSelectedShape" 
                        :disabled="selectedShapeIndex === null"
                    >
                        <el-icon><Delete /></el-icon>
                        删除选中图形
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 右键菜单 -->
        <div class="context-menu" v-if="showContextMenu" :style="{ left: contextMenuPos.x + 'px', top: contextMenuPos.y + 'px' }">
            <div class="menu-item" @click="deletePoint">删除该点</div>
            <div class="menu-item" @click="closeContextMenu">取消</div>
        </div>

        <!-- 上传视频弹窗 -->
        <el-dialog v-model="uploadDialogVisible" title="上传模拟视频" width="50%">
            <el-upload
                class="upload-demo"
                drag
                action=""
                :auto-upload="false"
                :on-change="handleVideoChange"
                :file-list="fileList"
                accept="video/*"
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    拖拽视频文件到此处或 <em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        请上传MP4、AVI等视频格式文件，大小不超过100MB
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="uploadDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmUpload" :disabled="!selectedFile">
                        确认上传
                    </el-button>
                </span>
            </template>
        </el-dialog>
      </dv-border-box-8>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { UploadFilled, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 绘图相关参数
const videoContainer = ref(null)
const drawingCanvas = ref(null)
const ctx = ref(null)
const showDrawingCanvas = ref(false)
const canvasInitialized = ref(false)

// 绘图状态
const points = ref([]) // 存储当前图形的点
const completedShapes = ref([]) // 存储已完成的图形
const isDrawing = ref(false) // 是否正在绘制
const selectedShapeIndex = ref(null) // 当前选中的图形索引
const drawMode = ref('polygon') // 绘制模式：polygon-多边形，line-直线
const mousePos = ref(null) // 鼠标当前位置

// 右键菜单状态
const showContextMenu = ref(false)
const contextMenuPos = ref({ x: 0, y: 0 })
const clickedPointIndex = ref(-1)

// 上传视频相关状态
const uploadDialogVisible = ref(false)
const fileList = ref([])
const selectedFile = ref(null)

// 事件组相关状态
const eventGroups = ref([])
const activeIndex = ref(0)

const props = defineProps({
    deviceData: {
        type: Object,
        required: true
    }
})

const emit = defineEmits(['close', 'save'])

const algorithms = ref([
    { id: 'alg-001', name: '船舶靠泊识别', condition: '识别船舶框体与电子围栏相交则报警靠岸成功' },
    { id: 'alg-002', name: '船舶离泊识别', condition: '识别船舶框体与电子围栏远离则报警开始离岸' },
    { id: 'alg-003', name: '人员登轮识别', condition: '目标识别人员依次通过电子围栏1、2则报警人员登轮' },
    { id: 'alg-004', name: '人员离轮识别', condition: '目标识别人员依次通过电子围栏1、2则报警人员离轮' },
    { id: 'alg-005', name: '弹窗识别', condition: '识别个人办公区域内电脑出现弹窗后无第二位员工且弹窗消失则报警' }
])

// 当前活动的事件
const activeEvent = computed(() => {
    return eventGroups.value[activeIndex.value] || {}
})

// 初始化事件组
const initEventGroups = () => {
    eventGroups.value = [
        {
            name: '船舶靠泊', // 默认设置为船舶靠泊
            fenceArea: '整个监控画面',
            level: 'P0',
            fenceAreas: [],
            completedShapes: [],
            points: [],
            drawMode: 'polygon',
            crossAreaName: '',
            crossAlgorithm: 'alg-001'
        }
    ]
}

// 添加新的事件组
const addEventGroup = () => {
    eventGroups.value.push({
        name: '船舶靠泊', // 默认设置为船舶靠泊
        fenceArea: '整个监控画面',
        level: 'P0',
        fenceAreas: [],
        completedShapes: [],
        points: [],
        drawMode: 'polygon',
        crossAreaName: '',
        crossAlgorithm: 'alg-001'
    })
    // 切换到新添加的事件组
    switchEvent(eventGroups.value.length - 1)
}

// 切换事件组
const switchEvent = (index) => {
    // 保存当前事件组的绘图状态
    if (activeEvent.value) {
        activeEvent.value.points = [...points.value];
        activeEvent.value.completedShapes = [...completedShapes.value];
        activeEvent.value.drawMode = drawMode.value;
    }
    
    // 切换到新的事件组
    activeIndex.value = index;
    
    // 加载新事件组的绘图状态
    points.value = [...(activeEvent.value.points || [])];
    completedShapes.value = [...(activeEvent.value.completedShapes || [])];
    drawMode.value = activeEvent.value.drawMode || 'polygon';
    
    // 更新显示状态
    showDrawingCanvas.value = activeEvent.value.fenceArea === '自定义画面';
    
    // 重绘画布
    nextTick(() => {
        if (showDrawingCanvas.value) {
            initCanvas();
        }
        redrawCanvas();
    });
}

// 保存事件
const saveEvent = () => {
    // 保存当前事件组的绘图状态
    if (activeEvent.value) {
        activeEvent.value.points = [...points.value]
        activeEvent.value.completedShapes = [...completedShapes.value]
    }
    
    emit('save', {
        eventGroups: eventGroups.value
    })
}

// 组件挂载时初始化
onMounted(() => {
    initEventGroups()
    window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
})

// 监听电子围栏区域变化
watch(() => activeEvent.value?.name, (newName, oldName) => {
    if (newName !== oldName) {
        // 根据事件名称自动设置电子围栏和算法
        updateEventConfigByType(newName);
    }
})
const updateEventConfigByType = (eventType) => {
    if (!activeEvent.value) return;
    
    // 保存当前绘图状态
    const currentPoints = [...points.value];
    const currentShapes = [...completedShapes.value];
    
    // 根据事件类型设置默认算法
    let algorithmId = 'alg-001';
    let fenceName = '围栏区域';
    
    switch(eventType) {
        case '船舶靠泊':
            algorithmId = 'alg-001';
            fenceName = '岸边';
            break;
        case '船舶离泊':
            algorithmId = 'alg-002';
            fenceName = '岸边';
            break;
        case '人员登轮':
            algorithmId = 'alg-003';
            fenceName = '岸边平面';
            break;
        case '人员离轮':
            algorithmId = 'alg-004';
            fenceName = '船舶楼梯上层平面';
            break;
        case '电脑弹窗':
            algorithmId = 'alg-005';
            fenceName = '个人办公区域';
            break;
    }
    
    // 更新交叉区域算法
    activeEvent.value.crossAlgorithm = algorithmId;
    
    // 恢复绘图状态
    points.value = currentPoints;
    completedShapes.value = currentShapes;
    
    // 重绘画布
    redrawCanvas();
}

// 处理窗口大小变化
const handleResize = () => {
    if (showDrawingCanvas.value && canvasInitialized.value) {
        initCanvas()
        redrawCanvas()
    }
}

// 初始化画布
const initCanvas = () => {
    if (!drawingCanvas.value || !videoContainer.value) return
    
    const canvas = drawingCanvas.value
    canvas.width = videoContainer.value.clientWidth
    canvas.height = videoContainer.value.clientHeight
    
    ctx.value = canvas.getContext('2d')
    canvasInitialized.value = true
}

// 处理鼠标移动事件
const handleMouseMove = (e) => {
    if (!isDrawing.value || points.value.length === 0) return
    
    const rect = drawingCanvas.value.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    mousePos.value = { x, y }
    redrawCanvas()
}

// 处理画布点击事件
const handleCanvasClick = (e) => {
    if (activeEvent.value?.fenceArea !== '自定义画面') return
    
    const rect = drawingCanvas.value.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    // 检查是否点击了已存在的图形
    if (!isDrawing.value) {
        let clickedShape = false
        
        completedShapes.value.forEach((shape, index) => {
            if (isPointInShape({x, y}, shape)) {
                selectedShapeIndex.value = index
                clickedShape = true
            }
        })
        
        if (clickedShape) {
            redrawCanvas()
            return
        }
    }
    
    // 如果是第一次点击，开始新图形
    if (!isDrawing.value) {
        points.value = [{x, y}]
        isDrawing.value = true
        selectedShapeIndex.value = null
        redrawCanvas()
        return
    }
    
    // 检查是否接近第一个点（闭合多边形）
    if (drawMode.value === 'polygon' && points.value.length > 2) {
        const firstPoint = points.value[0]
        const distance = Math.sqrt(Math.pow(x - firstPoint.x, 2) + Math.pow(y - firstPoint.y, 2))
        
        if (distance < 15) { // 15像素范围内认为是要闭合
            points.value.push({x: firstPoint.x, y: firstPoint.y})
            completeDrawing()
            return
        }
    }
    
    // 添加新点
    points.value.push({x, y})
    
    // 如果是直线模式且有两个点，完成绘制
    if (drawMode.value === 'line' && points.value.length === 2) {
        completeDrawing()
        return
    }
    
    redrawCanvas()
}

// completeDrawing方法
const completeDrawing = () => {
    if (points.value.length < 2) {
        isDrawing.value = false;
        points.value = [];
        return;
    }
    
    // 如果是多边形且点数大于2，闭合多边形
    if (drawMode.value === 'polygon' && points.value.length > 2) {
        const firstPoint = points.value[0];
        const lastPoint = points.value[points.value.length - 1];
        
        // 确保多边形是闭合的
        if (firstPoint.x !== lastPoint.x || firstPoint.y !== lastPoint.y) {
            points.value.push({x: firstPoint.x, y: firstPoint.y});
        }
    }
    
    // 创建新的图形对象
    const newShape = {
        type: drawMode.value,
        points: [...points.value]
    };
    
    // 添加到已完成图形数组
    completedShapes.value.push(newShape);
    
    // 根据事件名称自动设置电子围栏名称和算法
    let fenceName = '围栏区域';
    let algorithmId = 'alg-001';
    
    if (activeEvent.value.name === '船舶靠泊') {
        fenceName = '岸边';
        algorithmId = 'alg-001';
    } else if (activeEvent.value.name === '船舶离泊') {
        fenceName = '岸边';
        algorithmId = 'alg-002';
    } else if (activeEvent.value.name === '人员登轮') {
        fenceName = '岸边平面';
        algorithmId = 'alg-003';
    } else if (activeEvent.value.name === '人员离轮') {
        fenceName = '船舶楼梯上层平面';
        algorithmId = 'alg-004';
    } else if (activeEvent.value.name === '电脑弹窗') {
        fenceName = '个人办公区域';
        algorithmId = 'alg-005';
    }
    
    // 添加到当前事件组的电子围栏配置
    if (activeEvent.value) {
        activeEvent.value.fenceAreas.push({
            name: `${fenceName}`,
            algorithm: algorithmId,
            points: [...points.value],
            type: drawMode.value,
            condition: algorithms.value.find(a => a.id === algorithmId)?.condition || ''
        });
        
        // 确保completedShapes与fenceAreas同步
        activeEvent.value.completedShapes = [...completedShapes.value];
    }
    
    // 重置当前绘制状态
    points.value = [];
    isDrawing.value = false;
    
    // 立即重绘画布
    redrawCanvas();
}

// 修改redrawCanvas方法
const redrawCanvas = () => {
  if (!ctx.value || !drawingCanvas.value) return
  
  // 清除画布
  ctx.value.clearRect(0, 0, drawingCanvas.value.width, drawingCanvas.value.height)
  
  // 绘制所有已完成的图形
  completedShapes.value.forEach((shape, index) => {
    // 如果是选中的图形，用不同颜色显示
    if (index === selectedShapeIndex.value) {
      ctx.value.fillStyle = 'rgba(255, 0, 0, 0.3)'
      ctx.value.strokeStyle = '#ff0000'
    } else {
      ctx.value.fillStyle = 'rgba(124, 208, 255, 0.3)'
      ctx.value.strokeStyle = '#7cd0ff'
    }
    
    // 绘制图形
    drawShape(shape)
  })
  
  // 绘制当前正在绘制的图形
  if (points.value.length > 0) {
    // 绘制点
    points.value.forEach((point, index) => {
      ctx.value.beginPath()
      ctx.value.arc(point.x, point.y, 5, 0, Math.PI * 2)
      ctx.value.fillStyle = index === clickedPointIndex.value ? '#ff0000' : '#ff7cd0'
      ctx.value.fill()
      ctx.value.strokeStyle = '#fff'
      ctx.value.lineWidth = 1
      ctx.value.stroke()
    })
    
    // 绘制连线
    if (points.value.length > 1 || mousePos.value) {
      ctx.value.beginPath()
      ctx.value.moveTo(points.value[0].x, points.value[0].y)
      
      if (drawMode.value === 'polygon') {
        for (let i = 1; i < points.value.length; i++) {
          ctx.value.lineTo(points.value[i].x, points.value[i].y)
        }
      } else if (drawMode.value === 'line') {
        const endPoint = mousePos.value || points.value[1] || points.value[0]
        ctx.value.lineTo(endPoint.x, endPoint.y)
      }
      
      ctx.value.strokeStyle = '#7cd0ff'
      ctx.value.lineWidth = 2
      ctx.value.stroke()
    }
  }
}

// 修改drawShape方法
const drawShape = (shape) => {
  if (!shape || !shape.points || shape.points.length < 2) return
  
  ctx.value.beginPath()
  ctx.value.moveTo(shape.points[0].x, shape.points[0].y)
  
  for (let i = 1; i < shape.points.length; i++) {
    ctx.value.lineTo(shape.points[i].x, shape.points[i].y)
  }
  
  if (shape.type === 'polygon') {
    ctx.value.closePath()
    ctx.value.fill()
  }
  
  ctx.value.stroke()
  
  // 绘制顶点
  shape.points.forEach(point => {
    drawPoint(point)
  })
}

// 修改resetDrawing方法
const resetDrawing = () => {
  points.value = []
  completedShapes.value = []
  if (activeEvent.value) {
    activeEvent.value.fenceAreas = []
    activeEvent.value.completedShapes = []
  }
  selectedShapeIndex.value = null
  isDrawing.value = false
  if (ctx.value && drawingCanvas.value) {
    ctx.value.clearRect(0, 0, drawingCanvas.value.width, drawingCanvas.value.height)
  }
}

// 处理右键点击事件
const handleRightClick = (e) => {
    if (!isDrawing.value || points.value.length === 0 || drawMode.value === 'line') return
    
    const rect = drawingCanvas.value.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    // 找到最近的坐标点
    let minDistance = Infinity
    let pointIndex = -1
    
    points.value.forEach((point, index) => {
        const distance = Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2))
        if (distance < 15 && distance < minDistance) { // 15像素范围内
            minDistance = distance
            pointIndex = index
        }
    })
    
    if (pointIndex !== -1) {
        clickedPointIndex.value = pointIndex
        contextMenuPos.value = { x: e.clientX, y: e.clientY }
        showContextMenu.value = true
        redrawCanvas() // 重绘以高亮显示选中的点
    }
}

// 删除点
const deletePoint = () => {
    if (clickedPointIndex.value === -1) return
    
    points.value.splice(clickedPointIndex.value, 1)
    
    // 如果删除后点数不足2个，结束绘制
    if (points.value.length < 2) {
        isDrawing.value = false
    }
    
    closeContextMenu()
    redrawCanvas()
}

// 关闭右键菜单
const closeContextMenu = () => {
    showContextMenu.value = false
    clickedPointIndex.value = -1
    redrawCanvas()
}

// 删除选中的图形
const deleteSelectedShape = () => {
    if (selectedShapeIndex.value === null) return
    
    // 从已完成图形数组中移除
    completedShapes.value.splice(selectedShapeIndex.value, 1)
    // 从电子围栏配置中移除
    if (activeEvent.value) {
        activeEvent.value.fenceAreas.splice(selectedShapeIndex.value, 1)
    }
    
    selectedShapeIndex.value = null
    redrawCanvas()
}

// 判断点是否在图形内
const isPointInShape = (point, shape) => {
    if (shape.type === 'polygon') {
        return isPointInPolygon(point, shape.points)
    } else if (shape.type === 'line') {
        return isPointNearLine(point, shape.points[0], shape.points[1])
    }
    return false
}

// 判断点是否在多边形内
const isPointInPolygon = (point, polygon) => {
    const x = point.x
    const y = point.y
    
    let inside = false
    for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const xi = polygon[i].x
        const yi = polygon[i].y
        const xj = polygon[j].x
        const yj = polygon[j].y
        
        const intersect = ((yi > y) !== (yj > y)) &&
            (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
        if (intersect) inside = !inside
    }
    
    return inside
}

// 判断点是否在直线附近
const isPointNearLine = (point, lineStart, lineEnd) => {
    const {x, y} = point
    const {x: x1, y: y1} = lineStart
    const {x: x2, y: y2} = lineEnd
    
    // 计算点到线段的距离
    const A = x - x1
    const B = y - y1
    const C = x2 - x1
    const D = y2 - y1

    const dot = A * C + B * D
    const len_sq = C * C + D * D
    let param = -1
    if (len_sq !== 0) param = dot / len_sq

    let xx, yy

    if (param < 0) {
        xx = x1
        yy = y1
    } else if (param > 1) {
        xx = x2
        yy = y2
    } else {
        xx = x1 + param * C
        yy = y1 + param * D
    }

    const dx = x - xx
    const dy = y - yy
    const distance = Math.sqrt(dx * dx + dy * dy)
    
    return distance < 15 // 15像素范围内认为是在直线附近
}





// 绘制点
const drawPoint = (point) => {
    ctx.value.beginPath()
    ctx.value.arc(point.x, point.y, 5, 0, Math.PI * 2)
    ctx.value.fillStyle = '#7cd0ff'
    ctx.value.fill()
    ctx.value.strokeStyle = '#fff'
    ctx.value.lineWidth = 1
    ctx.value.stroke()
}



// 上传视频相关方法
const handleUploadClick = () => {
    uploadDialogVisible.value = true
    fileList.value = []
    selectedFile.value = null
}

const handleVideoChange = (file) => {
    selectedFile.value = file.raw
}

const confirmUpload = () => {
    if (!selectedFile.value) return
    
    // 这里可以添加文件上传逻辑
    console.log('上传文件:', selectedFile.value)
    
    // 模拟上传成功
    ElMessage.success('视频上传成功')
    uploadDialogVisible.value = false
}

const closeEditor = () => {
    emit('close')
}
</script>

<style scoped>
.event-editor-container {
    height: 85vh;
    background: #0a1d3c;
    padding: 20px;
    width: 100vw;
}

.editor-content {
    display: flex;
    height: 85vh;
    width: 98vw;
    padding: 30px;
}

/* 左侧视频区域 */
.video-section {
    width: 30%;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

/* 视频预览区域 (55%) */
.video-preview {
    height: 55%;
    display: flex;
    flex-direction: column;
}

.video-placeholder {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(16, 42, 87, 0.6);
    border: 1px dashed #7cd0ff;
    border-radius: 4px;
    color: #7cd0ff;
    position: relative;
}

.video-placeholder p {
    margin-top: 10px;
    color: white;
    font-size: 14px;
}

.video-actions {
    display: flex;
    gap: 10px;
    margin-top: 10px;
    align-items: center;
}

.video-actions .el-radio-group {
    margin-right: auto;
}

.video-actions .el-button {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px;
}

.upload-btn {
    background: rgba(124, 208, 255, 0.2);
    border-color: #7cd0ff;
    color: #7cd0ff;
}

.clear-btn {
    background: rgba(255, 77, 79, 0.2);
    border-color: #ff4d4f;
    color: #ff4d4f;
    display: flex;
    align-items: center;
    padding: 8px 12px;
}

.clear-btn .el-icon {
    margin-right: 6px;
    font-size: 16px;
}

/* 设备信息区域 (45%) */
.device-info {
    height: 35%;
    background: rgba(16, 42, 87, 0.6);
    border-radius: 4px;
    padding: 15px;
    color: white;
}

.device-info h4 {
    color: #7cd0ff;
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 16px;
}

.info-item {
    display: flex;
    margin-bottom: 12px;
    font-size: 14px;
}

.info-item .label {
    color: #7cd0ff;
    width: 100px;
}

.info-item .value {
    color: white;
    flex: 1;
}

.event-section {
    width: 60%;
    flex: 1;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
    background: rgba(16, 42, 87, 0.6);
    border-radius: 4px;
    padding: 20px;
    color: white;
    height: 92%;
}

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

.section-header h3 {
    color: white;
    margin: 0;
    font-size: 18px;
}

.add-event-btn {
    background: rgba(124, 208, 255, 0.2);
    border-color: #7cd0ff;
    color: #7cd0ff;
    display: flex;
    align-items: center;
    gap: 6px;
}

.event-group-list {
    flex: 1;
    overflow-y: auto;
    padding-right: 10px;
}

.event-group {
    background: rgba(5, 18, 42, 0.6);
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 15px;
    transition: all 0.3s;
}

.event-group.active {
    border: 1px solid #00d2ff;
}

.algorithm-condition-hint {
    margin-top: 15px;
    padding: 8px 12px;
    background-color: rgba(255, 77, 79, 0.2);
    border-radius: 4px;
}

.hint-text {
    color: #ff4d4f;
    font-size: 14px;
}

.form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
    animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
    from { 
        opacity: 0; 
        transform: translateY(10px); 
    }
    to { 
        opacity: 1; 
        transform: translateY(0); 
    }
}

.form-row:last-child {
    margin-bottom: 0;
}

.form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 400px;
}

.form-item label {
    display: block;
    color: #7cd0ff;
    font-size: 14px;
    width: 120px;
}

.form-item .el-input,
.form-item .el-select {
    width: 70%;
}

.form-item .el-switch {
    flex: 1;
}

/* 调整单选按钮样式 */
.el-radio {
    --el-radio-text-color: white;
    --el-radio-checked-text-color: #7cd0ff;
}

.el-radio__input.is-checked + .el-radio__label {
    color: #7cd0ff;
}

.el-radio__inner {
    border-color: #7cd0ff;
}

.el-radio__input.is-checked .el-radio__inner {
    background-color: #0a1d3c;
    border-color: #7cd0ff;
}

.el-radio__inner::after {
    background-color: #7cd0ff;
}

/* 添加开关样式 */
.el-switch {
    --el-switch-on-color: #00d2ff;
    --el-switch-off-color: #7cd0ff;
}

.el-switch__text {
    color: white;
    font-size: 14px;
    margin-left: 8px;
    margin-right: 8px;
}

.editor-footer {
    text-align: right;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 15px;
}

.delete-polygon-btn {
    background: rgba(255, 0, 0, 0.2);
    border-color: #ff0000;
    color: #ff0000;
    display: flex;
    align-items: center;
}

.delete-polygon-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.delete-polygon-btn .el-icon {
    margin-right: 6px;
}

/* 蒙版样式 */
.drawing-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    cursor: crosshair;
}

.mask-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
}

.drawing-mask canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 11;
}

/* 右键菜单样式 */
.context-menu {
    position: fixed;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
    min-width: 120px;
}

.menu-item {
    padding: 8px 12px;
    cursor: pointer;
    color: #606266;
}

.menu-item:hover {
    background-color: #f5f7fa;
    color: #409eff;
}

/* 上传弹窗样式 */
.upload-demo {
    text-align: center;
}

.el-upload__tip {
    margin-top: 15px;
    color: #666;
    font-size: 14px;
}

.el-icon--upload {
    font-size: 50px;
    color: #7cd0ff;
    margin: 20px 0;
}

.el-upload__text {
    font-size: 16px;
    color: #606266;
}

.el-upload__text em {
    color: #7cd0ff;
    font-style: normal;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}
</style>