<template>
  <div class="group-comparison">
     
    <!-- 综合排名 -->
    <div class="ranking-section">
      <div class="ranking-header">
       <h3>综合表现排名</h3>
       <div class="manager-selector">
         <select v-model="selectedManager" @change="handleManagerChange" class="manager-dropdown">
           <option value="all">全部高级经理</option>
           <option v-for="manager in seniorManagers" :key="manager.id" :value="manager.id">
             {{ manager.name }}
           </option>
         </select>
       </div>
      </div>
    
      <div class="ranking-grid compact">
        <div 
          v-for="(group, index) in sortedGroups" 
          :key="group.id"
          class="ranking-card"
          :class="getRankingClass(index)"
          @click="$emit('select-group', group)"
          @dblclick="navigateToManager(group)"
        >
          <div class="rank-badge">{{ index + 1 }}</div>
          <div class="group-info">
            <div class="group-name">{{ group.name }}</div>
            <div class="group-leader">{{ group.leader }}</div>
          </div>
          <div class="key-metrics">
            <div class="mini-metric">
              <span class="mini-label">业绩</span>
              <span class="mini-value">{{ group.todayPerformance }}</span>
            </div>
            <div class="mini-metric">
              <span class="mini-label">转化</span>
              <span class="mini-value">{{ group.conversionRate }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const props = defineProps({
  groups: {
    type: Array,
    default: () => []
  },
  seniorManagerData: {
    type: Object,
    default: () => null
  },
  groupList: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['select-group', 'manager-change'])

// 路由实例
const router = useRouter()

// 选中的高级经理
const selectedManager = ref('all')

// 高级经理列表
const seniorManagers = computed(() => {
  if (props.seniorManagerData && props.seniorManagerData.center_advanced_managers) {
    return props.seniorManagerData.center_advanced_managers.map((name, index) => ({
      id: `manager_${index}`,
      name: name
    }))
  }
  return [
    { id: 'manager1', name: '张经理' }
  ]
})

// 处理经理选择变化
const handleManagerChange = () => {
  emit('manager-change', selectedManager.value)
}

// 处理 groupList 数据
const processedGroups = computed(() => {
  console.log('GroupList data:', props.groupList)
  
  if (!props.groupList || Object.keys(props.groupList).length === 0) {
    return props.groups || []
  }
  
  const groups = []
  
  // 处理 composition_transformation 数据
  if (props.groupList.composition_transformation) {
    console.log('Processing composition_transformation:', props.groupList.composition_transformation)
    Object.entries(props.groupList.composition_transformation).forEach(([managerName, teamData]) => {
      console.log('Manager:', managerName, 'TeamData:', teamData, 'Type:', typeof teamData)
      
      // 处理嵌套对象结构
      if (typeof teamData === 'object' && teamData !== null) {
        Object.entries(teamData).forEach(([teamName, rate]) => {
          // 解析团队名称，如"星耀三部-周毅"拆分为部门和经理
          const parts = teamName.split('-')
          let groupName, leaderName
          
          if (parts.length >= 2) {
            // 处理包含双横线的情况，如"巅峰三部--刘东洋"
            if (teamName.includes('--')) {
              const doubleDashParts = teamName.split('--')
              groupName = doubleDashParts[0]
              leaderName = doubleDashParts[1]
            } else {
              // 处理单横线的情况，如"星耀三部-周毅"
              groupName = parts[0]
              leaderName = parts.slice(1).join('-')
            }
          } else {
            groupName = teamName
            leaderName = managerName
          }
          
          groups.push({
            id: `${managerName}-${teamName}`,
            name: groupName,
            leader: leaderName,
            conversionRate: parseFloat(rate) || 0,
            todayPerformance: 0, // 默认值
            newClients: 0, // 默认值
            deals: 0 // 默认值
          })
        })
      } else if (typeof teamData === 'string') {
        // 处理直接字符串值的情况（选择具体经理时可能出现）
        // 解析团队名称，如"星耀三部-周毅"拆分为部门和经理
        const parts = managerName.split('-')
        let groupName, leaderName
        
        if (parts.length >= 2) {
          // 处理包含双横线的情况，如"巅峰三部--刘东洋"
          if (managerName.includes('--')) {
            const doubleDashParts = managerName.split('--')
            groupName = doubleDashParts[0]
            leaderName = doubleDashParts[1]
          } else {
            // 处理单横线的情况，如"星耀三部-周毅"
            groupName = parts[0]
            leaderName = parts.slice(1).join('-')
          }
        } else {
          groupName = managerName
          leaderName = managerName
        }
        
        groups.push({
          id: `${managerName}`,
          name: groupName,
          leader: leaderName,
          conversionRate: parseFloat(teamData) || 0,
          todayPerformance: 0,
          newClients: 0,
          deals: 0
        })
      }
    })
  }
  
  // 处理 formal_plural 数据（业绩数据）
  if (props.groupList.formal_plural) {
    console.log('Processing formal_plural:', props.groupList.formal_plural)
    Object.entries(props.groupList.formal_plural).forEach(([managerName, teamData]) => {
      if (typeof teamData === 'object' && teamData !== null) {
        Object.entries(teamData).forEach(([teamName, performance]) => {
          const existingGroup = groups.find(g => g.id === `${managerName}-${teamName}` || g.id === managerName)
          if (existingGroup) {
            existingGroup.todayPerformance = performance || 0
          }
        })
      } else if (typeof teamData === 'number') {
        // 处理直接数值的情况
        const existingGroup = groups.find(g => g.id === managerName)
        if (existingGroup) {
          existingGroup.todayPerformance = teamData || 0
        }
      }
    })
  }
  
  console.log('Processed groups:', groups)
  return groups
})

// 按综合表现排序的组别
const sortedGroups = computed(() => {
  return [...processedGroups.value].sort((a, b) => calculateScore(b) - calculateScore(a))
})

// 计算综合分数
const calculateScore = (group) => {
  const performanceScore = (group.todayPerformance / 200000) * 30
  const conversionScore = (group.conversionRate / 10) * 25
  const clientScore = (group.newClients / 50) * 25
  const dealScore = (group.deals / 20) * 20
  
  return Math.round(performanceScore + conversionScore + clientScore + dealScore)
}

// 格式化指标值
const formatMetricValue = (value, unit) => {
  switch (unit) {
    case 'currency':
      return formatCurrency(value)
    case 'percent':
      return value + '%'
    case 'number':
      return value.toString()
    default:
      return value
  }
}

// 格式化货币
const formatCurrency = (value) => {
  if (value >= 10000) {
    return (value / 10000).toFixed(1) + '万'
  }
  return value.toLocaleString()
}

// 获取进度条宽度
const getProgressWidth = (value, metricKey) => {
  const maxValues = {
    todayPerformance: 200000,
    conversionRate: 10,
    newClients: 50,
    deals: 20
  }
  
  return Math.min((value / maxValues[metricKey]) * 100, 100)
}

// 获取表现等级样式
const getPerformanceClass = (value, metricKey) => {
  const thresholds = {
    todayPerformance: { excellent: 120000, good: 80000 },
    conversionRate: { excellent: 6, good: 4 },
    newClients: { excellent: 25, good: 15 },
    deals: { excellent: 8, good: 5 }
  }
  
  const threshold = thresholds[metricKey]
  if (value >= threshold.excellent) return 'excellent'
  if (value >= threshold.good) return 'good'
  return 'poor'
}

// 获取排名样式
const getRankingClass = (index) => {
  if (index === 0) return 'rank-1'
  if (index === 1) return 'rank-2'
  if (index === 2) return 'rank-3'
  return 'rank-other'
}

// 处理部门双击事件，跳转到经理页面
const navigateToManager = (group) => {
  router.push({
    path: '/manager',
    query: {
      user_name: group.leader,
      user_level: 2
    }
  })
}

// 获取趋势图标
const getTrendIcon = (trend) => {
  const icons = {
    up: '↗',
    down: '↘',
    stable: '→'
  }
  return icons[trend] || '→'
}

// 获取预警图标
const getAlertIcon = (level) => {
  const icons = {
    warning: '⚠️',
    info: 'ℹ️',
    urgent: '🚨'
  }
  return icons[level] || 'ℹ️'
}
</script>

<style lang="scss" scoped>
.group-comparison {
  background: white;
  border-radius: 12px;
  padding: 1rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  height: 24rem;
  overflow: auto;
    
  // 综合排名
  .ranking-section {
    // margin-bottom: 2rem;
    
    .ranking-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1rem;
      
      h3 {
        font-size: 1.1rem;
        font-weight: 600;
        color: #374151;
        margin: 0;
      }
      
      .manager-selector {
        .manager-dropdown {
          padding: 0.5rem 0.75rem;
          border: 1px solid #d1d5db;
          border-radius: 6px;
          background: white;
          font-size: 0.875rem;
          color: #374151;
          cursor: pointer;
          transition: all 0.2s ease;
          
          &:hover {
            border-color: #9ca3af;
          }
          
          &:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          }
        }
      }
    }
    
    .ranking-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 1rem;
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;
        
        &:hover {
          background: #94a3b8;
        }
      }
      
      &.compact {
        grid-template-columns: repeat(1, 1fr);
        gap: 0.75rem;
        max-height: 500px;
        
        .ranking-card {
          padding: 0.75rem;
          gap: 0.5rem;
          
          .rank-badge {
            width: 24px;
            height: 24px;
            font-size: 0.8rem;
          }
          
          .group-info {
            .group-name {
              font-size: 0.9rem;
            }
            
            .group-leader {
              font-size: 0.75rem;
            }
          }
          
          .performance-score {
            .score {
              font-size: 1.1rem;
            }
            
            .score-label {
              font-size: 0.7rem;
            }
          }
          
          .key-metrics {
            .mini-metric {
              .mini-label {
                font-size: 0.7rem;
              }
              
              .mini-value {
                font-size: 0.8rem;
              }
            }
          }
        }
      }
    }
    
    .ranking-card {
      display: flex;
      align-items: center;
      padding: 1rem;
      border-radius: 10px;
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      &.rank-1 {
        background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
        border: 2px solid #f59e0b;
      }
      
      &.rank-2 {
        background: linear-gradient(135deg, #c0c0c0 0%, #e5e7eb 100%);
        border: 2px solid #9ca3af;
      }
      
      &.rank-3 {
        background: linear-gradient(135deg, #cd7f32 0%, #d97706 100%);
        border: 2px solid #b45309;
      }
      
      &.rank-other {
        background: white;
        border: 1px solid #e5e7eb;
      }
      
      .rank-badge {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 1.2rem;
        margin-right: 1rem;
        background: rgba(255, 255, 255, 0.9);
        color: #1f2937;
      }
      
      .group-info {
        flex: 1;
        
        .group-name {
          font-weight: 600;
          color: #1f2937;
          margin-bottom: 0.25rem;
        }
        
        .group-leader {
          font-size: 0.85rem;
          color: #6b7280;
        }
      }
      
      .performance-score {
        text-align: center;
        margin: 0 1rem;
        
        .score {
          font-size: 1.5rem;
          font-weight: bold;
          color: #1f2937;
        }
        
        .score-label {
          font-size: 0.75rem;
          color: #6b7280;
        }
      }
      
      .key-metrics {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
        
        .mini-metric {
          display: flex;
          justify-content: space-between;
          gap: 0.5rem;
          
          .mini-label {
            font-size: 0.75rem;
            color: #6b7280;
          }
          
          .mini-value {
            font-size: 0.75rem;
            font-weight: 600;
            color: #1f2937;
          }
        }
      }
    }
  }
}

// 移动端适配
@media (max-width: 768px) {
  .group-comparison {
    padding: 0.75rem;
    
    .ranking-grid {
      grid-template-columns: 1fr;
      
      &.compact {
        grid-template-columns: 1fr;
      }
    }
    
    .ranking-card {
      .key-metrics {
        display: none;
      }
    }
  }
}
</style>