<template>
  <div class="mark-container">
    <!-- 左侧区域 -->
    <el-aside class="left-container" width="320px">
      <!-- 项目选择器 -->
      <div class="project-selector">
        <el-select 
          v-model="selectedProjectId" 
          placeholder="请选择数据集" 
          @change="handleProjectChange"
          size="large"
          class="full-width"
        >
          <el-option
            v-for="project in projectList"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
      </div>
      
      <el-collapse v-model="activeLeftPanels" accordion class="custom-collapse">
        <!-- 项目信息面板 -->
        <el-collapse-item title="数据集信息" name="projectInfo">
          <div v-if="currentProject" class="project-info">
            <el-descriptions :column="1" size="small" :border="true">
              <el-descriptions-item label="项目名称">
                <span class="project-name">{{ currentProject.name }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="项目描述">
                <span class="project-desc">{{ currentProject.description || '暂无描述' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                <span class="project-time">{{ formatTimestamp(currentProject.createTime) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="识别类型">
                <dict-tag :type="DICT_TYPE.VISUAL_TYPE" :value="currentProject.type" />
              </el-descriptions-item>
              <el-descriptions-item label="标注进度">
                <div class="progress-info">
                  <el-progress 
                    :percentage="imageList.length > 0 ? Math.round((imageList.filter(img => img.status === 1).length / imageList.length) * 100) : 0" 
                    :show-text="true" 
                  />
                  <div class="progress-text">
                    {{ imageList.filter(img => img.status === 1).length }} / {{ imageList.length }}
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div v-else class="empty-state">
            <el-empty description="请选择数据集" :image-size="80" />
          </div>
        </el-collapse-item>

        <!-- 标注类型面板 -->
        <el-collapse-item title="标注类型" name="types">
          <div class="type-header">
            <el-button type="primary" size="small" @click="showAddTypeDialog" class="add-type-btn">
              <Icon icon="ep:plus" /> 新增类型
            </el-button>
          </div>
          <el-scrollbar class="left-scrollbar">
            <div class="type-list">
              <div 
                v-for="type in annotationTypes" 
                :key="type.id" 
                class="type-item"
              >
                <div class="type-color" :style="{ backgroundColor: type.color }"></div>
                <div class="type-name">{{ type.name }}</div>
                <div class="type-actions">
                  <el-button 
                    link 
                    type="danger" 
                    size="small" 
                    @click="deleteAnnotationType(type.id)"
                    class="delete-btn"
                  >
                    <Icon icon="ep:delete" />
                  </el-button>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-collapse-item>

        <!-- 标注结果面板 -->
        <el-collapse-item title="标注结果" name="results">
          <el-scrollbar class="left-scrollbar">
            <div class="annotation-list">
              <div 
                v-for="(annotation, index) in annotations" 
                :key="annotation.id" 
                class="annotation-item"
              >
                <div class="annotation-header">
                  <el-select 
                    v-model="annotation.classId" 
                    placeholder="选择类型"
                    size="small"
                    @change="(value) => setAnnotationType(index, value)"
                    class="type-select"
                  >
                    <el-option
                      v-for="type in annotationTypes"
                      :key="type.id"
                      :label="type.name"
                      :value="type.id"
                    />
                  </el-select>
                  <el-button 
                    link 
                    type="danger" 
                    size="small"
                    @click="deleteAnnotation(annotation, index)"
                    class="delete-annotation"
                  >
                    <Icon icon="ep:close" />
                  </el-button>
                </div>
                <div class="annotation-coords">
                  <div class="coord-item">
                    <Icon icon="ep:location" />
                    <span>中心: ({{ Math.round(annotation.centerX) }}, {{ Math.round(annotation.centerY) }})</span>
                  </div>
                  <div class="coord-item">
                    <Icon icon="ep:full-screen" />
                    <span>尺寸: {{ Math.round(annotation.width) }} × {{ Math.round(annotation.height) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-collapse-item>
      </el-collapse>
    </el-aside>

    <!-- 中间区域：图片标注区域 -->
    <el-main class="center-container">
      <!-- 检测模式：使用 OpenSeadragon + Annotorious -->
      <template v-if="currentProject && currentProject.type === '1'">
        <!-- 右上角按钮组 -->
        <div v-if="currentImage" class="top-right-buttons">
          <el-button 
            :type="isAnnotationMode ? 'warning' : 'primary'" 
            size="small" 
            @click="toggleAnnotationMode"
            class="annotation-toggle"
          >
            <Icon :icon="isAnnotationMode ? 'ep:close' : 'ep:edit'" />
            {{ isAnnotationMode ? '移动' : '标注' }}
          </el-button>
          <el-button 
            :type="isCopyMode ? 'success' : 'info'" 
            size="small" 
            @click="toggleCopyMode"
            class="copy-toggle"
          >
            <Icon icon="ep:copy-document" />
            {{ isCopyMode ? '取消复制' : '复制' }}
          </el-button>
        </div>
        
        <div ref="annotatorContainer" class="annotator-wrapper" id="openseadragon-container">
          <!-- OpenSeadragon 容器 -->
        </div>
      </template>

      <!-- 分类模式：简化的单标签标注 -->
      <template v-else-if="currentProject && currentProject.type === '2'">
        <div v-if="currentImage" class="classification-container">
          <!-- 图片显示区域 -->
          <div class="classification-image-wrapper">
            <img 
              :src="currentImage.path" 
              :alt="currentImage.name" 
              class="classification-image"
              @error="handleImageError"
            />
          </div>
          
          <!-- 滚动条式分类选择区域 -->
          <div class="classification-controls-scroll">
            <div class="classification-prompt">
              <span>选择分类</span>
            </div>
            <div class="classification-scroll">
              <el-scrollbar>
                <el-radio-group 
                  v-model="selectedClassificationType" 
                  @change="handleClassificationChange"
                  class="type-radio-group-scroll"
                >
                  <el-radio 
                    v-for="type in annotationTypes" 
                    :key="type.id"
                    :label="type.id"
                    class="type-radio-scroll"
                  >
                    <div class="type-radio-content-scroll">
                      <div class="type-color" :style="{ backgroundColor: type.color }"></div>
                      <span class="type-name">{{ type.name }}</span>
                    </div>
                  </el-radio>
                </el-radio-group>
              </el-scrollbar>
            </div>
            
            <div class="classification-status-scroll">
              <el-tag 
                v-if="selectedClassificationType" 
                :type="getTypeTagType(selectedClassificationType)"
                size="large"
              >
                {{ getTypeName(selectedClassificationType) }}
              </el-tag>
              <el-tag v-else type="info" size="large">未分类</el-tag>
            </div>
          </div>
        </div>
        <div v-else class="empty-classification">
          <el-empty description="请选择图片进行分类标注" :image-size="120" />
        </div>
      </template>

      <!-- 未选择项目时的提示 -->
      <div v-else class="empty-state-container">
        <el-empty description="请选择数据集开始标注" :image-size="120" />
      </div>
    </el-main>

    <!-- 右侧区域 -->
    <el-aside class="right-container" width="320px">
      <el-collapse v-model="activeRightPanels" accordion class="custom-collapse">
        <!-- 图片选择面板 -->
        <el-collapse-item title="图片选择" name="images">
          <el-scrollbar class="image-scrollbar">
            <div class="image-grid">
              <div
                v-for="image in imageList"
                :key="image.id"
                class="image-item"
                :class="{ active: currentImage && currentImage.id === image.id }"
                @click="selectImage(image)"
              >
                <div class="image-wrapper">
                  <img 
                    :src="image.path" 
                    :alt="image.name" 
                    class="thumbnail"
                    @error="handleImageError"
                  />
                  <div v-if="image.status === 1" class="status-indicator completed">
                    <Icon icon="ep:check" />
                  </div>
                </div>
                <div class="image-name">{{ image.name }}</div>
              </div>
            </div>
          </el-scrollbar>
        </el-collapse-item>
      </el-collapse>
    </el-aside>
  </div>
  
  <!-- 添加类型对话框 -->
  <el-dialog 
    v-model="addTypeDialogVisible" 
    title="添加标注类型" 
    width="450px"
    :close-on-click-modal="false"
  >
    <el-form :model="newTypeForm" ref="typeFormRef" label-width="100px" :rules="typeFormRules">
      <el-form-item label="类型名称" prop="name">
        <el-input 
          v-model="newTypeForm.name" 
          placeholder="请输入类型名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="类型颜色" prop="color">
        <div class="color-picker-wrapper">
          <el-color-picker 
            v-model="newTypeForm.color" 
            show-alpha
            :predefine="predefineColors"
          />
          <el-button 
            size="small" 
            @click="newTypeForm.color = generateRandomColor()"
            class="random-color-btn"
          >
            随机颜色
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addTypeDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addAnnotationType">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { MarkApi } from '@/api/annotation/mark'
import { createImageAnnotator } from '@annotorious/annotorious';
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/web/useMessage'
import { DICT_TYPE } from '@/utils/dict'

// 在响应式数据部分添加默认类型ID
const defaultTypeId = ref<number | null>(null);
const message = useMessage()

// 在其他ref声明后面添加
const route = useRoute()
// Import essential CSS styles
import '@annotorious/annotorious/annotorious.css';
import OpenSeadragon from 'openseadragon';
import { createOSDAnnotator } from '@annotorious/openseadragon';

// Import essential CSS styles
import '@annotorious/openseadragon/annotorious-openseadragon.css';
// 在 script setup 中添加颜色生成相关函数
const usedColors: string[] = [];
// 在响应式数据部分添加
let annoInstance = null
let viewerInstance = null
// 添加响应式数据
const isAnnotationMode = ref(true);
const isCopyMode = ref(false);
const copiedAnnotations = ref<Annotation[]>([]);
// 切换标注模式
const toggleAnnotationMode = () => {
  if (!annoInstance) return;
  
  isAnnotationMode.value = !isAnnotationMode.value;
  
  if (isAnnotationMode.value) {
    // 启用标注模式
    annoInstance.setDrawingEnabled(true);
  } else {
    // 禁用标注模式
    annoInstance.setDrawingEnabled(false);
  }
};

// 切换复制模式
const toggleCopyMode = () => {
  if (!isCopyMode.value) {
    // 进入复制模式，备份当前标注
    copiedAnnotations.value = JSON.parse(JSON.stringify(annotations.value));
    console.log('备份标注:', copiedAnnotations.value);
  } else {
    // 退出复制模式，清空备份
    copiedAnnotations.value = [];
  }
  isCopyMode.value = !isCopyMode.value;
};

// 修改初始化 annotorious 的方法，添加更多事件监听器

// 修改 initAnnotorious 函数，在创建 annoInstance 后添加：
// 修改 initAnnotorious 函数
const initAnnotorious = async () => {
  await nextTick();
  if (currentImage.value && annotatorContainer.value) {
    // 销毁之前的实例
    if (annoInstance) {
      annoInstance.destroy();
      annoInstance = null;
    }
    
    // 销毁之前的 OpenSeadragon 实例
    if (viewerInstance) {
      viewerInstance.destroy();
      viewerInstance = null;
    }
    
    // 清空容器
    if (annotatorContainer.value) {
      annotatorContainer.value.innerHTML = '';
    }
    
    // 初始化 OpenSeadragon
    viewerInstance = OpenSeadragon({
      element: annotatorContainer.value,
      prefixUrl: '/openseadragon/images/',
      tileSources: {
        type: 'image',
        url: currentImage.value.path
      },
      showNavigator: false,
      showRotationControl: true,
      showFlipControl: true,
      showHomeControl: true,
      showFullPageControl: true,
      showZoomControl: true,
      // 调整缩放参数
      minZoomLevel: 0.1,
      maxZoomLevel: 100,
      zoomPerScroll: 1.2,
      zoomPerClick: 2.0,
      gestureSettingsMouse: {
        clickToZoom: false,
        dblClickToZoom: false,
        pinchToZoom: true,
        flickEnabled: true,
        flickMinSpeed: 120,
        flickMomentum: 0.25
      },
      gestureSettingsTouch: {
        pinchToZoom: true,
        flickEnabled: true,
        flickMinSpeed: 120,
        flickMomentum: 0.25
      }
    });
    
    // 使用 OpenSeadragon 创建 Annotorious 实例
    annoInstance = createOSDAnnotator(viewerInstance, {
      locale: 'auto',
      theme: 'dark'
    });
    
    // 设置绘制模式
    annoInstance.setDrawingEnabled(isAnnotationMode.value);
    
    // 添加事件监听器
    annoInstance.on('createAnnotation', handleAnnotationCreated);
    annoInstance.on('updateAnnotation', handleAnnotationUpdated);
    annoInstance.on('deleteAnnotation', handleAnnotationDeleted);
    annoInstance.on('clickAnnotation', handleClickAnnotation);
    annoInstance.on('selectionChanged', handleSelectionChanged);
    
    // 等待图像加载完成后加载标注
    viewerInstance.addHandler('open', () => {
      console.log('图像加载完成，开始加载标注');
      setTimeout(() => {
        loadExistingAnnotations();
      }, 100);
    });
  }
};
// 删除标注
const deleteAnnotation = async (annotation: any, index: number) => {
  try {
    // 从 Annotorious 中删除标注
    if (annoInstance && annotation.annotationData) {
      annoInstance.removeAnnotation(annotation.annotationData);
    }
    
    // 从本地标注列表中删除
    annotations.value.splice(index, 1);
    
    // 如果需要，可以调用后端API删除标注
    // await MarkApi.deleteMark(annotation.id);
    
    console.log('删除成功');
  } catch (error) {
    console.error('删除标注失败:', error);
    alert('删除失败');
  }
};
// 生成HSL颜色，确保颜色差异较大
const generateDistinctColor = () => {
  // 预定义一些色相值，确保颜色分布均匀
  const hueSteps = 50;
  const saturation = Math.floor(Math.random() * 40) + 60; // 60-100%
  const lightness = Math.floor(Math.random() * 30) + 40;  // 40-70%
  
  // 如果已使用的颜色少于50个，使用均匀分布的色相
  if (usedColors.length < 50) {
    const hue = Math.floor((usedColors.length * 360) / hueSteps) % 360;
    const color = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
    usedColors.push(color);
    return color;
  } else {
    // 超过50个后使用随机色相
    const hue = Math.floor(Math.random() * 360);
    return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  }
}

// HSL转HEX颜色格式
const hslToHex = (h: number, s: number, l: number) => {
  l /= 100;
  const a = s * Math.min(l, 1 - l) / 100;
  const f = n => {
    const k = (n + h / 30) % 12;
    const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
    return Math.round(255 * color).toString(16).padStart(2, '0');
  };
  return `#${f(0)}${f(8)}${f(4)}`;
}
// 修改 generateRandomColor 函数，排除已存在的颜色
const generateRandomColor = () => {
  // 预定义一组高对比度的基础颜色
  const baseColors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
    '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
    '#F8C471', '#82E0AA', '#F1948A', '#85C1E9', '#D7BDE2',
    '#A3E4D7', '#FAD7A0', '#D5A6BD', '#AED6F1', '#A9DFBF',
    '#F9E79F', '#D2B4DE', '#AED6F1', '#A2D9CE', '#FADBD8',
    '#EBDEF0', '#D6EAF8', '#D1F2EB', '#FCF3CF', '#FDEDEC',
    '#52BE80', '#F4D03F', '#E67E22', '#D35400', '#8E44AD',
    '#2980B9', '#1ABC9C', '#F39C12', '#D35400', '#C0392B',
    '#16A085', '#27AE60', '#F1C40F', '#E67E22', '#9B59B6',
    '#3498DB', '#2ECC71', '#F1C40F', '#E74C3C', '#9B59B6'
  ];
  
  // 获取当前已存在的颜色
  const existingColors = annotationTypes.value.map(type => type.color);
  
  // 过滤掉已存在的颜色
  const availableColors = baseColors.filter(color => !existingColors.includes(color));
  
  // 如果已使用的颜色少于50个，且还有可用颜色，优先使用预定义颜色
  if (usedColors.length < 50 && availableColors.length > 0) {
    // 从可用颜色中选择一个
    const color = availableColors[usedColors.length % availableColors.length];
    usedColors.push(color);
    return color;
  } else if (usedColors.length < 50 && availableColors.length === 0 && existingColors.length < baseColors.length) {
    // 如果所有预定义颜色都被使用了，但总数还没达到预定义颜色数量，使用均匀分布色相
    const hueSteps = 50;
    const saturation = Math.floor(Math.random() * 40) + 60; // 60-100%
    const lightness = Math.floor(Math.random() * 30) + 40;  // 40-70%
    const hue = Math.floor((usedColors.length * 360) / hueSteps) % 360;
    const color = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
    usedColors.push(color);
    return color;
  } else {
    // 超过50个后或没有可用预定义颜色时生成随机颜色
    let attempts = 0;
    let newColor;
    do {
      const hue = Math.floor(Math.random() * 360);
      const saturation = Math.floor(Math.random() * 40) + 60; // 60-100%
      const lightness = Math.floor(Math.random() * 30) + 40;  // 40-70%
      newColor = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
      attempts++;
      // 避免无限循环，最多尝试10次
    } while (existingColors.includes(newColor) && attempts < 10);
    
    return newColor;
  }
}
// 类型定义
interface Project {
  id: number
  name: string
  description: string
  createTime: string
  path: string
  count: number
  type: string
  progress: number
}

interface Image {
  id: number
  name: string
  path: string
  dataId: number
  annotation: Array<{
    class_id: number
    center_x: number
    center_y: number
    width: number
    height: number
    polygon_points: string
    angle: string
  }>
  status: number
}

interface AnnotationType {
  id: number
  name: string
  color: string
  dataId: number
  index: number
}
// 添加 Annotation 接口定义
interface Annotation {
  id: number;
  classId: number;
  className: string;
  markId: number;
  centerX: number;
  centerY: number;
  width: number;
  height: number;
  polygon_points: number;
  anagle: number;
  dataId: number;
  annotationData: any; // 根据实际需要定义具体类型
}

// 响应式数据
const selectedProjectId = ref<number | undefined>(undefined)
const currentProject = ref<Project | null>(null)
const currentImage = ref<Image | null>(null)
const projectList = ref<Project[]>([])
const imageList = ref<Image[]>([])
const annotationTypes = ref<AnnotationType[]>([])
const annotations = ref<Annotation[]>([])

// 分类模式相关数据
const selectedClassificationType = ref<number | null>(null)
const classificationAnnotations = ref<{ [key: number]: number }>({}) // 图片ID -> 类型ID的映射
const globalClassificationType = ref<number | null>(null) // 全局分类类型，切换图片时保持


// 添加类型对话框相关
const addTypeDialogVisible = ref(false)
const newTypeForm = reactive({
  name: '',
  color: '#409EFF',
  dataId: 0
})
const typeFormRef = ref()

// 表单验证规则
const typeFormRules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择颜色', trigger: 'change' }
  ]
}

// 预定义颜色
const predefineColors = [
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  '#409eff',
  '#67c23a',
  '#e6a23c',
  '#f56c6c',
  '#909399'
]

// 图片错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 隐藏图片元素，不显示占位符
  img.style.display = 'none'
}

// 折叠面板控制
const activeLeftPanels = ref(['project'])
const activeRightPanels = ref(['images'])

// DOM引用
const annotatorContainer = ref<HTMLElement | null>(null)
const annotatorImage = ref<HTMLImageElement | null>(null)
// 在 script setup 中添加时间格式化函数
// 修改时间格式化函数
const formatTimestamp = (timestamp: string) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 获取项目列表
const getProjectList = async () => {
  try {
    // 调用实际API获取项目列表
    const response = await MarkApi.getProjectList()
    projectList.value = response
    console.log(projectList.value)
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}
// 项目选择变更处理
const handleProjectChange = async (projectId: number) => {
  // 查找选中的项目
  currentProject.value = projectList.value.find(p => p.id === projectId) || null
  
  if (currentProject.value) {
    // 获取该项目下的图片列表和标注类型
    await Promise.all([
      getImageList(projectId),
      getAnnotationTypes(projectId)
    ])
  }
}

// 更新图片状态
const updateImageStatus = async (imageId: number, status: number) => {
  try {
    // 假设有一个更新图片状态的API
    await MarkApi.updateImageStatus({ id: imageId, status: status })
    // 更新本地数据
    const image = imageList.value.find(img => img.id === imageId)
    if (image) {
      image.status = status
    }
  } catch (error) {
    console.error('更新图片状态失败:', error)
  }
}
// 获取图片列表
const getImageList = async (projectId: number) => {
  try {
    const response = await MarkApi.getImageList({ dataId: projectId })
    
      imageList.value = response
      console.log(imageList.value);
      
  } catch (error) {
    console.error('获取图片列表失败:', error)
  }
}

// 获取标注类型列表
const getAnnotationTypes = async (projectId: number) => {
  try {
    const response = await MarkApi.getTypeList({ dataId: projectId })
    annotationTypes.value = response
  } catch (error) {
    console.error('获取标注类型失败:', error)
  }
}

// 图片有效性检查函数
const checkImageValidity = (imageUrl: string): Promise<boolean> => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    img.src = imageUrl;
  });
}



// 分类模式：处理分类选择变化
const handleClassificationChange = async (typeId: number) => {
  if (!currentImage.value) return;
  
  // 保存分类结果到当前图片
  classificationAnnotations.value[currentImage.value.id] = typeId;
  
  // 保存为全局分类类型，切换图片时保持
  globalClassificationType.value = typeId;
  
  // 创建分类标注数据
  const classificationAnnotation = {
    id: Date.now(),
    classId: typeId,
    className: getTypeName(typeId),
    markId: currentImage.value.id,
    centerX: 0,
    centerY: 0,
    width: 0,
    height: 0,
    polygon_points: 0,
    anagle: 0,
    dataId: currentImage.value.id,
    annotationData: {
      type: 'classification',
      typeId: typeId
    }
  };
  
  try {
    // 保存分类标注
    await MarkApi.createMarkInfo([classificationAnnotation]);
    
    // 更新图片状态为已完成
    currentImage.value.status = 1;
    const imageInList = imageList.value.find(img => img.id === currentImage.value?.id);
    if (imageInList) {
      imageInList.status = 1;
    }
    
    // 调用API更新图片状态
    await MarkApi.updateImageStatus({ id: currentImage.value.id, status: 1 });
    
    console.log('分类标注保存成功');
  } catch (error) {
    console.error('保存分类标注失败:', error);
  }
};

// 获取类型名称
const getTypeName = (typeId: number): string => {
  const type = annotationTypes.value.find(t => t.id === typeId);
  return type ? type.name : '未知类型';
};

// 获取类型标签样式
const getTypeTagType = (typeId: number): string => {
  const type = annotationTypes.value.find(t => t.id === typeId);
  if (!type) return 'info';
  
  // 根据颜色返回不同的标签类型
  const color = type.color.toLowerCase();
  if (color.includes('#67c23a') || color.includes('green')) return 'success';
  if (color.includes('#e6a23c') || color.includes('orange')) return 'warning';
  if (color.includes('#f56c6c') || color.includes('red')) return 'danger';
  return 'primary';
};

// 加载分类模式的已有标注
const loadClassificationAnnotation = async () => {
  if (!currentImage.value) return;
  
  try {
    const res = await MarkApi.getMarkInfoList(currentImage.value.id);
    if (res && res.length > 0) {
      // 分类模式只有一个标注，取第一个
      const annotation = res[0];
      selectedClassificationType.value = annotation.classId;
      classificationAnnotations.value[currentImage.value.id] = annotation.classId;
      // 更新全局分类类型
      globalClassificationType.value = annotation.classId;
    } else {
      // 如果没有已有标注，且当前图片状态为0（未标注），使用全局分类类型
      if (currentImage.value.status === 0) {
        selectedClassificationType.value = globalClassificationType.value;
      } else {
        selectedClassificationType.value = null;
      }
    }
  } catch (error) {
    console.error('获取分类标注失败:', error);
    // 出错时，如果当前图片状态为0，使用全局分类类型
    if (currentImage.value && currentImage.value.status === 0) {
      selectedClassificationType.value = globalClassificationType.value;
    } else {
      selectedClassificationType.value = null;
    }
  }
};

// 修改 selectImage 函数
const selectImage = async (image: Image) => {
  // 处理当前图片的保存逻辑（适用于检测模式）
  if (currentProject.value && currentProject.value.type === '1' && annotations.value && annotations.value.length > 0) {
    try {
      await MarkApi.createMarkInfo(annotations.value);
      
      // 保存成功后，更新当前图片状态为已完成
      if (currentImage.value) {
        currentImage.value.status = 1;
        
        // 更新图片列表中的状态
        const imageInList = imageList.value.find(img => img.id === currentImage.value?.id);
        if (imageInList) {
          imageInList.status = 1;
        }
        
        // 调用API更新图片状态
        try {
          await MarkApi.updateImageStatus({ id: currentImage.value.id, status: 1 });
        } catch (updateError) {
          console.error('更新图片状态失败:', updateError);
        }
      }
    } catch (error) {
      console.error('保存标注信息失败:', error);
    }
    
    // 清空当前标注列表
    annotations.value = [];
  } else if (currentProject.value && currentProject.value.type === '2' && selectedClassificationType.value) {
    // 分类模式：当前已有分类选择，保存当前状态
    try {
      const classificationAnnotation = {
        id: Date.now(),
        classId: selectedClassificationType.value,
        className: getTypeName(selectedClassificationType.value),
        markId: currentImage.value?.id,
        centerX: 0,
        centerY: 0,
        width: 0,
        height: 0,
        polygon_points: 0,
        anagle: 0,
        dataId: currentImage.value?.id || 0,
        annotationData: {
          type: 'classification',
          typeId: selectedClassificationType.value
        }
      };
      
      await MarkApi.createMarkInfo([classificationAnnotation]);
      
      // 更新图片状态
      if (currentImage.value) {
        currentImage.value.status = 1;
        const imageInList = imageList.value.find(img => img.id === currentImage.value?.id);
        if (imageInList) {
          imageInList.status = 1;
        }
        await MarkApi.updateImageStatus({ id: currentImage.value.id, status: 1 });
      }
    } catch (error) {
      console.error('保存分类标注失败:', error);
    }
  }
  
  // 检查图片是否有效
  const isValid = await checkImageValidity(image.path);
  if (!isValid) {
    console.error('图片无效或加载失败:', image.path);
    // 清空容器，不显示任何控件
    if (annotatorContainer.value) {
      annotatorContainer.value.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">图片加载失败</div>';
    }
    currentImage.value = image;
    return;
  }
  
  currentImage.value = image;
  
  // 根据项目类型执行不同的初始化
  if (currentProject.value) {
    if (currentProject.value.type === '1') {
      // 检测模式：初始化 annotorious 并加载标注
      annotations.value = [];
      await initAnnotorious();
    } else if (currentProject.value.type === '2') {
      // 分类模式：加载已有分类标注
      await loadClassificationAnnotation();
    }
  }
};




// 修改 handleAnnotationCreated 函数
const handleAnnotationCreated = (annotation: any) => {
  console.log('创建标注:', annotation);
  // 解析标注位置信息
  const positionInfo = parseAnnotationPosition(annotation);
  console.log(positionInfo);
  
  if (positionInfo) {
    // 如果有默认类型，使用默认类型
    let classId = null;
    let className = '未分类';
    let typeColor = null;
    
    if (defaultTypeId.value) {
      console.log(defaultTypeId.value);
      
      const type = annotationTypes.value.find(t => t.id === defaultTypeId.value);
      if (type) {
        classId = defaultTypeId.value;
        className = type.name;
        typeColor = type.color;
      }
    }
    
    // 添加到标注结果列表
    const newAnnotation: Annotation = {
      id: Date.now(),
      classId: classId,
      className: className,
      markId: currentImage.value?.id,
      centerX: positionInfo.center_x,
      centerY: positionInfo.center_y,
      width: positionInfo.width,
      height: positionInfo.height,
      polygon_points: 0,
      anagle: 0,
      dataId: currentImage.value?.id || 0,
      annotationData: annotation
    };
    
    annotations.value.push(newAnnotation);
    console.log(newAnnotation);
    
    // 如果有默认类型，更新标注颜色
    if (classId && typeColor && annoInstance) {
      // 确保颜色值是字符串格式
      const colorString = typeof typeColor === 'string' ? typeColor : typeColor.toString();
      
      // 正确设置 annotation 的 bodies
      if (!annotation.bodies) {
        annotation.bodies = [];
      }
      if (annotation.bodies.length > 0) {
        annotation.bodies[0] = colorString;
      } else {
        annotation.bodies.push(colorString);
      }
      
      annoInstance.setStyle((annotationItem, state) => {
        if (annotationItem.bodies && annotationItem.bodies.length > 0) {
          let color = annotationItem.bodies[0];
          
          // 修复可能损坏的颜色数据结构
          if (typeof color === 'object' && color !== null) {
            if (!Array.isArray(color)) {
              // 对象形式，重组为字符串
              const keys = Object.keys(color).filter(k => k !== 'annotation').sort((a, b) => parseInt(a) - parseInt(b));
              color = keys.map(k => color[k]).join('');
            }
          }
          
          const colorValue = typeof color === 'string' ? color : color.toString();
          return {
            fill: colorValue,
            fillOpacity: 0.25,
            stroke: colorValue,
            strokeWidth: 2,
          };
        } else {
          return null;
        }
      });
    }
  }
};

// 处理标注更新事件
const handleAnnotationUpdated = (annotation: any, previous: any) => {
  console.log('更新标注:', annotation);
  // 解析标注位置信息
  const positionInfo = parseAnnotationPosition(annotation);
  if (positionInfo) {
    // 更新标注结果列表中的对应项
    const index = annotations.value.findIndex((item: any) => 
      item.annotationData && item.annotationData.id === annotation.id);
    if (index !== -1) {
      annotations.value[index] = {
        ...annotations.value[index],
        centerX: positionInfo.center_x,
        centerY: positionInfo.center_y,
        width: positionInfo.width,
        height: positionInfo.height,
        annotationData: annotation
      };
    }
  }
};

// 处理标注删除事件
const handleAnnotationDeleted = (annotation: any) => {
  console.log('删除标注:', annotation);
  // 从标注结果列表中移除
  const index = annotations.value.findIndex((item: any) => 
    item.annotationData && item.annotationData.id === annotation.id);
  if (index !== -1) {
    annotations.value.splice(index, 1);
  }
};

// 处理点击标注事件
const handleClickAnnotation = (annotation: any, shape: any, sel: any) => {
  console.log('点击标注:', annotation);
  // 可以在这里实现标注选中后的操作，如高亮显示等
};

// 处理选择变化事件
const handleSelectionChanged = (selected: any[]) => {
  console.log('选择变化:', selected);
  // 可以在这里处理多选等操作
};

// 修复 parseAnnotationPosition 函数，确保能正确解析坐标
const parseAnnotationPosition = (annotation: any) => {
  try {
    // 处理 Annotorious 3 格式 - geometry 方式
    
    if (annotation.target?.selector?.geometry) {
      const geometry = annotation.target.selector.geometry;
        console.log('Rectangle geometry:', annotation.target.selector.type);
      if (annotation.target.selector.type === 'RECTANGLE') {
        // Rectangle 格式: { type: 'Rectangle', coordinates: [x, y, width, height] }
        
        // const [x, y, width, height] = geometry.coordinates;
        return {
          center_x: geometry.x,
          center_y: geometry.y,
          width: geometry.w,
          height: geometry.h
        };
      } else if (geometry.type === 'Polygon') {
        // Polygon 格式处理
        const coordinates = geometry.coordinates[0]; // 外环坐标
        if (coordinates.length >= 4) {
          // 计算边界框
          let minX = Math.min(...coordinates.map((p: number[]) => p[0]));
          let maxX = Math.max(...coordinates.map((p: number[]) => p[0]));
          let minY = Math.min(...coordinates.map((p: number[]) => p[1]));
          let maxY = Math.max(...coordinates.map((p: number[]) => p[1]));
          
          return {
            center_x: (minX + maxX) / 2,
            center_y: (minY + maxY) / 2,
            width: maxX - minX,
            height: maxY - minY
          };
        }
      }
    }
    
    // 处理 FragmentSelector 格式
    if (annotation.target?.selector?.type === 'FragmentSelector' && annotation.target?.selector?.value) {
      const selector = annotation.target.selector;
      // 解析 xywh 格式坐标 "xywh=pixel:x,y,width,height"
      const coords = selector.value.replace('xywh=pixel:', '').split(',');
      if (coords.length === 4) {
        const [x, y, width, height] = coords.map(Number);
        return {
          center_x: x + width / 2,
          center_y: y + height / 2,
          width: width,
          height: height
        };
      }
    }
    
    // 处理其他可能的格式
    if (annotation.target?.selector?.conformsTo) {
      const selector = annotation.target.selector;
      if (selector.value) {
        const coords = selector.value.replace('xywh=pixel:', '').split(',');
        if (coords.length === 4) {
          const [x, y, width, height] = coords.map(Number);
          return {
            center_x: x + width / 2,
            center_y: y + height / 2,
            width: width,
            height: height
          };
        }
      }
    }
    
    console.warn('无法解析标注位置信息:', annotation);
    return null;
  } catch (error) {
    console.error('解析标注位置信息失败:', error);
    return null;
  }
};
// 修改 setAnnotationType 函数
const setAnnotationType = (annotationIndex: number, typeId: number) => {
  const type = annotationTypes.value.find(t => t.id === typeId);
  if (type && annoInstance) {
    // 更新标注结果列表中的类型信息
    annotations.value[annotationIndex].className = type.name;
    annotations.value[annotationIndex].color = type.color;
    annotations.value[annotationIndex].typeId = typeId;
    
    // 保存为默认类型
    defaultTypeId.value = typeId;
    
    // 更新 Annotorious 中对应标注的样式
    const annotationData = annotations.value[annotationIndex].annotationData;
    
    if (annotationData) {
      // 确保颜色值是字符串格式
      const colorValue = typeof type.color === 'string' ? type.color : type.color.toString();
      console.log('更新标注类型:', colorValue);
      // 确保 bodies 数组存在并正确设置颜色值
      if (!annotationData.bodies) {
        annotationData.bodies = [];
      }
      
      // 设置颜色值 - 确保是字符串而不是分解的字符数组
      if (annotationData.bodies.length > 0) {
        annotationData.bodies[0] = colorValue;
      } else {
        annotationData.bodies.push(colorValue);
      }
      
      // 为特定标注设置样式，而不是全局设置
      annoInstance.setStyle((annoData, state) => {
          // 修复可能损坏的颜色数据结构
          if (annoData.bodies && annoData.bodies.length > 0) {
            let color = annoData.bodies[0];
            console.log('color:', annoData);
            
            // 修复可能损坏的颜色数据结构
            if (typeof color === 'object' && color !== null) {
              if (typeof color === 'object' && !Array.isArray(color)) {
                // 对象形式，重组为字符串
                const keys = Object.keys(color).filter(k => k !== 'annotation').sort((a, b) => parseInt(a) - parseInt(b));
                color = keys.map(k => color[k]).join('');
              }
            }
            
            // 确保颜色值是字符串格式
            const finalColor = typeof color === 'string' ? color : color.toString();
            annoData.bodies[0] = finalColor;
            
            return {
              fill: finalColor,
              fillOpacity: 0.25,
              stroke: finalColor,
              strokeWidth: 2,
            };
          }
        
        // 对于其他标注，返回 undefined 或 null 将使用默认样式
        return undefined;
      });
      
      // 更新标注以应用新样式
      try {
        annoInstance.updateAnnotation(annotationData);
      } catch (error) {
        console.error('更新标注样式失败:', error);
      }
    }
    
    // console.log(annotations.value[annotationIndex]);
  }
};
// 替换 selectAnnotationOnImage 函数
const selectAnnotationOnImage = (annotation: any) => {
  if (annoInstance && annotation.annotationData) {
    // 使用 Annotorious 的正确 API 来选中标注
    try {
      // 先清除当前选择
      annoInstance.clearSelection();
      // 选中指定的标注
      annoInstance.selectAnnotation(annotation.annotationData.id);
      console.log('选中标注:', annotation);
    } catch (error) {
      console.error('选中标注失败:', error);
    }
  }
};
// 添加选择标注的函数
const selectAnnotation = (annotation: any) => {
  if (annoInstance && annotation.annotationData) {
    // 选中对应的标注
     // 触发标注点击事件
    // const event = new CustomEvent('annotationClicked', { detail: { annotation } });
    // annoInstance.getElement().dispatchEvent(event);
  }
};
// 加载已存在的标注（修改此函数以正确处理类型和颜色）
// 加载已存在的标注
// 修改 loadExistingAnnotations 函数
const loadExistingAnnotations = () => {
  console.log('当前图片:', currentImage.value);
  if (annoInstance && currentImage.value && currentImage.value.id) {
    MarkApi.getMarkInfoList(currentImage.value.id).then((res) => {
      if (res && res.length > 0) {
        console.log('获取到的标注数据:', res);
        
        // 清空当前标注列表
        annotations.value = [];
        
        res.forEach((item) => {
          console.log('处理单个标注:', item);
          
          // 确保 annotationData 存在
          if (item.annotationData) {
            try {
              // 添加标注到 Annotorious 实例
              annoInstance.addAnnotation(item.annotationData);
              
              // 查找对应的类型信息
              const annotationType = annotationTypes.value.find(t => t.id === item.classId);
              
              // 构建完整的标注对象
              const fullAnnotation: Annotation = {
                id: item.id || Date.now(),
                classId: item.classId,
                className: annotationType ? annotationType.name : '未知类型',
                markId: item.markId || currentImage.value?.id || 0,
                centerX: item.centerX,
                centerY: item.centerY,
                width: item.width,
                height: item.height,
                polygon_points: item.polygon_points || 0,
                anagle: item.anagle || 0,
                dataId: item.dataId || 0,
                annotationData: item.annotationData
              };
              
              annotations.value.push(fullAnnotation);
            } catch (error) {
              console.error('添加单个标注失败:', error, item);
            }
          }
        });
        
        console.log('最终标注列表:', annotations.value);
        
        // 如果有备份的标注，追加到现有标注后面
        if (copiedAnnotations.value && copiedAnnotations.value.length > 0) {
          console.log('追加备份标注:', copiedAnnotations.value);
          
          copiedAnnotations.value.forEach((copiedAnnotation) => {
            // 查找对应的类型信息以获取颜色
            const annotationType = annotationTypes.value.find(t => t.id === copiedAnnotation.classId);
            const color = annotationType ? annotationType.color : '#409eff';
            
            // 创建新的标注对象，更新ID和关联的图片ID
            const newAnnotation: Annotation = {
              ...copiedAnnotation,
              id: Date.now() + Math.random(), // 生成新的唯一ID
              markId: currentImage.value?.id || 0,
              dataId: currentImage.value?.id || 0,
              annotationData: { 
                ...copiedAnnotation.annotationData,
                // 确保颜色信息正确设置
                bodies: [color]
              }
            };
            
            // 添加到 Annotorious 实例
            if (annoInstance && newAnnotation.annotationData) {
              try {
                annoInstance.addAnnotation(newAnnotation.annotationData);
              } catch (error) {
                console.error('添加备份标注到 Annotorious 失败:', error);
              }
            }
            
            // 添加到标注列表
            annotations.value.push(newAnnotation);
          });
          
          console.log('追加后的标注列表:', annotations.value);
        }
        
        
      } else {
        // 没有标注数据时清空列表
        annotations.value = [];
        
        // 如果有备份的标注，直接添加
        if (copiedAnnotations.value && copiedAnnotations.value.length > 0) {
          console.log('直接添加备份标注:', copiedAnnotations.value);
          
          copiedAnnotations.value.forEach((copiedAnnotation) => {
            // 查找对应的类型信息以获取颜色
            const annotationType = annotationTypes.value.find(t => t.id === copiedAnnotation.classId);
            const color = annotationType ? annotationType.color : '#409eff';
            
            // 创建新的标注对象，更新ID和关联的图片ID
            const newAnnotation: Annotation = {
              ...copiedAnnotation,
              id: Date.now() + Math.random(), // 生成新的唯一ID
              markId: currentImage.value?.id || 0,
              dataId: currentImage.value?.id || 0,
              annotationData: { 
                ...copiedAnnotation.annotationData,
                // 确保颜色信息正确设置
                bodies: [color]
              }
            };
            
            // 添加到 Annotorious 实例
            if (annoInstance && newAnnotation.annotationData) {
              try {
                annoInstance.addAnnotation(newAnnotation.annotationData);
              } catch (error) {
                console.error('添加备份标注到 Annotorious 失败:', error);
              }
            }
            
            // 添加到标注列表
            annotations.value.push(newAnnotation);
          });
          
          console.log('添加备份标注后的列表:', annotations.value);
        }
      }
      annoInstance.setStyle((annotationItem, state) => {
        if (annotationItem.bodies && annotationItem.bodies.length > 0) {
          let color = annotationItem.bodies[0];
          
          // 修复可能损坏的颜色数据结构
          if (typeof color === 'object' && color !== null) {
            if (!Array.isArray(color)) {
              // 对象形式，重组为字符串
              const keys = Object.keys(color).filter(k => k !== 'annotation').sort((a, b) => parseInt(a) - parseInt(b));
              color = keys.map(k => color[k]).join('');
            }
          }
          
          const colorValue = typeof color === 'string' ? color : color.toString();
          return {
            fill: colorValue,
            fillOpacity: 0.25,
            stroke: colorValue,
            strokeWidth: 2,
          };
        } else {
          return null;
        }
      });
    }).catch(error => {
      console.error('获取标注信息失败:', error);
      annotations.value = [];
    });
  }
};
// 显示添加类型对话框
const showAddTypeDialog = () => {
  if (!selectedProjectId.value) {
    alert('请先选择项目')
    return
  }
  addTypeDialogVisible.value = true
  // 重置表单
  newTypeForm.name = ''
  newTypeForm.color = generateRandomColor() 
  newTypeForm.dataId = selectedProjectId.value
}

// 添加标注类型
const addAnnotationType = async () => {
  if (!typeFormRef.value) return
  
  try {
    await typeFormRef.value.validate()
    
    const response = await MarkApi.createType({
      name: newTypeForm.name,
      color: newTypeForm.color,
      dataId: newTypeForm.dataId
    })
    console.log(response);
    
      addTypeDialogVisible.value = false
      // 重新获取标注类型列表
      if (selectedProjectId.value) {
        await getAnnotationTypes(selectedProjectId.value)
      }
    
  } catch (error) {
    console.error('添加标注类型失败:', error)
    alert('添加失败')
  }
}

// 删除标注类型
const deleteAnnotationType = async (typeId: number) => {
  try {
    
      await MarkApi.deleteType(typeId)
      
        // 重新获取标注类型列表
        if (selectedProjectId.value) {
          await getAnnotationTypes(selectedProjectId.value)
        }
     
  } catch (error) {
    console.error('删除标注类型失败:', error)
    alert('删除失败')
  }
}

// 编辑标注
const editAnnotation = (annotation: any) => {
  console.log('编辑标注:', annotation)
  // 实现编辑逻辑
}

// 初始化
onMounted(() => {
  getProjectList().then(() => {
    // 检查路由参数中是否有id
    const projectId = route.query.id ? Number(route.query.id) : undefined
    if (projectId && projectList.value.some(p => p.id === projectId)) {
      selectedProjectId.value = projectId
      handleProjectChange(projectId)
    }
  })
})
// 清理资源
/**
 * 销毁现有的标注实例
 * 如果存在标注实例(annoInstance)，则调用其destroy方法并置为null
 */
onUnmounted(() => {
  if (annoInstance) {
    annoInstance.destroy();
    annoInstance = null;
  }
  if (viewerInstance) {
    viewerInstance.destroy();
    viewerInstance = null;
  }
});
</script>

<style scoped lang="scss">
.mark-container {
  display: flex;
  height: 90vh;
  background: #f5f5f5;
  gap: 16px;
  padding: 16px;
  box-sizing: border-box;
}

.left-container,
.right-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  .custom-collapse {
    :deep(.el-collapse-item__header) {
      font-weight: 600;
      padding: 16px 20px;
      background: #f8f9fa;
      color: #303133;
      border: none;
      margin-bottom: 1px;
      
      &:hover {
        background: #ecf5ff;
      }
    }
    
    :deep(.el-collapse-item__content) {
      padding: 20px;
      background: white;
    }
    
    :deep(.el-collapse-item__arrow) {
      color: #606266;
      font-weight: bold;
    }
  }
}

.center-container {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  
  .image-info {
    position: absolute;
    top: 16px;
    left: 16px;
    z-index: 100;
    background: rgba(255, 255, 255, 0.9);
    padding: 8px 12px;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .image-name {
      font-weight: 500;
      color: #303133;
    }
  }
  
  .top-right-buttons {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 100;
    display: flex;
    gap: 8px;
    
    .annotation-toggle {
      background: #409eff;
      border: none;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
      }
      
      &.el-button--warning {
        background: #e6a23c;
        box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
        
        &:hover {
          box-shadow: 0 4px 12px rgba(230, 162, 60, 0.4);
        }
      }
    }
    
    .copy-toggle {
      background: #909399;
      border: none;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(144, 147, 153, 0.3);
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(144, 147, 153, 0.4);
      }
      
      &.el-button--success {
        background: #67c23a;
        box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
        
        &:hover {
          box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
        }
      }
    }
  }
  
  .annotator-wrapper {
    flex: 1;
    width: 100%;
    height: 100%;
    position: relative;
    border-radius: 8px;
    overflow: hidden;
  }
  
  #openseadragon-container {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    overflow: hidden;
  }
}

// 项目选择器
.project-selector {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px 12px 0 0;
  border-bottom: 1px solid #e9ecef;
  
  .full-width {
    width: 100%;
    
    :deep(.el-input__wrapper) {
      background: white;
      border: 1px solid #dcdfe6;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
    }
  }
}

// 项目信息
.project-info {
  .project-name {
    font-weight: 600;
    color: #303133;
  }
  
  .project-desc {
    color: #606266;
    line-height: 1.4;
  }
  
  .project-time {
    color: #909399;
    font-size: 12px;
  }
}

.empty-state {
  text-align: center;
  padding: 20px;
}

// 类型列表
.type-header {
  margin-bottom: 16px;
  text-align: right;
  
  .add-type-btn {
    background: #409eff;
    border: none;
    border-radius: 6px;
    padding: 8px 16px;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    
    &:hover {
      background: #337ecc;
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
    }
  }
}

.type-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.type-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
  
  &:hover {
    background: #e9ecef;
    transform: translateX(4px);
  }
  
  .type-color {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border: 2px solid white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    margin-right: 12px;
  }
  
  .type-name {
    flex: 1;
    font-weight: 500;
    color: #303133;
  }
  
  .type-actions {
    .delete-btn {
      color: #f56c6c;
      
      &:hover {
        background: rgba(245, 108, 108, 0.1);
      }
    }
  }
}

// 标注结果
.annotation-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.annotation-item {
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  padding: 12px;
  transition: all 0.3s ease;
  
  &:hover {
    background: #e9ecef;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  .annotation-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    
    .type-select {
      flex: 1;
    }
    
    .delete-annotation {
      color: #f56c6c;
      
      &:hover {
        background: rgba(245, 108, 108, 0.1);
      }
    }
  }
  
  .annotation-coords {
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    .coord-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 12px;
      color: #606266;
      
      .el-icon {
        color: #909399;
      }
    }
  }
}

// 进度信息
.progress-info {
  .el-progress {
    margin-bottom: 4px;
  }
  
  .progress-text {
    font-size: 12px;
    color: #606266;
    text-align: center;
  }
}

// 图片网格
.image-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.image-item {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  
  &:hover {
    border-color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(64, 158, 255, 0.2);
  }
  
  &.active {
    border-color: #409eff;
    background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(64, 158, 255, 0.05) 100%);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
  
  .image-wrapper {
    position: relative;
    width: 100%;
    height: 100px;
    overflow: hidden;
    border-radius: 6px;
    background: #f5f7fa;
    
    .thumbnail {
      width: 100%;
      height: 100%;
      object-fit: contain;
      transition: transform 0.3s ease;
    }
    
    &:hover .thumbnail {
      transform: scale(1.05);
    }
    
    .status-indicator {
      position: absolute;
      bottom: 6px;
      right: 6px;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 14px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      
      &.completed {
        background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
      }
    }
  }
  
  .image-name {
    text-align: center;
    margin-top: 8px;
    font-size: 12px;
    font-weight: 500;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}



// 滚动条样式
.left-scrollbar {
  height: 60vh;
  
  :deep(.el-scrollbar__bar) {
    &.is-vertical {
      width: 6px;
      
      .el-scrollbar__thumb {
        background: rgba(144, 147, 153, 0.3);
        border-radius: 3px;
        
        &:hover {
          background: rgba(144, 147, 153, 0.5);
        }
      }
    }
  }
}

.image-scrollbar {
  height: calc(100vh - 200px);
  
  :deep(.el-scrollbar__bar) {
    &.is-vertical {
      width: 6px;
      
      .el-scrollbar__thumb {
        background: rgba(144, 147, 153, 0.3);
        border-radius: 3px;
        
        &:hover {
          background: rgba(144, 147, 153, 0.5);
        }
      }
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  
  .el-dialog__header {
    background: #f8f9fa;
    color: #303133;
    padding: 20px 24px;
    border-bottom: 1px solid #e9ecef;
    
    .el-dialog__title {
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    padding: 24px;
  }
}

.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .random-color-btn {
    background: #909399;
    border: none;
    color: white;
    border-radius: 6px;
    padding: 8px 16px;
    
    &:hover {
      background: #764ba2;
      transform: translateY(-1px);
    }
  }
}

// 分类模式样式
.classification-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  gap: 20px;
}

.classification-image-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 12px;
  overflow: hidden;
  min-height: 400px;
  
  .classification-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
}

// 滚动条式分类控制区域
.classification-controls-scroll {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  .classification-prompt {
    margin-bottom: 16px;
    text-align: center;
    
    span {
      color: #303133;
      font-weight: 600;
      font-size: 18px;
    }
  }
  
  .classification-scroll {
    margin-bottom: 16px;
    
    :deep(.el-scrollbar) {
      .el-scrollbar__wrap {
        overflow-x: auto;
      }
    }
    
    .type-radio-group-scroll {
      display: flex;
      gap: 8px;
      padding: 4px 0;
      flex-wrap: nowrap;
      
      .type-radio-scroll {
        margin: 0;
        padding: 6px 10px;
        border: 2px solid #e9ecef;
        border-radius: 6px;
        transition: all 0.3s ease;
        background: white;
        flex-shrink: 0;
        min-width: 70px;
        max-width: 100px;
        
        &:hover {
          border-color: #409eff;
          background: #f0f9ff;
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
        }
        
        &.is-checked {
          border-color: #409eff;
          background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(64, 158, 255, 0.05) 100%);
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
          transform: translateY(-1px);
        }
        
        :deep(.el-radio__input) {
          display: none;
        }
        
        :deep(.el-radio__label) {
          padding: 0;
          width: 100%;
        }
        
        .type-radio-content-scroll {
          display: flex;
          align-items: center;
          gap: 6px;
          width: 100%;
          justify-content: center;
          
          .type-color {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            border: 1px solid white;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
            flex-shrink: 0;
          }
          
          .type-name {
            font-weight: 500;
            color: #303133;
            font-size: 11px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: center;
            line-height: 1.1;
            max-width: 70px;
          }
        }
      }
    }
  }
  
  .classification-status-scroll {
    text-align: center;
    padding-top: 12px;
    border-top: 1px solid #e9ecef;
    
    .el-tag {
      font-size: 14px;
      padding: 8px 20px;
      border-radius: 6px;
      font-weight: 500;
    }
  }
}

.empty-classification,
.empty-state-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: white;
  border-radius: 12px;
}

// 响应式设计
@media (max-width: 1400px) {
  .left-container,
  .right-container {
    width: 280px;
  }
}

@media (max-width: 1200px) {
  .mark-container {
    flex-direction: column;
    height: auto;
    
    .left-container,
    .right-container {
      width: 100%;
      height: auto;
      max-height: 400px;
    }
    
    .center-container {
      height: 600px;
    }
  }
}
</style>