<template>
  <div class="practice-report-container">
    <div class="report-header card">
      <div class="header-content">
        <h1 class="report-title">陪练分析报告</h1>
        <div class="report-meta">
          <span>
            <el-icon><Calendar /></el-icon>
            {{ reportData.date }}
          </span>
          <span>
            <el-icon><Clock /></el-icon>
            通话时长：{{ reportData.duration }}
          </span>
          <span>
            <el-icon><ChatDotRound /></el-icon>
            对话轮次：{{ reportData.turns }}
          </span>
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="downloadReport">
          <el-icon class="el-icon--left"><Download /></el-icon>
          下载报告
        </el-button>
        <el-button type="primary" @click="startNewPractice">
          再练一次
        </el-button>
      </div>
    </div>

    <!-- 综合评分 -->
    <div class="score-section card">
      <h2 class="section-title">综合评分</h2>
      <div class="score-content">
        <div class="total-score">
          <div class="score-circle">
            <el-progress 
              type="circle" 
              :percentage="reportData.totalScore" 
              :width="160"
              :stroke-width="12"
              :color="getScoreColor(reportData.totalScore)"
            >
              <template #default="{ percentage }">
                <div class="score-text">
                  <div class="score-value">{{ percentage }}</div>
                  <div class="score-label">综合得分</div>
                </div>
              </template>
            </el-progress>
          </div>
          <div class="score-level">
            <el-tag :type="getScoreLevel(reportData.totalScore).type" size="large">
              {{ getScoreLevel(reportData.totalScore).text }}
            </el-tag>
          </div>
        </div>
        
        <div class="score-breakdown">
          <div class="breakdown-item" v-for="item in scoreBreakdown" :key="item.name">
            <div class="item-header">
              <span class="item-name">{{ item.name }}</span>
              <span class="item-score">{{ item.score }}分</span>
            </div>
            <el-progress :percentage="item.score" :color="getScoreColor(item.score)" />
            <div class="item-desc">{{ item.description }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 能力维度雷达图 -->
    <div class="radar-section card">
      <h2 class="section-title">能力维度分析</h2>
      <div class="radar-content">
        <div class="radar-chart" ref="radarChartRef"></div>
        <div class="radar-legend">
          <div class="legend-item" v-for="dimension in abilityDimensions" :key="dimension.name">
            <div class="legend-header">
              <span class="legend-name">{{ dimension.name }}</span>
              <span class="legend-score">{{ dimension.score }}分</span>
            </div>
            <el-progress :percentage="dimension.score" :show-text="false" />
            <div class="legend-feedback">{{ dimension.feedback }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 对话复盘 -->
    <div class="dialogue-section card">
      <h2 class="section-title">完整对话复盘</h2>
      <div class="dialogue-controls">
        <el-button-group>
          <el-button 
            :type="dialogueFilter === 'all' ? 'primary' : ''"
            @click="dialogueFilter = 'all'"
          >
            全部对话
          </el-button>
          <el-button 
            :type="dialogueFilter === 'highlight' ? 'primary' : ''"
            @click="dialogueFilter = 'highlight'"
          >
            亮点话术
          </el-button>
          <el-button 
            :type="dialogueFilter === 'golden' ? 'primary' : ''"
            @click="dialogueFilter = 'golden'"
          >
            金牌话术
          </el-button>
        </el-button-group>
      </div>
      
      <div class="dialogue-timeline">
        <div 
          class="dialogue-item"
          v-for="(item, index) in filteredDialogue"
          :key="index"
          :class="item.speaker"
        >
          <div class="speaker-avatar">
            <el-avatar :size="36">
              {{ item.speaker === 'user' ? 'ME' : 'AI' }}
            </el-avatar>
          </div>
          
          <div class="dialogue-content">
            <div class="content-header">
              <span class="speaker-name">{{ item.speaker === 'user' ? '你' : 'AI客户' }}</span>
              <span class="dialogue-time">{{ item.time }}</span>
            </div>
            <div class="content-text">{{ item.content }}</div>
            <div class="content-tags" v-if="item.tags && item.tags.length">
              <el-tag 
                v-for="tag in item.tags" 
                :key="tag"
                :type="getTagType(tag)"
                size="small"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="content-comment" v-if="item.comment">
              <el-icon><InfoFilled /></el-icon>
              <span>{{ item.comment }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 改进建议 -->
    <div class="suggestions-section card">
      <h2 class="section-title">改进建议</h2>
      <div class="suggestions-list">
        <div class="suggestion-item" v-for="(suggestion, index) in suggestions" :key="index">
          <div class="suggestion-icon">
            <el-icon :size="24" :color="suggestion.color">
              <component :is="suggestion.icon" />
            </el-icon>
          </div>
          <div class="suggestion-content">
            <h3>{{ suggestion.title }}</h3>
            <p>{{ suggestion.content }}</p>
            <div class="suggestion-example" v-if="suggestion.example">
              <span class="example-label">示例：</span>
              <span class="example-text">{{ suggestion.example }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { practiceApi } from '@/api/practice'
import * as echarts from 'echarts'

const router = useRouter()
const route = useRoute()

// 雷达图引用
const radarChartRef = ref()
let radarChart: any = null

// 报告数据
const reportData = ref({
  date: '2024-03-20 14:30',
  duration: '12分35秒',
  turns: 16,
  totalScore: 85
})

// 分数细分
const scoreBreakdown = ref([
  {
    name: '开场技巧',
    score: 90,
    description: '开场自然，快速建立信任'
  },
  {
    name: '需求挖掘',
    score: 85,
    description: '能够有效识别客户需求'
  },
  {
    name: '产品介绍',
    score: 88,
    description: '产品介绍清晰，重点突出'
  },
  {
    name: '异议处理',
    score: 78,
    description: '处理客户异议还需加强'
  },
  {
    name: '成交技巧',
    score: 82,
    description: '成交话术运用良好'
  }
])

// 能力维度
const abilityDimensions = ref([
  {
    name: '沟通表达',
    score: 88,
    feedback: '语言流畅，表达清晰，但语速可以适当放慢'
  },
  {
    name: '倾听理解',
    score: 92,
    feedback: '能够准确理解客户意图，给予恰当回应'
  },
  {
    name: '情绪控制',
    score: 85,
    feedback: '整体情绪稳定，面对异议时保持专业'
  },
  {
    name: '专业知识',
    score: 90,
    feedback: '产品知识扎实，能够准确回答客户问题'
  },
  {
    name: '销售技巧',
    score: 83,
    feedback: '基本销售流程掌握良好，细节还可优化'
  },
  {
    name: '应变能力',
    score: 80,
    feedback: '面对突发问题反应较快，但处理方式可更灵活'
  }
])

// 对话记录
const dialogueRecords = ref([
  {
    speaker: 'user',
    time: '00:05',
    content: '您好，王女士，我是XX保险公司的销售顾问小张，今天打电话给您是想了解一下您对保险产品的需求。',
    tags: ['亮点话术'],
    comment: '开场专业，身份介绍清晰'
  },
  {
    speaker: 'ai',
    time: '00:12',
    content: '哦，保险啊，我现在已经有社保了，不需要额外的保险。',
    tags: [],
    comment: ''
  },
  {
    speaker: 'user',
    time: '00:18',
    content: '王女士，社保确实是基础保障，但您知道吗，社保的报销比例和范围是有限的。比如很多进口药品和先进治疗手段都不在社保范围内。',
    tags: ['金牌话术'],
    comment: '巧妙引导，从客户角度出发'
  },
  {
    speaker: 'ai',
    time: '00:28',
    content: '这个我倒是听说过，但是保险费用会不会很贵？',
    tags: [],
    comment: ''
  },
  {
    speaker: 'user',
    time: '00:35',
    content: '王女士，其实保险的费用是根据您的年龄和保额来定的。像您这个年龄，每月只需要几百元，就相当于每天一杯咖啡的钱，却能获得几十万的保障。',
    tags: ['亮点话术'],
    comment: '类比生动，让客户容易理解'
  }
])

// 对话筛选
const dialogueFilter = ref('all')

// 筛选后的对话
const filteredDialogue = computed(() => {
  if (dialogueFilter.value === 'all') {
    return dialogueRecords.value
  }
  return dialogueRecords.value.filter(item => 
    item.tags && item.tags.includes(
      dialogueFilter.value === 'highlight' ? '亮点话术' : '金牌话术'
    )
  )
})

// 改进建议
const suggestions = ref([
  {
    icon: 'Clock',
    color: '#e6a23c',
    title: '控制语速',
    content: '您的语速偏快，建议适当放慢，给客户更多思考时间',
    example: '说完产品优势后，停顿2-3秒，观察客户反应'
  },
  {
    icon: 'QuestionFilled',
    color: '#667eea',
    title: '多用开放式问题',
    content: '增加开放式问题的使用，更深入了解客户需求',
    example: '"您对未来的保障有什么期望？"而不是"您需要保险吗？"'
  },
  {
    icon: 'Trophy',
    color: '#67c23a',
    title: '强化成交信号识别',
    content: '客户已经表现出兴趣时，要及时推进成交',
    example: '当客户问"费用多少"时，这是购买信号，应该立即报价并促成'
  }
])

/**
 * 获取分数颜色
 */
const getScoreColor = (score: number) => {
  if (score >= 90) return '#67c23a'
  if (score >= 80) return '#409eff'
  if (score >= 70) return '#e6a23c'
  return '#f56c6c'
}

/**
 * 获取分数等级
 */
const getScoreLevel = (score: number) => {
  if (score >= 90) return { type: 'success', text: '优秀' }
  if (score >= 80) return { type: '', text: '良好' }
  if (score >= 70) return { type: 'warning', text: '及格' }
  return { type: 'danger', text: '待提升' }
}

/**
 * 获取标签类型
 */
const getTagType = (tag: string) => {
  if (tag === '金牌话术') return 'warning'
  if (tag === '亮点话术') return 'success'
  return ''
}

/**
 * 下载报告
 */
const downloadReport = () => {
  ElMessage.success('报告下载中...')
}

/**
 * 初始化雷达图
 */
const initRadarChart = () => {
  if (!radarChartRef.value) return
  
  radarChart = echarts.init(radarChartRef.value)
  
  const option = {
    title: {
      text: '能力维度雷达图',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params: any) {
        return `${params.name}: ${params.value}分`
      }
    },
    radar: {
      indicator: abilityDimensions.value.map(item => ({
        name: item.name,
        max: 100
      })),
      center: ['50%', '55%'],
      radius: '70%',
      startAngle: 90,
      splitNumber: 5,
      shape: 'polygon',
      name: {
        formatter: '{value}',
        textStyle: {
          color: '#666',
          fontSize: 13
        }
      },
      splitArea: {
        areaStyle: {
          color: ['rgba(102, 126, 234, 0.05)', 'rgba(102, 126, 234, 0.1)', 'rgba(102, 126, 234, 0.15)', 'rgba(102, 126, 234, 0.2)', 'rgba(102, 126, 234, 0.25)']
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(102, 126, 234, 0.3)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(102, 126, 234, 0.3)'
        }
      }
    },
    series: [{
      name: '能力评估',
      type: 'radar',
      data: [{
        value: abilityDimensions.value.map(item => item.score),
        name: '当前表现',
        areaStyle: {
          color: 'rgba(102, 126, 234, 0.2)'
        },
        lineStyle: {
          color: '#667eea',
          width: 3
        },
        itemStyle: {
          color: '#667eea',
          borderWidth: 2,
          borderColor: '#fff'
        }
      }]
    }]
  }
  
  radarChart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => {
    radarChart?.resize()
  })
}

/**
 * 开始新的练习
 */
const startNewPractice = () => {
  router.push('/trainee/ai-practice')
}

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  // 1. 从URL获取sessionId（从路径参数）
  const sessionId = route.params.id as string
  
  if (!sessionId) {
    ElMessage.error('缺少会话ID')
    router.push('/trainee/ai-practice-center')
    return
  }
  
  console.log('[PracticeReport] 加载报告，sessionId=', sessionId)
  
  // 2. 加载报告数据
  try {
    const response: any = await practiceApi.getPracticeReport(sessionId)
    
    if (response.code === 200 && response.data) {
      const data = response.data
      
      // 3. 填充会话信息
      const startTime = new Date(data.session_info.start_time)
      const durationMin = Math.floor(data.session_info.duration_seconds / 60)
      const durationSec = data.session_info.duration_seconds % 60
      
      reportData.value = {
        date: startTime.toLocaleString('zh-CN'),
        duration: `${durationMin}分${durationSec}秒`,
        turns: data.session_info.turns,
        totalScore: data.analysis.total_score
      }
      
      // 4. 填充分析数据
      scoreBreakdown.value = data.analysis.score_breakdown
      abilityDimensions.value = data.analysis.ability_dimensions
      dialogueRecords.value = data.analysis.dialogue_review
      suggestions.value = data.analysis.suggestions
      
      // 5. 初始化图表
      nextTick(() => {
        initRadarChart()
      })
    } else {
      ElMessage.error('加载报告失败')
      router.push('/trainee/ai-practice-center')
    }
  } catch (error: any) {
    console.error('加载报告失败:', error)
    ElMessage.error(error.message || '加载报告失败')
    router.push('/trainee/ai-practice-center')
  }
  
  // 6. 响应式处理
  window.addEventListener('resize', handleResize)
})

/**
 * 组件卸载时清理资源
 */
onUnmounted(() => {
  // 销毁图表实例
  radarChart?.dispose()
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})

/**
 * 窗口大小改变处理
 */
const handleResize = () => {
  radarChart?.resize()
}
</script>

<style lang="scss" scoped>
.practice-report-container {
  max-width: 1200px;
  margin: 0 auto;

  .report-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
    margin-bottom: 24px;

    .header-content {
      .report-title {
        font-size: 28px;
        font-weight: 600;
        color: #333;
        margin-bottom: 12px;
      }

      .report-meta {
        display: flex;
        gap: 24px;
        font-size: 14px;
        color: #666;

        span {
          display: flex;
          align-items: center;
          gap: 6px;

          .el-icon {
            color: #909399;
          }
        }
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;

      .el-button--primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
      }
    }
  }

  .section-title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
    margin-bottom: 24px;
  }

  .score-section {
    padding: 32px;
    margin-bottom: 24px;

    .score-content {
      display: grid;
      grid-template-columns: 300px 1fr;
      gap: 48px;

      .total-score {
        text-align: center;

        .score-circle {
          margin-bottom: 24px;

          .score-text {
            .score-value {
              font-size: 48px;
              font-weight: 700;
              color: #333;
            }

            .score-label {
              font-size: 14px;
              color: #666;
              margin-top: 4px;
            }
          }
        }
      }

      .score-breakdown {
        display: grid;
        gap: 20px;

        .breakdown-item {
          .item-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;

            .item-name {
              font-size: 15px;
              font-weight: 500;
              color: #333;
            }

            .item-score {
              font-size: 14px;
              color: #667eea;
              font-weight: 600;
            }
          }

          .item-desc {
            font-size: 13px;
            color: #909399;
            margin-top: 6px;
          }
        }
      }
    }
  }

  .radar-section {
    padding: 32px;
    margin-bottom: 24px;

    .radar-content {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 48px;

      .radar-chart {
        height: 400px;
        width: 100%;
      }

      .radar-legend {
        .legend-item {
          margin-bottom: 24px;

          .legend-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;

            .legend-name {
              font-size: 15px;
              font-weight: 500;
              color: #333;
            }

            .legend-score {
              font-size: 14px;
              color: #667eea;
              font-weight: 600;
            }
          }

          .legend-feedback {
            font-size: 13px;
            color: #666;
            margin-top: 8px;
            line-height: 1.5;
          }
        }
      }
    }
  }

  .dialogue-section {
    padding: 32px;
    margin-bottom: 24px;

    .dialogue-controls {
      margin-bottom: 24px;

      .el-button-group {
        .el-button--primary {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-color: #667eea;
        }
      }
    }

    .dialogue-timeline {
      .dialogue-item {
        display: flex;
        gap: 16px;
        margin-bottom: 24px;

        &.ai {
          flex-direction: row-reverse;

          .dialogue-content {
            background: #f5f7fa;
          }
        }

        .speaker-avatar {
          flex-shrink: 0;
        }

        .dialogue-content {
          flex: 1;
          max-width: 70%;
          background: #fff;
          border: 1px solid #ebeef5;
          border-radius: 12px;
          padding: 16px;

          .content-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;

            .speaker-name {
              font-size: 14px;
              font-weight: 500;
              color: #333;
            }

            .dialogue-time {
              font-size: 12px;
              color: #909399;
            }
          }

          .content-text {
            font-size: 15px;
            color: #333;
            line-height: 1.6;
          }

          .content-tags {
            margin-top: 12px;
            display: flex;
            gap: 8px;
          }

          .content-comment {
            margin-top: 12px;
            padding: 8px 12px;
            background: #f5f7fa;
            border-radius: 6px;
            font-size: 13px;
            color: #666;
            display: flex;
            align-items: flex-start;
            gap: 6px;

            .el-icon {
              color: #667eea;
              margin-top: 2px;
              flex-shrink: 0;
            }
          }
        }
      }
    }
  }

  .suggestions-section {
    padding: 32px;

    .suggestions-list {
      .suggestion-item {
        display: flex;
        gap: 20px;
        margin-bottom: 24px;
        padding: 20px;
        background: #f9fafb;
        border-radius: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .suggestion-icon {
          width: 48px;
          height: 48px;
          background: white;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .suggestion-content {
          flex: 1;

          h3 {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
          }

          p {
            font-size: 14px;
            color: #666;
            line-height: 1.6;
            margin-bottom: 12px;
          }

          .suggestion-example {
            padding: 12px;
            background: white;
            border-radius: 8px;
            font-size: 13px;

            .example-label {
              color: #909399;
              margin-right: 8px;
            }

            .example-text {
              color: #333;
              font-style: italic;
            }
          }
        }
      }
    }
  }
}

// 响应式
@media (max-width: 1024px) {
  .practice-report-container {
    .report-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }

    .score-content {
      grid-template-columns: 1fr !important;
    }

    .radar-content {
      grid-template-columns: 1fr !important;
    }
  }
}

@media (max-width: 768px) {
  .practice-report-container {
    .dialogue-item {
      .dialogue-content {
        max-width: 85% !important;
      }
    }

    .suggestion-item {
      flex-direction: column;
      text-align: center;

      .suggestion-icon {
        margin: 0 auto;
      }
    }
  }
}
</style>
