<template>
  <div class="member-details">
    <div class="details-header" @click="toggleDetailsCollapse">
      <h2>{{ memberDetails?.user_name || selectedMember?.user_name || selectedMember?.name||'张三' }} 的详细数据</h2>
      <div class="collapse-toggle" :class="{ 'collapsed': isDetailsCollapsed }">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
          <path d="M8 4l4 4H4l4-4z"/>
        </svg>
      </div>
    </div>
    <div class="details-content">
      <div class="details-grid" v-show="!isDetailsCollapsed" :class="{ 'collapsing': isDetailsCollapsed }">
        <div class="detail-card">
          <div class="detail-label">
            总通话次数
            <span class="info-icon" @mouseenter="showTooltip($event, 'totalCalls')" @mouseleave="hideTooltip">ⓘ</span>
          </div>
          <div class="detail-value">{{ memberDetails?.call_count || 0 }} 次</div>
        </div>
        <div class="detail-card">
          <div class="detail-label">
            通话时长
            <span class="info-icon" @mouseenter="showTooltip($event, 'callTime')" @mouseleave="hideTooltip">ⓘ</span>
          </div>
          <div class="detail-value">{{ memberDetails?.total_call_duration_hour || 0 }} 小时</div>
        </div>
        <div class="detail-card">
          <div class="detail-label">
            新增客户
            <span class="info-icon" @mouseenter="showTooltip($event, 'newClients')" @mouseleave="hideTooltip">ⓘ</span>
          </div>
          <div class="detail-value">{{ memberDetails?.add_customer_count || 0 }} 人</div>
        </div>
        <div class="detail-card">
          <div class="detail-label">
            成交单数
            <span class="info-icon" @mouseenter="showTooltip($event, 'deals')" @mouseleave="hideTooltip">ⓘ</span>
          </div>
          <div class="detail-value">{{ memberDetails?.month_order_count || 0 }} 单</div>
        </div>
        <div class="detail-card">
          <div class="detail-label">
            转化率
            <span class="info-icon" @mouseenter="showTooltip($event, 'conversionRate')" @mouseleave="hideTooltip">ⓘ</span>
          </div>
          <div class="detail-value">{{ selectedMember?.conversion_rate || selectedMember?.conversion || '0%' }}</div>
        </div>
      </div>
    </div>

    <!-- 【新增】通话分类统计模块 -->
    <div class="call-analysis-section">
      <div class="analysis-header" @click="toggleCallAnalysisCollapse">
        <h3>📊 通话分类统计</h3>
        <div class="collapse-toggle" :class="{ 'collapsed': isCallAnalysisCollapsed }">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 4l4 4H4l4-4z"/>
          </svg>
        </div>
      </div>
      <div class="analysis-content" v-show="!isCallAnalysisCollapsed" :class="{ 'collapsing': isCallAnalysisCollapsed }">
        <div v-if="processedCallStats.length > 0" class="analysis-list">
          <div v-for="stat in processedCallStats" :key="stat.tag" class="analysis-item">
            <div class="analysis-label">
              <span class="tag-name">{{ stat.tag }}</span>
              <span class="call-count">{{ stat.count }} 次</span>
            </div>
            <div class="progress-bar-container">
              <div class="progress-bar" :style="{ width: stat.percentage + '%' }"></div>
            </div>
            <div class="analysis-stats">
              <span class="percentage">{{ stat.percentage.toFixed(1) }}%</span>
              <span class="avg-time">均长: {{ stat.avgTime.toFixed(1) }} 分钟</span>
            </div>
          </div>
        </div>
        <div v-else class="no-data">
          <p>暂无通话分类数据</p>
        </div>
      </div>
    </div>
    <!-- 【新增】模块结束 -->
    
    <!-- 指导建议 -->
    <div class="guidance-section">
      <div class="guidance-header" @click="toggleGuidanceCollapse">
        <h3>💡 指导建议</h3>
        <div class="collapse-toggle" :class="{ 'collapsed': isGuidanceCollapsed }">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 4l4 4H4l4-4z"/>
          </svg>
        </div>
      </div>
      <div class="guidance-content" v-show="!isGuidanceCollapsed" :class="{ 'collapsing': isGuidanceCollapsed }">
        <!-- 分析报告内容 -->
        <div class="analysis-report">
          <div v-if="isReportLoading" class="loading-message">正在生成分析报告...</div>
          <div v-else-if="!analysisReport || (Array.isArray(analysisReport) && analysisReport.length === 0)" class="empty-message">
            暂无分析报告数据
          </div>
          <div v-else-if="Array.isArray(analysisReport)">
            <div v-for="(report, index) in analysisReport" :key="index" class="report-section">
              <h4 class="report-title">{{ report.name }} ({{ report.start_time }} - {{ report.end_time }})</h4>
              <div class="report-content" v-html="report.report.replace(/\n/g, '<br>')"></div>
            </div>
          </div>
          <div v-else class="report-content">{{ analysisReport }}</div>
        </div>
      </div>
    </div>
    <!-- Tooltip 组件 -->
    <Tooltip 
      :visible="tooltip.visible"
      :x="tooltip.x"
      :y="tooltip.y"
      :title="tooltip.title"
      :description="tooltip.description"
    />
  </div>
</template>

<script setup>
import { ref, defineProps, watch, nextTick, reactive, computed } from 'vue'
import Tooltip from '@/components/Tooltip.vue'
import { GetSecondOrderAnalysisReport, getMemberCallClassify } from '@/api/manager.js'
import { SimpleChatService } from '@/utils/ChatService.js'

// 定义props
const props = defineProps({
  selectedMember: {
    type: Object,
    required: true
  },
  memberDetails: {
    type: Object,
    required: true
  }
})

// 详细数据折叠状态
const isDetailsCollapsed = ref(false)

// 指导建议折叠状态（默认展开）
const isGuidanceCollapsed = ref(false)

// 【新增】通话分类统计折叠状态
const isCallAnalysisCollapsed = ref(false)

// 【修改】存放通话分类API数据的内部状态
const callClassificationData = ref({
  call_count_by_tag: {},
  call_avg_time: {}
});

// 分析周期
const analysisPeriod = ref('day') // 默认周期为当日
const analysisReport = ref('') // 分析报告内容
const isReportLoading = ref(false) // 报告加载状态
const chatService_02 = ref(null) // 用于生成分析报告的聊天服务实例

// 工具提示状态
const tooltip = reactive({
  visible: false,
  x: 0,
  y: 0,
  title: '',
  description: ''
})

// 指标描述
const metricDescriptions = {
  totalCalls: { title: '总通话次数计算方式', description: '统计在选定时间范围内的所有外呼和接听通话的总次数，包括有效通话和无效通话。' },
  callTime: { title: '通话时长计算方式', description: '累计所有有效通话的时长，以小时为单位显示，精确到小数点后一位。' },
  newClients: { title: '新增客户计算方式', description: '在选定时间范围内新建档的客户数量，不包括重复录入的客户。' },
  deals: { title: '成交单数计算方式', description: '在选定时间范围内成功签约的订单数量，包括全款和定金订单。' },
  conversionRate: { title: '转化率计算方式', description: '成交单数 ÷ 新增客户数 × 100%' }
}

// 切换详细数据折叠状态
const toggleDetailsCollapse = () => {
  isDetailsCollapsed.value = !isDetailsCollapsed.value
}

// 【新增】切换通话分析折叠状态
const toggleCallAnalysisCollapse = () => {
  isCallAnalysisCollapsed.value = !isCallAnalysisCollapsed.value
}


// 【修改】处理通话统计数据的 computed 属性，现在它依赖于内部状态
const processedCallStats = computed(() => {
  const counts = callClassificationData.value?.call_count_by_tag;
  const avgs = callClassificationData.value?.call_avg_time;

  if (!counts || !avgs || Object.keys(counts).length === 0) {
    return [];
  }

  const totalCalls = Object.values(counts).reduce((sum, count) => sum + count, 0);
  if (totalCalls === 0) {
    return [];
  }

  return Object.keys(counts).map(tag => ({
    tag: tag,
    count: counts[tag],
    avgTime: avgs[tag] || 0,
    percentage: (counts[tag] / totalCalls) * 100,
  })).sort((a, b) => b.count - a.count); // 按通话次数降序排列
});

// 切换指导建议折叠状态
const toggleGuidanceCollapse = () => {
  isGuidanceCollapsed.value = !isGuidanceCollapsed.value
}

// 显示工具提示
const showTooltip = (event, metricType) => {
  const metric = metricDescriptions[metricType]
  if (metric) {
    tooltip.title = metric.title
    tooltip.description = metric.description
    tooltip.x = event.clientX
    tooltip.y = event.clientY
    tooltip.visible = true
  }
}

// 隐藏工具提示
const hideTooltip = () => {
  tooltip.visible = false
}

// 【修改】函数现在从API获取数据并更新内部状态
async function updateCallClassificationData() {
  if (props.selectedMember && props.selectedMember.user_name) {
    try {
      const response = await getMemberCallClassify({
        user_name: props.selectedMember.user_name
      });
      console.log('获取通话分类数据:', response.data);
      // 将获取到的数据赋值给内部状态
      callClassificationData.value = {
          call_count_by_tag: response.call_count_by_tag || {},
          call_avg_time: response.call_avg_time || {}
      };
    } catch (error) {
      console.error('获取通话分类失败:', error);
      // 出错时清空数据
      callClassificationData.value = { call_count_by_tag: {}, call_avg_time: {} };
    }
  } else {
    // 如果没有选中的成员，则清空数据
    callClassificationData.value = { call_count_by_tag: {}, call_avg_time: {} };
  }
}

// 获取二阶分析报告数据
async function fetchAnalysisReport() {
  if (props.selectedMember && props.selectedMember.user_name) {
    isReportLoading.value = true;
    try {
      const response = await GetSecondOrderAnalysisReport({
        user_name: props.selectedMember.user_name
      });
      console.log('获取分析报告数据:', response.data);
      // 将获取到的数据赋值给分析报告变量
      analysisReport.value = response.data;
    } catch (error) {
      console.error('获取分析报告失败:', error);
      analysisReport.value = '';
    } finally {
      isReportLoading.value = false;
    }
  }
}

// 监听selectedMember变化
watch(() => props.selectedMember, (newMember) => {
  if (newMember) {
    // 成员变化时，获取新的通话分类数据
    updateCallClassificationData();    
    // 获取分析报告数据
    fetchAnalysisReport();
    // 重置滚动位置
    nextTick(() => {
      const container = document.querySelector('.member-details')
      if (container) container.scrollTop = 0;
    })
  }
}, { immediate: true, deep: true }) // 使用 immediate: true 和 deep: true

</script>

<style lang="scss" scoped>
// Member Details
.member-details {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  height: 600px; // 固定高度
  overflow-y: auto; // 整个卡片可滚动
  
  // 自定义滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;
    
    &:hover {
      background: #94a3b8;
    }
  }
  
  h2 {
    font-size: 1.2rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 1.5rem 0;
  }
  
  .details-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 0.5rem;
    flex: 1;
    align-content: start;
  }
  
  .detail-card {
    background: #f8fafc;
    border-radius: 8px;
    padding: 0.5rem;
    text-align: center;
    
    .detail-label {
      color: #64748b;
      font-size: 0.85rem;
      margin-bottom: 0.5rem;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.25rem;
      
      .info-icon {
        color: #94a3b8;
        font-size: 0.75rem;
        cursor: pointer;
        opacity: 0.7;
        transition: all 0.2s ease;
        margin-left: 0.25rem;
        
        &:hover {
          opacity: 1;
          color: #3b82f6;
          transform: scale(1.1);
        }
      }
    }
    
    .detail-value {
      color: #1e293b;
      font-size: 1.1rem;
      font-weight: 600;
    }
  }
}

// 详细数据折叠功能样式
.details-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  padding: 0.5rem 0;
  border-bottom: 1px solid #e2e8f0;
  margin-bottom: 1rem;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: #f8fafc;
    border-radius: 4px;
    padding: 0.5rem;
    margin: 0 -0.5rem 1rem -0.5rem;
  }
  
  h2 {
    margin: 0;
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
  }
}

.collapse-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  background-color: #f1f5f9;
  color: #64748b;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: #e2e8f0;
    color: #475569;
  }
  
  svg {
    transition: transform 0.2s ease;
  }
  
  &.collapsed svg {
    transform: rotate(180deg);
  }
}

.details-grid, .analysis-content, .guidance-content { // 【修改】统一折叠动画
  transition: all 0.3s ease;
  
  &.collapsing {
    opacity: 0;
    transform: translateY(-10px);
  }
}

/* 【新增】通话分类统计样式 */
.call-analysis-section {
  margin-top: 1.5rem;

  .analysis-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    padding: 0.5rem 0;
    border-bottom: 1px solid #e2e8f0;
    margin-bottom: 1rem;
    transition: all 0.2s ease;

    &:hover {
      background-color: #f8fafc;
      border-radius: 4px;
      padding: 0.5rem;
      margin: 0 -0.5rem 1rem -0.5rem;
    }

    h3 {
      font-size: 1.1rem;
      font-weight: 600;
      color: #1e293b;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
  }

  .analysis-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .analysis-item {
    display: grid;
    grid-template-columns: 1fr auto;
    grid-template-areas:
      "label stats"
      "progress progress";
    gap: 0.25rem 1rem;
    align-items: center;
  }

  .analysis-label {
    grid-area: label;
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    font-size: 0.9rem;
    color: #334155;
    
    .tag-name {
      font-weight: 500;
    }

    .call-count {
      font-size: 0.8rem;
      color: #64748b;
    }
  }

  .progress-bar-container {
    grid-area: progress;
    width: 100%;
    background-color: #e2e8f0;
    border-radius: 4px;
    height: 8px;
    overflow: hidden;
  }

  .progress-bar {
    height: 100%;
    background-color: #3b82f6;
    border-radius: 4px;
    transition: width 0.3s ease-in-out;
  }

  .analysis-stats {
    grid-area: stats;
    display: flex;
    align-items: baseline;
    gap: 0.75rem;
    font-size: 0.85rem;

    .percentage {
      font-weight: 600;
      color: #1e293b;
      min-width: 45px;
      text-align: right;
    }

    .avg-time {
      color: #64748b;
    }
  }
  
  .no-data {
    text-align: center;
    padding: 1.5rem;
    background: #f8fafc;
    border-radius: 8px;
    color: #94a3b8;
  }
}
/* 【新增】样式结束 */


// 指导建议样式
.guidance-section {
  margin-top: 1.5rem;
}

.guidance-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  padding: 0.5rem 0;
  border-bottom: 1px solid #e2e8f0;
  margin-bottom: 1rem;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: #f8fafc;
    border-radius: 4px;
    padding: 0.5rem;
    margin: 0 -0.5rem 1rem -0.5rem;
  }
  
  h3 {
    font-size: 1.1rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
}

// 分析报告样式
.analysis-report {
  background: #f8fafc;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.25rem;
  border: 1px solid #e2e8f0;
  min-height: 100px;
  
  .loading-message {
    text-align: center;
    color: #64748b;
    font-style: italic;
    padding: 1rem;
  }
  
  .empty-message {
    text-align: center;
    color: #94a3b8;
    padding: 2rem;
    font-style: italic;
  }
  
  .report-section {
    margin-bottom: 1.5rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px dashed #e2e8f0;
    
    &:last-child {
      margin-bottom: 0;
      padding-bottom: 0;
      border-bottom: none;
    }
    
    .report-title {
      font-size: 1rem;
      font-weight: 600;
      color: #1e293b;
      margin: 0 0 0.75rem 0;
      padding: 0.5rem 0.75rem;
      background: #ffffff;
      border-left: 3px solid #3b82f6;
      border-radius: 2px;
    }
    
    .report-content {
      white-space: pre-wrap;
      line-height: 1.6;
      color: #334155;
      font-size: 0.9rem;
      padding: 0 0.5rem;
      
      h1, h2, h3 {
        color: #1e293b;
        margin: 1.25rem 0 0.75rem 0;
      }
      
      h3 {
        font-size: 1.1rem;
        border-bottom: 1px solid #e2e8f0;
        padding-bottom: 0.25rem;
      }
      
      p {
        margin: 0.5rem 0;
      }
      
      ul, ol {
        margin: 0.75rem 0;
        padding-left: 1.5rem;
      }
      
      li {
        margin: 0.25rem 0;
      }
      
      strong {
        font-weight: 600;
      }
    }
  }
  
  .report-content:not(.report-section .report-content) {
    white-space: pre-wrap;
    line-height: 1.5;
    color: #1e293b;
    font-size: 0.9rem;
  }
}

.guidance-cards {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

// 周期切换按钮样式
.period-switcher {
  display: flex;
  gap: 0.5rem;
  margin-left: auto;
  
  button {
    padding: 0.25rem 0.75rem;
    border: 1px solid #cbd5e1;
    background: white;
    border-radius: 16px;
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.2s ease;
    
    &:hover {
      background: #f1f5f9;
      border-color: #94a3b8;
    }
    
    &.active {
      background: #3b82f6;
      color: white;
      border-color: #3b82f6;
      
      &:hover {
        background: #2563eb;
        border-color: #2563eb;
      }
    }
  }
}

.guidance-card {
  background: white;
  border-radius: 8px;
  padding: 1rem;
  border: 1px solid #e2e8f0;
}

.guidance-item {
  display: flex;
  gap: 0.75rem;
  padding: 0.75rem 0;
  
  &:not(:last-child) {
    border-bottom: 1px solid #f1f5f9;
  }
}

.guidance-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  flex-shrink: 0;
  
  &.urgent {
    background: #fef2f2;
    border: 1px solid #fecaca;
  }
  
  &.warning {
    background: #fffbeb;
    border: 1px solid #fed7aa;
  }
  
  &.info {
    background: #eff6ff;
    border: 1px solid #bfdbfe;
  }
  
  &.success {
    background: #f0fdf4;
    border: 1px solid #bbf7d0;
  }
}

.guidance-content {
  flex: 1;
}

.guidance-title {
  font-size: 0.9rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 0.25rem 0;
}

.guidance-description {
  font-size: 0.8rem;
  color: #64748b;
  margin: 0 0 0.5rem 0;
  line-height: 1.4;
}

.guidance-action {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  
  .action-label {
    font-size: 0.75rem;
    font-weight: 500;
    color: #3b82f6;
  }
  
  .action-text {
    font-size: 0.8rem;
    color: #1e293b;
    background: #f8fafc;
    padding: 0.5rem;
    border-radius: 4px;
    border-left: 3px solid #3b82f6;
  }
}

// 移动端适配
@media (max-width: 768px) {
  .member-details {
    padding: 1rem;
    height: auto;
    max-height: 500px;
    
    h2 {
      font-size: 1.1rem;
      margin-bottom: 1rem;
    }
    
    .details-grid {
       grid-template-columns: repeat(2, 1fr);
       gap: 0.75rem;
     }
    
    .detail-card {
      padding: 0.75rem;
      
      .detail-label {
        font-size: 0.8rem;
      }
      
      .detail-value {
        font-size: 1rem;
      }
    }
  }

  /* 【新增】通话分类统计响应式样式 */
  .call-analysis-section {
    margin-top: 1rem;
    .analysis-header h3 {
      font-size: 1rem;
    }
    .analysis-item {
      grid-template-areas: 
        "label label"
        "progress stats";
      gap: 0.5rem;
    }
    .analysis-label {
      .tag-name { font-size: 0.85rem; }
      .call-count { font-size: 0.75rem; }
    }
    .analysis-stats {
      font-size: 0.75rem;
      gap: 0.5rem;
      justify-content: flex-end;
      .percentage {
        min-width: 40px;
      }
    }
  }
  /* 【新增】响应式样式结束 */
  
  // 指导建议适配
.guidance-section {
  margin-top: 1rem;
  
  .guidance-header {
    h3 {
      font-size: 1rem;
    }
  }
  
  .analysis-report {
    padding: 0.75rem;
    
    .report-content {
      font-size: 0.8rem;
    }
  }
  
  .guidance-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    padding: 0.5rem 0;
    
    .guidance-icon {
      width: 28px;
      height: 28px;
      font-size: 0.9rem;
    }
  }
  
  .guidance-title {
    font-size: 0.85rem;
  }
  
  .guidance-description {
    font-size: 0.75rem;
  }
  
  .guidance-action {
    .action-label {
      font-size: 0.7rem;
    }
    
    .action-text {
      font-size: 0.75rem;
      padding: 0.4rem;
    }
  }
}
}
</style>