import { ref, reactive, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import {
  getProjectList,
  getTurbineList,
  getPartList,
  getImageList,
  deleteImage,
  autoAnnotateImage,
  generateReport,
  batchUploadImages,
  uploadImageToPartV2,
  type ProjectTreeNode,
  type IndustrialImage,
  type ProjectInfo,
  type TurbineInfo,
  type PartInfo
} from '@/apis/industrial-image'
import {
  detectDefects,
  getDefectList,
  addDefect,
  updateDefect,
  deleteDefect,
  addManualDefect,
  type DefectDetectionRequest,
  type DefectDetectionResult,
  type ManualDefectAddRequest
} from '@/apis/industrial-image/defect'
import type { TreeNodeData, ImageInfo } from '@/apis/industrial-image/type'
import type { DefectInfo } from '@/apis/industrial-image/defect'
import type { Annotation } from '@/views/project-operation-platform/data-processing/industrial-image/components/ImageCanvas.vue'

export function useIndustrialImage() {
  // 项目树数据
  const projectTreeData = ref<ProjectTreeNode[]>([])
  const selectedKeys = ref<string[]>([])
  const currentProjectId = ref<string>('')

  // 图像列表数据
  const imageList = ref<any[]>([])
  const selectedImage = ref<any | null>(null)
  const selectedImageId = ref<string>('')
  const searchKeyword = ref('')

  // 模态框状态
  const previewModalVisible = ref(false)
  const previewImage = ref<any | null>(null)
  const processModalVisible = ref(false)
  const processImage = ref<any | null>(null)
  const importModalVisible = ref(false)
  const annotationModalVisible = ref(false)

  // 图像导入向导相关数据
  const importWizardVisible = ref(false)
  const selectedTurbineId = ref('')
  const currentTurbineParts = ref<PartInfo[]>([])

  // 自动识别相关状态
  const isAutoRecognitionMode = ref(false)
  const recognitionResults = ref<DefectDetectionResult[]>([])
  const isRecognizing = ref(false)

  // 手动标注相关状态
  const isManualAnnotationMode = ref(false)
  const defectList = ref<DefectInfo[]>([])
  const selectedDefect = ref<DefectInfo | null>(null)
  
  // Canvas 标注相关状态
  const selectedDefectAnnotations = computed(() => {
    if (!selectedDefect.value) return []
    // 将缺陷数据转换为 Canvas 标注格式
    return [{
      id: selectedDefect.value.id,
      type: 'rectangle' as const,
      points: selectedDefect.value.boundingBox ? [
        { x: selectedDefect.value.boundingBox.x, y: selectedDefect.value.boundingBox.y },
        { x: selectedDefect.value.boundingBox.x + selectedDefect.value.boundingBox.width, 
          y: selectedDefect.value.boundingBox.y + selectedDefect.value.boundingBox.height }
      ] : [],
      color: selectedDefect.value.severity === 'high' ? '#ff4d4f' : '#faad14',
      label: selectedDefect.value.defectType
    }]
  })

  // 报告生成相关状态
  const reportGenerationVisible = ref(false)
  const reportUnitData = ref<{
    id: string
    name: string
    type: 'project' | 'turbine' | 'part'
  } | null>(null)

  // 加载状态
  const loading = ref(false)

  // 计算属性
  const currentImageId = computed(() => selectedImageId.value)

  // 加载项目树数据
  const loadProjectTree = async () => {
    try {
      loading.value = true
      const response = await getProjectList({ page: 1, pageSize: 1000 })
      
      // 处理不同的返回数据结构
      let projects: ProjectInfo[] = []
      if (Array.isArray(response.data)) {
        projects = response.data
      } else if (response.data?.list) {
        projects = response.data.list
      } else {
        projects = []
      }
      
      projectTreeData.value = projects.map(project => ({
        id: project.projectId,
        name: project.projectName,
        type: 'project' as const,
        children: [],
        isLeaf: false,
        loaded: false,
        expanded: false,
        status: project.status,
        createTime: project.createTime,
        rawData: project
      }))
      
      // 默认选中第一个项目
      if (projectTreeData.value.length > 0) {
        const firstProject = projectTreeData.value[0]
        selectedKeys.value = [firstProject.id]
        currentProjectId.value = firstProject.id
        console.log('默认选中第一个项目:', firstProject.name)
        
        // 加载图像列表
        loadImageList()
      }
    } catch (error) {
      console.error('加载项目列表失败:', error)
      Message.error('加载项目列表失败')
    } finally {
      loading.value = false
    }
  }

  // 懒加载子节点
  const handleLoadMore = async (node: ProjectTreeNode) => {
    if (!node || node.loaded) return
    
    try {
      if (node.type === 'project') {
        const response = await getTurbineList({ projectId: node.id })
        const turbines = response.data || []
        
        node.children = turbines.map(turbine => ({
          id: turbine.turbineId || turbine.projectId,
          name: turbine.turbineName || turbine.turbineDesc || `机组${turbine.turbineId || turbine.projectId}`,
          type: 'turbine' as const,
          parentId: node.id,
          children: [],
          isLeaf: false,
          loaded: false,
          expanded: false,
          status: turbine.status,
          createTime: turbine.createTime,
          rawData: turbine
        }))
      } else if (node.type === 'turbine') {
        const turbineData = node.rawData as TurbineInfo
        const response = await getPartList({ 
          turbineId: turbineData?.turbineId || node.id 
        })
        const parts = response.data || []
        
        node.children = parts.map(part => ({
          id: part.partId,
          name: part.partName || part.partType || `部件${part.partId}`,
          type: 'part' as const,
          parentId: node.id,
          children: [],
          isLeaf: true,
          loaded: true,
          expanded: false,
          status: part.partType,
          createTime: part.createTime,
          rawData: part
        }))
      }
      
      node.loaded = true
    } catch (error) {
      console.error('加载子节点失败:', error)
      Message.error('加载子节点失败')
    }
  }

  // 处理节点选择
  const handleNodeSelect = (keys: string[]) => {
    if (keys.length > 0) {
      selectedKeys.value = keys
      currentProjectId.value = keys[0]
      
      const selectedNode = findSelectedNode(projectTreeData.value, keys[0])
      if (selectedNode) {
        console.log('选中节点:', selectedNode)
        
        // 如果选中的是机组节点，设置为当前选中的机组
        if (selectedNode.type === 'turbine') {
          selectedTurbineId.value = selectedNode.id
          // 加载该机组下的部件信息
          loadTurbineParts(selectedNode)
        }
      }
      
      loadImageList()
    }
  }

  // 加载指定机组的部件信息
  const loadTurbineParts = async (turbineNode: ProjectTreeNode) => {
    try {
      const turbineData = turbineNode.rawData as TurbineInfo
      const response = await getPartList({ 
        turbineId: turbineData?.turbineId || turbineNode.id 
      })
      
      const parts = response.data || []
      console.log('加载的部件信息:', parts)
      
      currentTurbineParts.value = parts
      console.log('设置部件信息完成，数量:', currentTurbineParts.value.length)
    } catch (error) {
      console.error('加载机组部件失败:', error)
      Message.error('加载机组部件失败')
      currentTurbineParts.value = []
    }
  }

  // 加载图像列表
  const loadImageList = async () => {
    try {
      loading.value = true
      
      const selectedNode = findSelectedNode(projectTreeData.value, currentProjectId.value)
      if (!selectedNode) {
        imageList.value = []
        return
      }
      
      // 构建查询参数
      const params: {
        imageTypes?: string[]
        keyword?: string
        partId?: string
        turbineId?: string
      } = {}
      
      // 添加关键字搜索
      if (searchKeyword.value) {
        params.keyword = searchKeyword.value
      }
      
      // 根据选中节点类型设置查询参数
      if (selectedNode.type === 'project') {
        // 选中项目时，不设置特定的过滤条件，查询所有图像
        console.log('选中项目节点，查询所有图像')
      } else if (selectedNode.type === 'turbine') {
        params.turbineId = selectedNode.id
      } else if (selectedNode.type === 'part') {
        params.partId = selectedNode.id
        // 如果选中部件，也需要找到对应的机组ID
        const turbineNode = findParentNode(projectTreeData.value, selectedNode.id)
        if (turbineNode) {
          params.turbineId = turbineNode.id
        }
      }
      
      console.log('查询图像列表参数:', params)
      // 调用真实API
      const response = await getImageList(params)
      imageList.value = response.data
    } catch (error) {
      Message.error('加载图像列表失败')
      imageList.value = []
    } finally {
      loading.value = false
    }
  }



  // 查找选中的节点
  const findSelectedNode = (nodes: ProjectTreeNode[], nodeId: string): ProjectTreeNode | null => {
    if (!nodes || !Array.isArray(nodes) || !nodeId) return null
    
    for (const node of nodes) {
      if (!node) continue
      
      if (node.id === nodeId) {
        return node
      }
      if (node.children && node.children.length > 0) {
        const found = findSelectedNode(node.children, nodeId)
        if (found) return found
      }
    }
    return null
  }

  // 查找父节点
  const findParentNode = (nodes: ProjectTreeNode[], childId: string): ProjectTreeNode | null => {
    if (!nodes || !Array.isArray(nodes) || !childId) return null
    
    for (const node of nodes) {
      if (!node) continue
      
      if (node.children && node.children.length > 0) {
        const childFound = node.children.find(child => child && child.id === childId)
        if (childFound) return node
        
        const found = findParentNode(node.children, childId)
        if (found) return found
      }
    }
    return null
  }

  // 图像操作
  const handleImageSelect = (image: any) => {
    console.log('选中图像:', image)
    selectedImage.value = image
    
    // 尝试多种可能的图像ID字段名
    const imageId = image.imageId || image.id || image.image_id || image.key || image.attachId
    selectedImageId.value = imageId || ''
    
    console.log('设置图像ID:', selectedImageId.value)
    
    if (!selectedImageId.value) {
      console.warn('图像ID为空，图像数据结构:', image)
      Message.warning('图像ID为空，标注功能可能无法正常使用')
    }
    
    // 确保图像对象有必要的字段
    if (!image.attachId && imageId) {
      image.attachId = imageId
    }
  }

  const handleImagePreview = (image: any) => {
    console.log("image:",image);
    previewImage.value = image
    previewModalVisible.value = true
  }

  const handleImageProcess = (image: any) => {
    processImage.value = image
    processModalVisible.value = true
  }

  const handleImageDelete = (image: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除图像"${image.imageName}"吗？`,
      onOk: async () => {
        try {
          await deleteImage(image.imageId)
          Message.success('删除成功')
          loadImageList()
        } catch (error) {
          console.error('删除图像失败:', error)
          Message.error('删除图像失败')
        }
      }
    })
  }

  const handleSearch = (keyword: string) => {
    searchKeyword.value = keyword
    loadImageList()
  }

  // 头部按钮操作
  const handleStart = () => {
    Message.info('开始处理功能')
  }

  const handleIndustrialImage = () => {
    Message.info('工业图像功能')
  }

  const handleImportImages = () => {
    // 检查是否选择了机组
    const selectedNode = findSelectedNode(projectTreeData.value, currentProjectId.value)
    if (!selectedNode) {
      Message.warning('请先选择一个项目或机组')
      return
    }
    
    if (selectedNode.type === 'turbine') {
      // 如果选中的是机组，直接打开向导
      importWizardVisible.value = true
    } else if (selectedNode.type === 'project') {
      // 如果选中的是项目，提示用户选择机组
      Message.warning('请先选择一个机组来导入图像')
    } else {
      // 如果选中的是部件，使用原来的导入方式
      importModalVisible.value = true
    }
  }

  const handleAutoAnnotate = async () => {
    if (!selectedImage.value) {
      Message.warning('请先选择一张图像')
      return
    }
    
    // 切换到自动识别模式
    isAutoRecognitionMode.value = true
    
    // 清空之前的识别结果
    recognitionResults.value = []
    
    Message.info('已切换到自动识别模式')
  }

  const handleManualAnnotate = () => {
    if (!selectedImage.value) {
      Message.warning('请先选择一张图像')
      return
    }
    
    // 切换到手动标注模式
    isManualAnnotationMode.value = true
    
    // 加载对应的缺陷列表
    loadDefectList()
    
    Message.info('已切换到手动标注模式')
  }

  const handleGenerateReport = async () => {
    const selectedNode = findSelectedNode(projectTreeData.value, currentProjectId.value)
    if (!selectedNode) {
      Message.warning('请先选择一个项目、机组或部件')
      return
    }
    
    // 设置报告单位数据
    reportUnitData.value = {
      id: selectedNode.id,
      name: selectedNode.name,
      type: selectedNode.type
    }
    
    // 显示报告生成对话框
    reportGenerationVisible.value = true
  }

  // 模态框事件处理
  const handleImportSuccess = () => {
    loadImageList()
    Message.success('图像导入成功')
  }

  const handleAnnotationSaved = () => {
    loadImageList()
    Message.success('标注保存成功')
  }

  const handleProcessSuccess = () => {
    loadImageList()
  }

  // 向导导入成功处理
  const handleWizardImportSuccess = async (data: any) => {
    console.log('向导导入成功:', data)
    
    try {
      // 构建上传参数
      const uploadParams = {
        collectorName: data.imageInfo.operator,
        humidness: data.imageInfo.humidity,
        shootingDistance: data.imageInfo.captureDistance,
        shootingMethod: data.imageInfo.captureMethod,
        shootingTimeBegin: data.imageInfo.startTime,
        shootingTimeEnd: data.imageInfo.endTime,
        temperatureMax: data.imageInfo.maxTemperature,
        temperatureMin: data.imageInfo.minTemperature,
        weather: data.imageInfo.weather,
        windLevel: data.imageInfo.windPower
      }
      
      // 使用新的API接口上传图像
      const response = await uploadImageToPartV2(
        'default', // 图像源
        data.part.partId, // 部件ID
        data.images, // 文件列表
        uploadParams
      )
      
      console.log('批量上传响应:', response)
      
      // 重新加载图像列表
      loadImageList()
      
      Message.success(`成功导入${data.images.length}张图像到${data.part.name}`)
    } catch (error) {
      console.error('批量上传失败:', error)
      Message.error('图像上传失败，请重试')
    }
  }

  // 加载缺陷列表
  const loadDefectList = async () => {
    try {
      // 构建查询参数
      const params: any = {}

      // 如果有图像ID，添加到参数
      if (selectedImage.value?.id) {
        params.imageId = selectedImage.value.id
      } else if (selectedImageId.value) {
        params.imageId = selectedImageId.value
      }

      // 如果有选中的节点，按照节点类型添加筛选条件
      if (selectedKeys.value && selectedKeys.value.length > 0) {
        const selectedNodeId = selectedKeys.value[0]
        const selectedNode = findSelectedNode(projectTreeData.value, selectedNodeId)
        
        if (!selectedNode) {
          console.warn('找不到选中的节点:', selectedNodeId)
        } else if (selectedNode.type === 'turbine') {
          params.turbineId = selectedNode.id
        } else if (selectedNode.type === 'part') {
          params.partId = selectedNode.id
          
          // 添加机组ID
          const turbineNode = findParentNode(projectTreeData.value, selectedNode.id)
          if (turbineNode) {
            params.turbineId = turbineNode.id
          }
        }
      }

      console.log('加载缺陷列表参数:', params)
      const response = await getDefectList(params)
      
      if (response.data && response.data.code === 0) {
        // 检查返回数据结构
        const resultData = response.data.data
        
        // 将结果转换为DefectInfo[]类型
        let defects: DefectInfo[] = []
        
        if (resultData) {
          if ('list' in resultData && Array.isArray(resultData.list)) {
            // 分页结构
            defects = resultData.list.map((item: any) => ({
              id: item.id || item.defectId || `defect-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
              ...item
            }))
          } else if (Array.isArray(resultData)) {
            // 直接数组结构
            defects = resultData.map((item: any) => ({
              id: item.id || item.defectId || `defect-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
              ...item
            }))
          }
        }
        
        console.log('处理后的缺陷列表数据:', defects)
        defectList.value = defects
      } else {
        console.error('加载缺陷列表失败:', response)
        defectList.value = []
      }
    } catch (error) {
      console.error('加载缺陷列表失败:', error)
      Message.error('加载缺陷列表失败')
      defectList.value = []
    }
  }

  // 更新选中缺陷的标注
  const updateSelectedDefectAnnotations = () => {
    if (!selectedDefect.value || !selectedDefect.value.labelInfo) {
      selectedDefectAnnotations.value = []
      return
    }
    
    try {
      // 尝试解析labelInfo
      const labelInfo = JSON.parse(selectedDefect.value.labelInfo)
      if (Array.isArray(labelInfo)) {
        selectedDefectAnnotations.value = labelInfo
      } else {
        selectedDefectAnnotations.value = [labelInfo]
      }
    } catch (error) {
      console.error('解析标注信息失败:', error)
      selectedDefectAnnotations.value = []
    }
  }
  
  // 选择缺陷
  const handleDefectSelect = (defect: DefectInfo) => {
    selectedDefect.value = defect
    updateSelectedDefectAnnotations()
  }

  const handleAddDefect = async (defectForm: any, nodeId: string) => {
    try {
      const selectedNode = findSelectedNode(projectTreeData.value, nodeId)
      if (!selectedNode) {
        Message.error('无法找到选中的节点')
        return
      }

      // 构建缺陷数据
      const defectData: Partial<DefectDetectionResult> = {
        defectName: defectForm.defectName,
        defectType: defectForm.defectType,
        defectLevel: defectForm.defectLevel,
        defectPosition: defectForm.defectPosition,
        description: defectForm.description,
        repairIdea: defectForm.repairIdea,
        imageId: selectedImage.value?.imageId || '',
        detectionDate: new Date().toISOString(),
        source: 'manual'
      }

      // 根据节点类型设置相关ID
      if (selectedNode.type === 'part') {
        // TODO: 设置 partId 和 turbineId
        const turbineNode = findParentNode(projectTreeData.value, selectedNode.id)
        if (turbineNode) {
          // defectData.turbineId = turbineNode.id
          // defectData.partId = selectedNode.id
        }
      }

      const response = await addDefect(defectData)
      
      if (response.data.success) {
        Message.success('缺陷添加成功')
        loadDefectList() // 重新加载缺陷列表
      } else {
        Message.error('缺陷添加失败')
      }
    } catch (error) {
      console.error('添加缺陷失败:', error)
      Message.error('添加缺陷失败')
    }
  }

  const handleEditDefect = async (defect: DefectDetectionResult) => {
    try {
      const response = await updateDefect(defect.defectId, defect)
      
      if (response.data.success) {
        Message.success('缺陷更新成功')
        loadDefectList() // 重新加载缺陷列表
      } else {
        Message.error('缺陷更新失败')
      }
    } catch (error) {
      console.error('更新缺陷失败:', error)
      Message.error('更新缺陷失败')
    }
  }

  const handleDeleteDefectById = async (defectId: string) => {
    try {
      const response = await deleteDefect(defectId)
      
      if (response.data.success) {
        Message.success('缺陷删除成功')
        loadDefectList() // 重新加载缺陷列表
      } else {
        Message.error('缺陷删除失败')
      }
    } catch (error) {
      console.error('删除缺陷失败:', error)
      Message.error('删除缺陷失败')
    }
  }

  // Canvas 标注相关方法
  const handleAnnotationAdd = async (annotation: any) => {
    try {
      // 检查是否有选中的图像
      if (!selectedImageId.value && !selectedImage.value?.imageId) {
        Message.error('请先选择一张图像')
        return
      }
      
      // 获取有效的图像ID
      const imageId = selectedImageId.value || selectedImage.value?.imageId || selectedImage.value?.id
      
      if (!imageId) {
        console.error('无法获取图像ID，选中的图像数据:', selectedImage.value)
        Message.error('无法获取图像ID，请重新选择图像')
        return
      }
      
      console.log('添加标注 - 图像ID:', imageId)
      console.log('添加标注 - 标注数据:', annotation)
      
      // 构造符合API要求的缺陷数据
      const defectData: ManualDefectAddRequest = {
        attachId: selectedImage.value?.attachId || '',
        axial: 0,
        chordwise: 0,
        defectCode: 'MANUAL_001',
        defectLevel: 'MEDIUM',
        defectName: annotation.label || '手动标注缺陷',
        defectPosition: 'UNKNOWN',
        defectType: annotation.label || 'UNKNOWN',
        description: '手动标注缺陷',
        detectionDate: new Date().toISOString(),
        labelInfo: JSON.stringify(annotation),
        markInfo: {
          bbox: annotation.type === 'rectangle' ? [
            Math.min(annotation.points[0].x, annotation.points[1].x),
            Math.min(annotation.points[0].y, annotation.points[1].y),
            Math.abs(annotation.points[1].x - annotation.points[0].x),
            Math.abs(annotation.points[1].y - annotation.points[0].y)
          ] : [],
          clsId: 1,
          confidence: 1.0,
          label: annotation.defectType || '手动标注'
        },
        repairIdea: '',
        repairStatus: 'PENDING',
        source: 'MANUAL'
      }
      
      console.log('发送给后端的缺陷数据:', defectData)
      
      // 调用API添加缺陷，传递两个参数：缺陷数据和图像ID
      await addManualDefect(defectData, imageId)
      
      // 重新加载缺陷列表
      await loadDefectList()
      
      Message.success('标注添加成功')
    } catch (error) {
      console.error('添加标注失败:', error)
      Message.error('添加标注失败')
    }
  }

  const handleAnnotationUpdate = async (annotation: any) => {
    try {
      // 更新标注逻辑
      await updateDefect(annotation.id, annotation)
      await loadDefectList()
      Message.success('标注更新成功')
    } catch (error) {
      console.error('更新标注失败:', error)
      Message.error('更新标注失败')
    }
  }

  const handleAnnotationDelete = async (annotationId: string) => {
    try {
      await deleteDefect(annotationId)
      await loadDefectList()
      Message.success('标注删除成功')
    } catch (error) {
      console.error('删除标注失败:', error)
      Message.error('删除标注失败')
    }
  }

  // 报告生成相关方法
  const handleReportGenerated = async (reportData: any) => {
    try {
      console.log('生成报告数据:', reportData)
      
      // 这里可以调用后端API生成报告
      // await generateReport(reportData)
      
      Message.success('报告生成成功')
      reportGenerationVisible.value = false
    } catch (error) {
      console.error('生成报告失败:', error)
      Message.error('生成报告失败')
    }
  }

  // 关闭自动识别模式
  const handleCloseAutoRecognition = () => {
    isAutoRecognitionMode.value = false
    recognitionResults.value = []
  }

  // 关闭手动标注模式
  const handleCloseManualAnnotation = () => {
    isManualAnnotationMode.value = false
    defectList.value = []
    selectedDefect.value = null
  }

  // 开始自动识别
  const handleStartRecognition = async (settings: {
    algorithm: string
    confidence: number
    defectTypes: string[]
  }) => {
    if (!selectedImage.value) {
      Message.warning('请先选择一张图像')
      return
    }

    try {
      isRecognizing.value = true
      
      // 调用真实的缺陷检测API
      const detectParams: DefectDetectionRequest = {
        confThreshold: settings.confidence / 100, // 转换为0-1的置信度
        defectTypeList: settings.defectTypes,
        imageId: selectedImage.value.imageId,
        modelId: settings.algorithm // 使用算法作为模型ID
      }
      
      const response = await detectDefects(detectParams)
      
      // 检查返回结构，适配API实际返回的数据格式
      let detectedDefects: DefectDetectionResult[] = []
      
      if (response && response.data) {
        if (Array.isArray(response.data)) {
          // 直接使用返回的数组
          detectedDefects = response.data
        } else if (typeof response.data === 'object' && 'data' in response.data && Array.isArray(response.data.data)) {
          // 使用嵌套的data数组
          detectedDefects = response.data.data
        }
      }
      
      if (detectedDefects.length > 0) {
        recognitionResults.value = detectedDefects
        
        // 检查是否有attachPath，如果有则更新当前显示的图片路径
        const firstResult = detectedDefects[0]
        if (firstResult.attachPath && firstResult.attachPath !== selectedImage.value.imagePath) {
          // 更新当前选中图像的路径为识别后返回的attachPath
          selectedImage.value = {
            ...selectedImage.value,
            imagePath: firstResult.attachPath
          }
          console.log('图片路径已更新为识别后的路径:', firstResult.attachPath)
        }
        
        Message.success(`识别完成，发现${detectedDefects.length}个缺陷`)
      } else {
        recognitionResults.value = []
        Message.info('未发现缺陷')
      }
      
      // 不再需要类型映射，因为RecognitionResults组件已经处理了自定义类型
      
    } catch (error) {
      console.error('识别失败:', error)
      Message.error('识别失败')
      recognitionResults.value = []
    } finally {
      isRecognizing.value = false
    }
  }

  // 选择识别结果
  const handleRecognitionResultSelect = (index: number) => {
    const result = recognitionResults.value[index]
    if (result) {
      // 这里可以在图像上高亮显示选中的缺陷
      console.log('选中识别结果:', result)
    }
  }

  // 保存识别结果
  const handleSaveRecognitionResults = async (results: DefectDetectionResult[]) => {
    if (!results || results.length === 0) {
      Message.warning('没有识别结果需要保存')
      return
    }

    if (!selectedImage.value) {
      Message.warning('当前没有选中的图像')
      return
    }

    try {
      console.log('开始保存识别结果:', results)
      
      let successCount = 0
      let failCount = 0
      const errors: string[] = []

      // 为每个识别结果创建缺陷记录
      for (let i = 0; i < results.length; i++) {
        const result = results[i]
        
        try {
          // 构建缺陷数据，转换识别结果为手动添加缺陷的格式
          const defectData: ManualDefectAddRequest = {
            attachId: selectedImage.value.imageId, // 使用图像ID作为附件ID
            // axial: result.axial || 0,
            // chordwise: result.chordwise || 0,
            // defectCode: result.defectCode || `AUTO-${Date.now()}-${i + 1}`, // 自动生成缺陷编码
            defectCode: '',
            defectLevel: result.defectLevel || 'medium', // 默认中等级别
            defectName: result.defectName || `自动识别缺陷-${i + 1}`,
            defectPosition: result.defectPosition || '自动识别位置',
            defectType: result.defectType || 'unknown',
            description: result.description || `自动识别发现的${result.defectType || '未知'}类型缺陷`,
            detectionDate: result.detectionDate || new Date().toISOString(),
            labelInfo: result.labelInfo || JSON.stringify(result.markInfo || {}),
            markInfo: result.markInfo || {
              bbox: [0, 0, 0, 0],
              clsId: 0,
              confidence: 0.8,
              label: result.defectType || '自动识别'
            },
            repairIdea: result.repairIdea || '建议进一步检查确认',
            repairStatus: result.repairStatus || 'pending',
            source: 'auto' // 标记为自动识别来源
          }

          // 调用手动添加缺陷接口
          const response = await addManualDefect(defectData,selectedImage.value.imageId)
          
          if (response.data.success) {
            successCount++
            console.log(`缺陷 ${i + 1} 保存成功:`, response.data.data)
          } else {
            failCount++
            errors.push(`缺陷 ${i + 1}: ${response.data.msg || '保存失败'}`)
          }
        } catch (error: any) {
          failCount++
          console.error(`保存缺陷 ${i + 1} 失败:`, error)
          errors.push(`缺陷 ${i + 1}: ${error.message || '网络错误'}`)
        }
      }

      // 显示保存结果
      if (successCount > 0 && failCount === 0) {
        Message.success(`所有识别结果已保存！共保存 ${successCount} 个缺陷记录`)
      } else if (successCount > 0 && failCount > 0) {
        Message.warning(`部分识别结果保存成功！成功 ${successCount} 个，失败 ${failCount} 个`)
        if (errors.length > 0) {
          console.warn('保存失败的详情:', errors)
        }
      } else {
        Message.error(`保存失败！所有 ${failCount} 个识别结果都未能保存`)
        if (errors.length > 0) {
          console.error('保存失败的详情:', errors)
        }
      }

      // 如果有成功保存的，重新加载缺陷列表
      if (successCount > 0) {
        loadDefectList()
      }

    } catch (error) {
      console.error('保存识别结果失败:', error)
      Message.error('保存识别结果失败')
    }
  }

  // 导出识别结果
  const handleExportRecognitionResults = (results: any[]) => {
    console.log('导出识别结果:', results)
    // 实际项目中这里应该调用导出接口
  }

  // 初始化
  const init = () => {
    if (!projectTreeData.value) {
      projectTreeData.value = []
    }
    loadProjectTree()
  }

  return {
    // 数据
    projectTreeData,
    selectedKeys,
    currentProjectId,
    imageList,
    selectedImage,
    selectedImageId,
    searchKeyword,
    previewModalVisible,
    previewImage,
    processModalVisible,
    processImage,
    importModalVisible,
    annotationModalVisible,
    loading,
    currentImageId,
    
    // 向导相关状态
    importWizardVisible,
    selectedTurbineId,
    currentTurbineParts,
    
    // 自动识别相关状态
    isAutoRecognitionMode,
    recognitionResults,
    isRecognizing,
    
    // 手动标注相关状态
    isManualAnnotationMode,
    defectList,
    selectedDefect,
    selectedDefectAnnotations,
    
    // 报告生成相关状态
    reportGenerationVisible,
    reportUnitData,
    
    // 方法
    loadProjectTree,
    handleLoadMore,
    handleNodeSelect,
    loadImageList,
    handleImageSelect,
    handleImagePreview,
    handleImageProcess,
    handleImageDelete,
    handleSearch,
    handleStart,
    handleIndustrialImage,
    handleImportImages,
    handleAutoAnnotate,
    handleManualAnnotate,
    handleGenerateReport,
    handleImportSuccess,
    handleAnnotationSaved,
    handleProcessSuccess,
    handleWizardImportSuccess,
    
    // 自动识别相关方法
    handleCloseAutoRecognition,
    handleStartRecognition,
    handleRecognitionResultSelect,
    handleSaveRecognitionResults,
    handleExportRecognitionResults,
    
    // 手动标注相关方法
    handleCloseManualAnnotation,
    loadDefectList,
    handleDefectSelect,
    handleAddDefect,
    handleEditDefect,
    handleDeleteDefectById,
    
    // Canvas 标注相关方法
    handleAnnotationAdd,
    handleAnnotationUpdate,
    handleAnnotationDelete,
    
    // 报告生成相关方法
    handleReportGenerated,
    
    init
  }
} 