<template>
  <div class="defect-list-panel">
    <div class="panel-header">
      <h2>缺陷管理</h2>
      <div class="header-actions">
        <a-button 
          type="primary" 
          size="small"
          @click="handleAddDefect"
          :disabled="!canAddDefect"
        >
          <template #icon><icon-plus /></template>
          新增缺陷
        </a-button>
        <a-button type="text" @click="$emit('close')">
          <template #icon><icon-close /></template>
        </a-button>
      </div>
    </div>
    
    <div class="panel-content">
      <!-- 项目树形结构 -->
      <div class="tree-section">
        <h3>项目管理</h3>
        <div class="project-tree">
          <a-tree
            :data="enhancedTreeData"
            :selected-keys="selectedKeys"
            :field-names="{ key: 'id', title: 'name', children: 'children' }"
            :load-more="handleLoadMore"
            :show-line="true"
            @select="handleNodeSelect"
          >
            <template #title="node">
              <div class="tree-node">
                <span class="node-icon">
                  <icon-folder v-if="node.type === 'project'" />
                  <icon-settings v-else-if="node.type === 'turbine'" />
                  <icon-tool v-else-if="node.type === 'part'" />
                  <icon-bug v-else-if="node.type === 'defect'" />
                  <icon-apps v-else />
                </span>
                <span class="node-title">{{ node.name }}</span>
                <span v-if="node.imageCount" class="node-count">({{ node.imageCount }})</span>
                <span v-if="node.defectCount" class="defect-count">[{{ node.defectCount }}]</span>
              </div>
            </template>
          </a-tree>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { IconClose, IconBug, IconFolder, IconPlus, IconSettings, IconTool, IconApps } from '@arco-design/web-vue/es/icon'
import type { PropType } from 'vue'
import { ref, computed, watch } from 'vue'

// 树节点类型
export interface TreeNode {
  id: string
  name: string
  type: string
  imageCount?: number
  defectCount?: number
  defectLevel?: string
  defectType?: string
  detectionDate?: string
  defectData?: DefectInfo
  children?: TreeNode[]
}

// 缺陷信息类型
export interface DefectInfo {
  id: string
  defectName?: string
  defectLevel?: string
  defectType?: string
  defectPosition?: string
  detectionDate?: string
  description?: string
  repairStatus?: string
  labelInfo?: string
  turbineId?: string
  [key: string]: any
}

// 定义属性
const props = defineProps({
  // 缺陷列表
  defectList: {
    type: Array as PropType<DefectInfo[]>,
    default: () => []
  },
  // 选中的缺陷
  selectedDefect: {
    type: Object as PropType<DefectInfo | null>,
    default: null
  },
  // 树数据
  treeData: {
    type: Array as PropType<TreeNode[]>,
    default: () => []
  },
  // 选中的树节点
  selectedKeys: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits([
  'defect-select',
  'node-select',
  'load-more',
  'add-defect',
  'turbine-select',
  'close'
])

// 增强的树数据，添加缺陷信息
const enhancedTreeData = computed(() => {
  if (!props.treeData || !Array.isArray(props.treeData)) {
    return []
  }
  
  return props.treeData.map(project => enhanceTreeNode(project))
})

// 递归增强树节点，为机组添加缺陷信息
const enhanceTreeNode = (node: TreeNode): TreeNode => {
  const enhancedNode = { ...node }
  
  if (node.type === 'turbine') {
    // 为机组添加缺陷列表作为子节点，与部件平级
    const defectNodes = getDefectNodesForTurbine(node.id)
    enhancedNode.children = [
      ...(node.children || []).map(child => enhanceTreeNode(child)),
      ...defectNodes
    ]
  } else if (node.children) {
    enhancedNode.children = node.children.map(child => enhanceTreeNode(child))
  }
  
  return enhancedNode
}

// 获取机组的缺陷节点
const getDefectNodesForTurbine = (turbineId: string): TreeNode[] => {
  // 根据机组ID过滤缺陷列表
  const turbineDefects = props.defectList.filter(defect => 
    defect.turbineId === turbineId || defect.imageId === turbineId
  )
  
  // 直接将缺陷作为子节点，与部件平级
  return turbineDefects.map(defect => ({
    id: defect.id,
    name: defect.defectName || '未命名缺陷',
    type: 'defect',
    defectLevel: defect.defectLevel,
    defectType: defect.defectType,
    detectionDate: defect.detectionDate,
    defectData: defect // 保存完整的缺陷数据
  }))
}

// 处理节点选择
const handleNodeSelect = (selectedKeys: string[], e: any) => {
  const selectedNode = e.node
  
  // 如果选择的是机组节点，触发查询缺陷列表
  if (selectedNode?.type === 'turbine') {
    emit('turbine-select', selectedNode.id)
  }
  
  // 如果选择的是缺陷节点，触发缺陷选择事件
  if (selectedNode?.type === 'defect') {
    const defect = selectedNode.defectData || props.defectList.find(d => d.id === selectedNode.id)
    if (defect) {
      emit('defect-select', defect)
    }
  }
  
  emit('node-select', selectedKeys, e)
}

// 处理加载更多
const handleLoadMore = (node: any) => {
  emit('load-more', node)
}

// 处理新增缺陷
const handleAddDefect = () => {
  if (canAddDefect.value) {
    emit('add-defect')
  }
}

// 计算是否可以添加缺陷
const canAddDefect = computed(() => {
  // 至少需要选择一个节点才能添加缺陷
  return props.selectedKeys && props.selectedKeys.length > 0
})
</script>

<style scoped lang="scss">
.defect-list-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f8f9fa;
  
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #e5e7eb;
    
    h2 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  
  .panel-content {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  .tree-section {
    flex: 1;
    background-color: white;
    border-radius: 8px;
    margin: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    
    h3 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: #1d2129;
      padding: 12px 16px;
      border-bottom: 1px solid #f2f3f5;
      background: white;
    }
    
    .project-tree {
      flex: 1;
      padding: 16px;
      overflow-y: auto;
      overflow-x: hidden;
      height: 0;
      min-height: 0;
      
      // 美化滚动条样式
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
        
        &:hover {
          background: #a8a8a8;
        }
      }
      
      // Firefox 滚动条样式
      scrollbar-width: thin;
      scrollbar-color: #c1c1c1 #f1f1f1;

      .tree-node {
        display: flex;
        align-items: center;
        gap: 6px;

        .node-icon {
          color: #6b7280;
        }

        .node-title {
          flex: 1;
          font-size: 14px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .node-count {
          font-size: 12px;
          color: #6b7280;
          flex-shrink: 0;
        }
        
        .defect-count {
          font-size: 12px;
          color: #ff4d4f;
          flex-shrink: 0;
          font-weight: 600;
        }
      }
    }
  }
}
</style> 