<template>
  <div class="defect-list-panel">
    <!-- 头部 -->
    <div class="panel-header">
      <h3>缺陷列表</h3>
      <a-button type="text" @click="$emit('close')">
        <template #icon><icon-close /></template>
      </a-button>
    </div>

    <!-- 项目树 -->
    <div class="project-tree-container">
      <a-tree
        v-model:selected-keys="localSelectedKeys"
        :data="treeData"
        :show-line="true"
        :block-node="true"
        @select="handleNodeSelect"
      >
        <template #icon="{ node }">
          <icon-folder v-if="node?.type === 'project'" />
          <icon-desktop v-else-if="node?.type === 'turbine'" />
          <icon-file v-else-if="node?.type === 'part'" />
          <icon-bug v-else />
        </template>
        <template #title="{ node }">
          <span class="node-title" v-if="node">
            {{ node.title || node.name || '未命名节点' }}
            <a-tag v-if="node.defectCount > 0" color="red" size="small">
              {{ node.defectCount }}
            </a-tag>
          </span>
        </template>
      </a-tree>
    </div>

    <!-- 缺陷列表 -->
    <div class="defect-list-container" v-if="filteredDefectList.length > 0">
      <div class="list-header">
        <span>缺陷详情</span>
        <a-tag color="blue" size="small">{{ filteredDefectList.length }}</a-tag>
      </div>
      
      <div class="defect-items">
        <div 
          v-for="defect in filteredDefectList" 
          :key="defect.defectId || defect.id || `defect-${Math.random()}`"
          class="defect-item"
          :class="{ 'active': selectedDefect && (selectedDefect.defectId === defect.defectId || selectedDefect.id === defect.id) }"
          @click="handleDefectSelect(defect)"
        >
          <div class="defect-content">
            <div class="defect-header">
              <span class="defect-name">{{ defect.defectName || defect.defectType || '未命名缺陷' }}</span>
              <a-tag 
                :color="getDefectLevelColor(defect.defectLevel)" 
                size="small"
              >
                {{ defect.defectLevelLabel || defect.defectLevel || '未知' }}
              </a-tag>
            </div>
            <div class="defect-meta">
              <span class="defect-type">{{ defect.defectTypeLabel || defect.defectType || '未知类型' }}</span>
              <span class="defect-position">{{ defect.defectPosition || '未知位置' }}</span>
            </div>
            <div class="defect-description" v-if="defect.description">
              {{ defect.description }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <icon-bug class="empty-icon" />
      <p>暂无缺陷数据</p>
      <p class="empty-tip">请在图像上绘制矩形标注缺陷</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { 
  IconClose, 
  IconFolder, 
  IconDesktop,
  IconFile,
  IconBug,
  IconExclamationCircle 
} from '@arco-design/web-vue/es/icon'
import type { DefectDetectionResult } from '@/apis/industrial-image/defect'

export interface TreeNode {
  key: string
  title: string
  type: 'project' | 'turbine' | 'part'
  defectCount?: number
  children?: TreeNode[]
}

const props = defineProps<{
  defectList: DefectDetectionResult[]
  selectedDefect: DefectDetectionResult | null
  treeData: TreeNode[]
  selectedKeys: string[]
}>()

const emit = defineEmits<{
  close: []
  'defect-select': [defect: DefectDetectionResult]
  'node-select': [keys: string[]]
}>()

// 本地选中的keys，用于同步外部状态
const localSelectedKeys = ref<string[]>([])

// 监听外部selectedKeys变化，同步到本地
watch(() => props.selectedKeys, (newKeys) => {
  localSelectedKeys.value = [...newKeys]
}, { immediate: true })

// 监听treeData变化，添加调试信息
watch(() => props.treeData, (newTreeData) => {
  console.log('DefectListPanel: treeData changed:', newTreeData)
  if (newTreeData && newTreeData.length > 0) {
    console.log('DefectListPanel: 第一个树节点:', newTreeData[0])
  }
}, { immediate: true })

// 根据选中的节点过滤缺陷列表
const filteredDefectList = computed(() => {
  if (!props.selectedKeys.length) {
    return props.defectList
  }
  
  const selectedKey = props.selectedKeys[0]
  return props.defectList.filter(defect => {
    // 根据选中的节点类型过滤缺陷
    return defect.turbineId === selectedKey || 
           defect.attachId === selectedKey ||
           defect.imageId === selectedKey
  })
})

const handleDefectSelect = (defect: DefectDetectionResult) => {
  emit('defect-select', defect)
}

const handleNodeSelect = (keys: string[]) => {
  localSelectedKeys.value = keys
  emit('node-select', keys)
}

const getDefectLevelColor = (level: string) => {
  switch (level?.toLowerCase()) {
    case 'high':
    case 'critical':
      return 'red'
    case 'medium':
    case 'moderate':
      return 'orange'
    case 'low':
    case 'minor':
      return 'green'
    default:
      return 'gray'
  }
}
</script>

<style scoped lang="scss">
.defect-list-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;
  }
}

.project-tree-container {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  max-height: 300px;
  overflow-y: auto;
  
  .node-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }
}

.defect-list-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e5e7eb;
  font-weight: 500;
  color: #374151;
}

.defect-items {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.defect-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    border-color: #3b82f6;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  &.active {
    border-color: #3b82f6;
    background: #f0f9ff;
  }
}

.defect-content {
  .defect-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    
    .defect-name {
      font-weight: 500;
      color: #1f2937;
    }
  }
  
  .defect-meta {
    display: flex;
    gap: 12px;
    margin-bottom: 8px;
    font-size: 12px;
    color: #6b7280;
    
    .defect-type {
      padding: 2px 6px;
      background: #f3f4f6;
      border-radius: 3px;
    }
  }
  
  .defect-description {
    font-size: 12px;
    color: #6b7280;
    line-height: 1.4;
  }
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #6b7280;
  
  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
  }
  
  p {
    margin: 4px 0;
    text-align: center;
  }
  
  .empty-tip {
    font-size: 12px;
    opacity: 0.7;
  }
}
</style>