<template>
  <div class="chart-container">
    <div class="chart-header">
      <h3>客户迫切解决的问题排行榜</h3>
      <button @click="exportData" v-if="userStore.userInfo.user_level === 4">一键导出</button>
    </div>
    <div class="chart-content">
      <div v-if="sortedData.length > 0" class="problem-ranking">
        <div 
          v-for="(item, index) in sortedData" 
          :key="item.name" 
          class="ranking-item" 
          :class="getRankingClass(index)"
        >
          <div class="rank-number">
            <span class="rank-badge" :class="getRankBadgeClass(index)">{{ index + 1 }}</span>
          </div>
          <div class="problem-info">
            <div class="problem-name">{{ item.name }}</div>
          </div>
          <div class="problem-percentage">
            <span class="percentage">{{ getPercentage(item.value) }}%</span>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: getPercentage(item.value) + '%' }"></div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <p>暂无排行榜数据</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed,onMounted } from 'vue';
import { exportCustomers, getExcellentRecordFile } from '@/api/secondTop';
import { useUserStore } from "@/stores/user";
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';
// 用户store实例
const userStore = useUserStore();

// 定义Props，接收一个包含 { name: string, value: string | number } 的数组
const props = defineProps({
  rankingData: {
    type: Array,
    default: () => [] // 默认值为空数组
  }
});

// --- 计算属性 ---
// 对传入的数据进行排序
const sortedData = computed(() => {
  if (Array.isArray(props.rankingData) && props.rankingData.length > 0) {
    // 创建一个副本进行排序，以避免直接修改 props
    return [...props.rankingData].sort((a, b) => {
      // 统一将值转换为数字进行比较
      const aValue = parseFloat(String(a.value).replace('%', '')) || 0;
      const bValue = parseFloat(String(b.value).replace('%', '')) || 0;
      return bValue - aValue;
    });
  }
  return []; // 如果没有有效数据，返回空数组
});

// --- 辅助方法 ---
// 获取百分比数值，兼容 "55%" 和 55 两种格式
const getPercentage = (value) => {
  return parseFloat(String(value).replace('%', '')) || 0;
};

// 根据排名索引返回不同的CSS类
const getRankingClass = (index) => {
  return ['rank-first', 'rank-second', 'rank-third'][index] || 'rank-other';
};

// 根据排名索引返回徽章的CSS类
const getRankBadgeClass = (index) => {
  return ['badge-gold', 'badge-silver', 'badge-bronze'][index] || 'badge-default';
};

async function exportData() {
  const params = {
    user_name: userStore.userInfo.username,
    user_level: userStore.userInfo.user_level.toString(),
  }
  
  try {
    ElMessage.info('正在导出数据，请稍候...')
    console.log('导出参数:', params)
    const res = await exportCustomers(params)
    if (res.code === 200 && res.data && res.data.length > 0) {
      // 处理数据，将复杂的嵌套对象展平
      const exportData = res.data.map(customer => {
        const flatData = {
          '昵称': customer.nickname || '',
          '性别': customer.gender || '',
          '跟进人': customer.follow_up_name || '',
          '手机号': customer.phone || '',
          '是否入群': customer.is_in_group || '',
          '用户ID': customer.mantis_user_id || '',
        }
        
        // 处理微信表单信息
        if (customer.wechat_form) {
          flatData['家长姓名'] = customer.wechat_form.name || ''
          flatData['孩子姓名'] = customer.wechat_form.child_name || ''
          flatData['孩子性别'] = customer.wechat_form.child_gender || ''
          flatData['职业'] = customer.wechat_form.occupation || ''
          flatData['孩子教育阶段'] = customer.wechat_form.child_education || ''
          flatData['与孩子关系'] = customer.wechat_form.child_relation || ''
          flatData['联系电话'] = customer.wechat_form.mobile || ''
          flatData['地区'] = customer.wechat_form.territory || ''
          flatData['创建时间'] = customer.wechat_form.created_at ? new Date(customer.wechat_form.created_at).toLocaleString() : ''
          flatData['更新时间'] = customer.wechat_form.updated_at ? new Date(customer.wechat_form.updated_at).toLocaleString() : ''
        }
        
        // 处理到课情况
        if (customer.live) {
          flatData['课一到课情况'] = customer.live['课一'] || ''
          flatData['课二到课情况'] = customer.live['课二'] || ''
          flatData['课三到课情况'] = customer.live['课三'] || ''
          flatData['课四到课情况'] = customer.live['课四'] || ''
        }
        
        // 处理问卷调查信息
        if (customer.wechat_form && customer.wechat_form.additional_info) {
          customer.wechat_form.additional_info.forEach((item) => {
            flatData[item.topic || ''] = item.answer || ''
          })
        }
        
        return flatData
      })
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(exportData)
      
      // 设置列宽
      const colWidths = [
        { wch: 10 }, // 昵称
        { wch: 6 },  // 性别
        { wch: 12 }, // 跟进人
        { wch: 15 }, // 手机号
        { wch: 10 }, // 是否入群
        { wch: 20 }, // 用户ID
        { wch: 12 }, // 家长姓名
        { wch: 12 }, // 孩子姓名
        { wch: 8 },  // 孩子性别
        { wch: 12 }, // 职业
        { wch: 12 }, // 孩子教育阶段
        { wch: 15 }, // 与孩子关系
        { wch: 15 }, // 联系电话
        { wch: 20 }, // 地区
        { wch: 20 }, // 创建时间
        { wch: 20 }, // 更新时间
      ]
      ws['!cols'] = colWidths
      
      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '客户数据')
      
      // 生成文件名（包含当前时间）
      const now = new Date()
      const fileName = `客户数据导出_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}.xlsx`
      
      // 导出文件
      XLSX.writeFile(wb, fileName)
      
      ElMessage.success(`导出成功！共导出 ${exportData.length} 条数据`)
    } else {
      alert('暂无数据可导出')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}



</script>

<style lang="scss" scoped>
/* 外部容器样式 */
.chart-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  height: 400px; /* 保持与其他卡片高度一致 */
  display: flex;
  flex-direction: column;
}

.chart-header {
  padding: 20px 20px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
  }
  
  button {
    padding: 8px 16px;
    background: linear-gradient(135deg, #409eff, #3a8ee6);
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
    
    &:hover {
      background: linear-gradient(135deg, #3a8ee6, #337ecc);
      transform: translateY(-1px);
      box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
    }
    
    &:active {
      transform: translateY(0);
      box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
    }
  }
}

.chart-content {
  padding: 20px;
  flex-grow: 1;
  overflow: hidden; /* 防止内容溢出 */
}

/* 排行榜核心样式 */
.problem-ranking {
  overflow-y: auto;
  /* 自定义滚动条样式 (可选) */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  border-radius: 8px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
  &:last-child {
    margin-bottom: 0;
  }
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.rank-number {
  margin-right: 16px;
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 14px;
  color: white;
  flex-shrink: 0;
  &.badge-gold {
    background: linear-gradient(135deg, #ffd700, #ffb300);
  }
  &.badge-silver {
    background: linear-gradient(135deg, #c0c0c0, #a8a8a8);
  }
  &.badge-bronze {
    background: linear-gradient(135deg, #cd7f32, #b8860b);
  }
  &.badge-default {
    background: linear-gradient(135deg, #6c757d, #495057);
  }
}

.problem-info {
  flex: 1;
  margin-right: 16px;
}

.problem-name {
  font-size: 16px;
  font-weight: 600;
  color: #212529;
}

.problem-percentage {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 80px;
}

.percentage {
  font-size: 16px;
  font-weight: bold;
  color: #495057;
  margin-bottom: 4px;
}

.progress-bar {
  width: 60px;
  height: 6px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
  
  .rank-first & { background: linear-gradient(90deg, #ffd700, #ffb300); }
  .rank-second & { background: linear-gradient(90deg, #c0c0c0, #a8a8a8); }
  .rank-third & { background: linear-gradient(90deg, #cd7f32, #b8860b); }
  .rank-other & { background: linear-gradient(90deg, #007bff, #0056b3); }
}

/* 空状态样式 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 16px;
}
</style>