<template>
  <div class="recognition-results">
    <div class="results-header">
      <h3>识别结果</h3>
      <div class="header-actions">
        <a-button type="text" @click="handleSaveResults">
          <template #icon><icon-save /></template>
          保存结果
        </a-button>
        <a-button type="text" @click="handleExportResults">
          <template #icon><icon-export /></template>
          导出
        </a-button>
      </div>
    </div>

    <div class="results-content">
      <!-- 识别统计 -->
      <div class="statistics-section">
        <div class="stat-item">
          <span class="stat-label">裂纹</span>
          <span class="stat-value">{{ statistics.crack }}</span>
          <span class="stat-confidence">置信度: {{ statistics.crackConfidence }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">腐蚀</span>
          <span class="stat-value">{{ statistics.corrosion }}</span>
          <span class="stat-confidence">置信度: {{ statistics.corrosionConfidence }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">磨损</span>
          <span class="stat-value">{{ statistics.wear }}</span>
          <span class="stat-confidence">置信度: {{ statistics.wearConfidence }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">变形</span>
          <span class="stat-value">{{ statistics.deformation }}</span>
          <span class="stat-confidence">置信度: {{ statistics.deformationConfidence }}%</span>
        </div>
      </div>

      <!-- 详细结果列表 -->
      <div class="results-list">
        <h4>详细结果</h4>
        <div class="result-items">
          <div 
            v-for="(result, index) in results" 
            :key="index"
            class="result-item"
            :class="{ active: selectedResultIndex === index }"
            @click="handleResultSelect(index)"
          >
            <div class="result-info">
                             <span class="result-type" :class="getDefectTypeClass(result.defectType)">
                 {{ getDefectTypeName(result.defectType) }}
               </span>
               <span class="result-confidence">{{ ((result.markInfo?.confidence || 0) * 100).toFixed(1) }}%</span>
            </div>
                         <div class="result-position">
               位置: {{ formatPosition(result.markInfo?.bbox) }}
             </div>
             <div class="result-size">
               尺寸: {{ formatSize(result.markInfo?.bbox) }}
             </div>
             <div class="result-recommendation">
               建议: {{ getRecommendation(result.defectType, result.markInfo?.confidence || 0) }}
             </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { 
  IconSave,
  IconExport 
} from '@arco-design/web-vue/es/icon'
import { Message } from '@arco-design/web-vue'

import type { DefectDetectionResult } from '@/apis/industrial-image/defect'

const props = defineProps<{
  results: DefectDetectionResult[]
  isProcessing: boolean
}>()

const emit = defineEmits<{
  resultSelect: [index: number]
  saveResults: [results: DefectDetectionResult[]]
  exportResults: [results: DefectDetectionResult[]]
}>()

const selectedResultIndex = ref(-1)

// 计算统计信息
const statistics = computed(() => {
  const stats = {
    crack: 0,
    crackConfidence: 0,
    corrosion: 0,
    corrosionConfidence: 0,
    wear: 0,
    wearConfidence: 0,
    deformation: 0,
    deformationConfidence: 0
  }

  if (props.results.length === 0) return stats

  // 映射自定义缺陷类型到标准类型
  const typeMapping: Record<string, string> = {
    bmlw: 'crack', // 表面裂纹 -> 裂纹
    hfms: 'wear',  // 合缝磨损 -> 磨损
    mpps: 'deformation', // 蒙皮破损 -> 变形
    bcps: 'deformation', // 布层破损 -> 变形
    jbps: 'deformation', // 局部破损 -> 变形
    ljss: 'corrosion', // 累计损伤 -> 腐蚀
    bcpf: 'deformation', // 布层剥落 -> 变形
    fbps: 'deformation', // 腹部破损 -> 变形
    taps: 'corrosion', // 涂层破损 -> 腐蚀
  }

  // 对结果进行分类统计
  const categorizedResults = props.results.reduce((acc, result) => {
    // 获取标准类型（如果有映射的话）
    const standardType = typeMapping[result.defectType] || result.defectType
    
    // 确保数组已初始化
    if (!acc[standardType]) acc[standardType] = []
    
    // 添加到相应类别
    acc[standardType].push(result)
    return acc
  }, {} as Record<string, DefectDetectionResult[]>)

  // 计算裂纹统计
  const crackResults = categorizedResults['crack'] || []
  stats.crack = crackResults.length
  stats.crackConfidence = crackResults.length > 0 
    ? Math.round(crackResults.reduce((sum, r) => sum + ((r.markInfo?.confidence || 0) * 100), 0) / crackResults.length)
    : 0

  // 计算腐蚀统计  
  const corrosionResults = categorizedResults['corrosion'] || []
  stats.corrosion = corrosionResults.length
  stats.corrosionConfidence = corrosionResults.length > 0
    ? Math.round(corrosionResults.reduce((sum, r) => sum + ((r.markInfo?.confidence || 0) * 100), 0) / corrosionResults.length)
    : 0

  // 计算磨损统计
  const wearResults = categorizedResults['wear'] || []
  stats.wear = wearResults.length
  stats.wearConfidence = wearResults.length > 0
    ? Math.round(wearResults.reduce((sum, r) => sum + ((r.markInfo?.confidence || 0) * 100), 0) / wearResults.length)
    : 0

  // 计算变形统计
  const deformationResults = categorizedResults['deformation'] || []
  stats.deformation = deformationResults.length
  stats.deformationConfidence = deformationResults.length > 0
    ? Math.round(deformationResults.reduce((sum, r) => sum + ((r.markInfo?.confidence || 0) * 100), 0) / deformationResults.length)
    : 0

  return stats
})

// 获取缺陷类型名称
const getDefectTypeName = (type: string): string => {
  const typeMap: Record<string, string> = {
    crack: '裂纹',
    corrosion: '腐蚀',
    wear: '磨损',
    deformation: '变形',
    scratch: '划痕',
    hole: '孔洞',
    dirt: '污垢',
    // 新增自定义缺陷类型映射
    bmlw: '表面裂纹',
    hfms: '合缝磨损',
    mpps: '蒙皮破损',
    bcps: '布层破损',
    jbps: '局部破损',
    ljss: '累计损伤',
    bcpf: '布层剥落',
    fbps: '腹部破损',
    taps: '涂层破损',
    // 可继续添加更多自定义类型
  }
  return typeMap[type] || type
}

// 获取缺陷类型样式类
const getDefectTypeClass = (type: string): string => {
  const classMap: Record<string, string> = {
    crack: 'defect-crack',
    corrosion: 'defect-corrosion',
    wear: 'defect-wear',
    deformation: 'defect-deformation',
    scratch: 'defect-scratch',
    hole: 'defect-hole',
    dirt: 'defect-dirt',
    // 新增自定义缺陷类型样式
    bmlw: 'defect-crack', // 表面裂纹 -> 裂纹样式
    hfms: 'defect-wear', // 合缝磨损 -> 磨损样式
    mpps: 'defect-deformation', // 蒙皮破损 -> 变形样式
    bcps: 'defect-deformation', // 布层破损 -> 变形样式
    jbps: 'defect-deformation', // 局部破损 -> 变形样式
    ljss: 'defect-corrosion', // 累计损伤 -> 腐蚀样式
    bcpf: 'defect-deformation', // 布层剥落 -> 变形样式
    fbps: 'defect-deformation', // 腹部破损 -> 变形样式
    taps: 'defect-corrosion', // 涂层破损 -> 腐蚀样式
  }
  return classMap[type] || 'defect-default'
}

// 获取建议
const getRecommendation = (type: string, confidence: number): string => {
  if (confidence < 60) return '建议人工复核'
  
  const recommendations: Record<string, string> = {
    crack: '立即维修，防止扩散',
    corrosion: '清洁并涂保护层',
    wear: '定期监测，必要时更换',
    deformation: '检查结构完整性',
    scratch: '轻微处理即可',
    hole: '立即修补',
    dirt: '清洁处理'
  }
  return recommendations[type] || '建议进一步检查'
}

// 格式化位置信息
const formatPosition = (bbox: number[] | undefined): string => {
  if (!bbox || bbox.length < 2) return '未知位置'
  return `(${bbox[0]?.toFixed(0)}, ${bbox[1]?.toFixed(0)})`
}

// 格式化尺寸信息
const formatSize = (bbox: number[] | undefined): string => {
  if (!bbox || bbox.length < 4) return '未知尺寸'
  return `${bbox[2]?.toFixed(0)} × ${bbox[3]?.toFixed(0)}`
}

// 选择结果
const handleResultSelect = (index: number) => {
  selectedResultIndex.value = index
  emit('resultSelect', index)
}

// 保存结果
const handleSaveResults = () => {
  emit('saveResults', props.results)
  Message.success('结果已保存')
}

// 导出结果
const handleExportResults = () => {
  emit('exportResults', props.results)
  Message.success('结果已导出')
}
</script>

<style scoped lang="scss">
.recognition-results {
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;

  .results-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .results-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;

    .statistics-section {
      margin-bottom: 24px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 16px;
        background: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 8px;

        .stat-label {
          font-weight: 500;
          color: #374151;
          min-width: 60px;
        }

        .stat-value {
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
          min-width: 30px;
        }

        .stat-confidence {
          font-size: 12px;
          color: #6b7280;
          margin-left: auto;
        }
      }
    }

    .results-list {
      h4 {
        margin: 0 0 16px 0;
        font-size: 14px;
        font-weight: 500;
        color: #374151;
      }

      .result-items {
        .result-item {
          padding: 16px;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover {
            border-color: #3b82f6;
            background: #f0f9ff;
          }

          &.active {
            border-color: #3b82f6;
            background: #f0f9ff;
            box-shadow: 0 2px 4px rgba(59, 130, 246, 0.1);
          }

          .result-info {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;

            .result-type {
              padding: 4px 8px;
              border-radius: 4px;
              font-size: 12px;
              font-weight: 500;

              &.defect-crack {
                background: #fee2e2;
                color: #dc2626;
              }

              &.defect-corrosion {
                background: #fef3c7;
                color: #d97706;
              }

              &.defect-wear {
                background: #e0e7ff;
                color: #5b21b6;
              }

              &.defect-deformation {
                background: #f3e8ff;
                color: #7c3aed;
              }

              &.defect-scratch {
                background: #ecfdf5;
                color: #059669;
              }

              &.defect-hole {
                background: #fef2f2;
                color: #dc2626;
              }

              &.defect-dirt {
                background: #f3f4f6;
                color: #374151;
              }
            }

            .result-confidence {
              font-weight: 600;
              color: #1f2937;
              margin-left: auto;
            }
          }

          .result-position,
          .result-size {
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 4px;
          }

          .result-recommendation {
            font-size: 12px;
            color: #059669;
            font-weight: 500;
            margin-top: 8px;
          }
        }
      }
    }
  }

  // 滚动条样式
  .results-content::-webkit-scrollbar {
    width: 6px;
  }

  .results-content::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
  }

  .results-content::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;
    
    &:hover {
      background: #94a3b8;
    }
  }
}
</style> 