<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <div class="NCC-common-layout-main NCC-flex-main">
        <div class="NCC-common-head">
          <div>
            <h2>拓客报表</h2>
          </div>
          <div class="NCC-common-head-right">
            <el-button type="primary" icon="el-icon-back" @click="goBackToList">返回列表</el-button>
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false" @click="initData" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        
        <!-- Tab 切换 -->
        <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="report-tabs">
          <el-tab-pane label="总体统计" name="overview">
            <!-- 统计卡片 -->
            <el-row :gutter="20" class="statistics-cards">
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon">
                      <i class="el-icon-user"></i>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ totalTeams }}</div>
                      <div class="stat-label">参与战队数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon">
                      <i class="el-icon-s-data"></i>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ totalMembers }}</div>
                      <div class="stat-label">总拓客人数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon">
                      <i class="el-icon-trophy"></i>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ topTeam }}</div>
                      <div class="stat-label">冠军战队</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 图表展示 -->
            <el-row :gutter="20" class="chart-section">
              <el-col :span="12">
                <el-card class="chart-card">
                  <div slot="header" class="clearfix">
                    <span>战队拓客人数分布</span>
                  </div>
                  <div class="chart-container" ref="pieChart"></div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="chart-card">
                  <div slot="header" class="clearfix">
                    <span>拓客排行榜</span>
                  </div>
                  
                  <div class="ranking-table-container">
                    <NCC-table v-loading="listLoading" :data="rankingList" stripe size="mini">
                      <el-table-column prop="ranking" label="排名" width="60" align="center">
                        <template slot-scope="scope">
                          <div class="ranking-badge-small" :class="getRankingClass(scope.row.ranking)">
                            {{ scope.row.ranking }}
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="sszd" label="战队" align="left" min-width="100">
                        <template slot-scope="scope">
                          <span class="team-name-small">{{ scope.row.sszd || '未分配' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="tkrs" label="人数" align="center" width="60">
                        <template slot-scope="scope">
                          <span class="member-count-small">{{ scope.row.tkrs }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="占比" align="center" width="80">
                        <template slot-scope="scope">
                          <el-progress 
                            :percentage="getPercentage(scope.row.tkrs)" 
                            :color="getProgressColor(scope.row.ranking)"
                            :stroke-width="6"
                            :show-text="false">
                          </el-progress>
                        </template>
                      </el-table-column>
                    </NCC-table>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="战队详情" name="teamDetail">
            <!-- 战队人员详细报表 -->
            <div class="team-detail-section">
              <el-row :gutter="20" class="team-overview">
                <el-col :span="24">
                  <el-card class="overview-card">
                    <div slot="header" class="clearfix">
                      <span>战队拓客总览</span>
                      <div class="header-right">
                        <span class="total-count">总拓客数: {{ totalTeamCount }}</span>
                        <el-button style="margin-left: 15px; padding: 3px 0" type="text" @click="refreshTeamDetail">
                          <i class="el-icon-refresh"></i> 刷新
                        </el-button>
                      </div>
                    </div>
                    <el-row :gutter="20">
                      <el-col :span="6" v-for="team in teamDetailList" :key="team.sszd">
                        <div class="team-summary-card">
                          <div class="team-header">
                            <h4>{{ team.sszd || '未分配' }}</h4>
                            <span class="team-total">总计: {{ team.totalCount }}</span>
                          </div>
                          <div class="team-members">
                            <div class="member-item" v-for="member in team.members" :key="member.tkry">
                              <span class="member-name">{{ member.tkry }}</span>
                              <span class="member-count">{{ member.tkrs }}</span>
                            </div>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                  </el-card>
                </el-col>
              </el-row>
              
              <!-- 详细表格 - 暂时隐藏 -->
              <!-- 
              <el-row :gutter="20" class="detail-table-section">
                <el-col :span="24">
                  <el-card class="detail-card">
                    <div slot="header" class="clearfix">
                      <span>战队人员详细报表</span>
                    </div>
                    <div class="detail-table-container">
                      <NCC-table v-loading="teamDetailLoading" :data="flattenedTeamDetail" stripe>
                        <el-table-column prop="sszd" label="战队" align="left" min-width="120">
                          <template slot-scope="scope">
                            <span class="team-name">{{ scope.row.sszd || '未分配' }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="tkry" label="拓客人员" align="left" min-width="120">
                          <template slot-scope="scope">
                            <span class="member-name">{{ scope.row.tkry }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="tkrs" label="拓客数量" align="center" width="100">
                          <template slot-scope="scope">
                            <span class="member-count">{{ scope.row.tkrs }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="teamRanking" label="战队内排名" align="center" width="100">
                          <template slot-scope="scope">
                            <div class="ranking-badge" :class="getTeamRankingClass(scope.row.teamRanking)">
                              {{ scope.row.teamRanking }}
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="percentage" label="战队内占比" align="center" width="120">
                          <template slot-scope="scope">
                            <el-progress 
                              :percentage="scope.row.percentage" 
                              :color="getTeamProgressColor(scope.row.teamRanking)"
                              :stroke-width="8"
                              :show-text="true">
                            </el-progress>
                          </template>
                        </el-table-column>
                      </NCC-table>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              -->
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import * as echarts from 'echarts'

export default {
  name: 'LqTkjlbReport',
  data() {
    return {
      listLoading: true,
      rankingList: [],
      totalTeams: 0,
      totalMembers: 0,
      topTeam: '',
      pieChart: null,
      activeTab: 'overview', // 默认显示总体统计
      teamDetailList: [], // 用于存储战队人员详细报表的数据
      teamDetailLoading: true, // 战队人员详细报表的加载状态
      flattenedTeamDetail: [], // 用于存储扁平化的战队人员详细报表数据
      totalTeamCount: 0 // 所有战队拓客总数
    }
  },
  computed: {},
  created() {
    this.initData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  beforeDestroy() {
    if (this.pieChart) {
      this.pieChart.dispose()
    }
  },
  methods: {
    // 初始化数据
    async initData() {
      this.listLoading = true
      try {
        const res = await request({
          url: '/api/Extend/LqTkjlb/Actions/GetRanking',
          method: 'GET'
        })
        
        this.rankingList = res.data || []
        this.calculateStatistics()
        this.updateCharts()
      } catch (error) {
        console.error('获取拓客排行榜失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.listLoading = false
      }
    },

    // 计算统计数据
    calculateStatistics() {
      this.totalTeams = this.rankingList.length
      this.totalMembers = this.rankingList.reduce((sum, item) => sum + item.tkrs, 0)
      this.topTeam = this.rankingList.length > 0 ? this.rankingList[0].sszd || '未分配' : '无数据'
    },

    // 获取排名样式类
    getRankingClass(ranking) {
      if (ranking === 1) return 'rank-gold'
      if (ranking === 2) return 'rank-silver'
      if (ranking === 3) return 'rank-bronze'
      return 'rank-normal'
    },

    // 获取进度条颜色
    getProgressColor(ranking) {
      if (ranking === 1) return '#FFD700'
      if (ranking === 2) return '#C0C0C0'
      if (ranking === 3) return '#CD7F32'
      return '#409EFF'
    },

    // 计算占比
    getPercentage(count) {
      if (this.totalMembers === 0) return 0
      return Math.round((count / this.totalMembers) * 100)
    },

    // 初始化图表
    initCharts() {
      // 饼图
      this.pieChart = echarts.init(this.$refs.pieChart)
      
      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        this.pieChart && this.pieChart.resize()
      })
    },

    // 更新图表数据
    updateCharts() {
      this.updatePieChart()
    },

    // 更新饼图
    updatePieChart() {
      if (!this.pieChart || this.rankingList.length === 0) return

      const data = this.rankingList.map(item => ({
        name: item.sszd || '未分配',
        value: item.tkrs
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '拓客人数',
            type: 'pie',
            radius: '50%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

      this.pieChart.setOption(option)
    },

    // 返回列表页面
    goBackToList() {
      this.$router.push('/lqTkjlb')
    },

    // 导出排行榜
    exportRanking() {
      // 这里可以调用导出接口
      this.$message.success('导出功能开发中...')
    },

    // 切换 Tab 时触发
    handleTabClick(tab) {
      if (tab.paneName === 'teamDetail') {
        this.loadTeamDetail()
      }
    },

    // 加载战队人员详细报表数据
    async loadTeamDetail() {
      this.teamDetailLoading = true
      try {
        const res = await request({
          url: '/api/Extend/LqTkjlb/Actions/GetTeamDetail',
          method: 'GET'
        })
        this.teamDetailList = res.data || []
        this.calculateTotalTeamCount() // 计算总拓客数
        this.flattenTeamDetail() // 扁平化数据
      } catch (error) {
        console.error('获取战队人员详细报表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.teamDetailLoading = false
      }
    },

    // 计算所有战队拓客总数
    calculateTotalTeamCount() {
      this.totalTeamCount = this.teamDetailList.reduce((total, team) => {
        return total + (team.totalCount || 0)
      }, 0)
    },

    // 扁平化战队人员详细报表数据
    flattenTeamDetail() {
      this.flattenedTeamDetail = []
      this.teamDetailList.forEach(team => {
        team.members.forEach(member => {
          this.flattenedTeamDetail.push({
            sszd: team.sszd,
            tkry: member.tkry,
            tkrs: member.tkrs,
            teamRanking: member.teamRanking,
            percentage: member.percentage
          })
        })
      })
    },

    // 刷新战队人员详细报表数据
    refreshTeamDetail() {
      this.loadTeamDetail()
    },

    // 获取战队排名样式类
    getTeamRankingClass(ranking) {
      if (ranking === 1) return 'rank-gold'
      if (ranking === 2) return 'rank-silver'
      if (ranking === 3) return 'rank-bronze'
      return 'rank-normal'
    },

    // 获取战队进度条颜色
    getTeamProgressColor(ranking) {
      if (ranking === 1) return '#FFD700'
      if (ranking === 2) return '#C0C0C0'
      if (ranking === 3) return '#CD7F32'
      return '#409EFF'
    }
  }
}
</script>

<style lang="scss" scoped>
// 全局页面布局样式
.NCC-common-layout {
  height: 100%;
  overflow: auto;
}

.NCC-common-layout-center {
  height: 100%;
  overflow: auto;
}

.NCC-common-layout-main {
  height: 100%;
  overflow: auto;
  padding: 20px;
}
.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      font-size: 48px;
      color: #409EFF;
      margin-right: 20px;
    }
    
    .stat-info {
      .stat-number {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 5px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

.ranking-card {
  margin-bottom: 20px;
  
  // 确保表格容器有足够的高度和宽度
  .el-card__body {
    padding: 20px;
    overflow: visible;
  }
  
  // 表格容器样式
  .NCC-table {
    width: 100%;
    
    // 确保表格行高度足够
    .el-table__row {
      height: 50px;
    }
    
    // 表格单元格样式
    .el-table__cell {
      padding: 8px 0;
      line-height: 1.5;
    }
    
    // 确保表格内容不被遮挡
    .el-table__body-wrapper {
      overflow: visible;
      max-height: none;
    }
    
    // 表格头部样式
    .el-table__header-wrapper {
      overflow: visible;
    }
    
    // 确保表格容器有足够的空间
    .el-table {
      width: 100% !important;
      min-width: 800px;
    }
    
    // 表格行样式
    .el-table__row {
      td {
        padding: 12px 0;
        height: auto;
        min-height: 50px;
        vertical-align: middle;
      }
    }
  }
}

.ranking-badge {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
  color: white;
  
  &.rank-gold {
    background: linear-gradient(135deg, #FFD700, #FFA500);
  }
  
  &.rank-silver {
    background: linear-gradient(135deg, #C0C0C0, #A9A9A9);
  }
  
  &.rank-bronze {
    background: linear-gradient(135deg, #CD7F32, #B8860B);
  }
  
  &.rank-normal {
    background: #409EFF;
  }
}

// 小尺寸排行榜徽章样式
.ranking-badge-small {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
  color: white;
  font-size: 12px;
  
  &.rank-gold {
    background: linear-gradient(135deg, #FFD700, #FFA500);
  }
  
  &.rank-silver {
    background: linear-gradient(135deg, #C0C0C0, #A9A9A9);
  }
  
  &.rank-bronze {
    background: linear-gradient(135deg, #CD7F32, #B8860B);
  }
  
  &.rank-normal {
    background: #409EFF;
  }
}

.team-name {
  font-weight: 500;
  color: #303133;
}

.team-name-small {
  font-weight: 500;
  color: #303133;
  font-size: 12px;
}

.member-count {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.member-count-small {
  font-size: 14px;
  font-weight: bold;
  color: #409EFF;
}

.trend-indicator {
  font-size: 20px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  .chart-container {
    height: 300px;
    width: 100%;
  }
  
  .ranking-table-container {
    height: 300px;
    width: 100%;
    overflow: auto;
    
    .NCC-table {
      .el-table {
        font-size: 12px;
      }
      
      .el-table__row {
        td {
          padding: 8px 0;
          height: auto;
          min-height: 40px;
        }
      }
    }
  }
}

.el-progress {
  margin: 0;
}

// 确保表格内容完全显示
.el-table {
  .el-table__body-wrapper {
    overflow: visible !important;
    max-height: none !important;
  }
  
  .el-table__header-wrapper {
    overflow: visible !important;
  }
  
  .el-table__fixed-body-wrapper {
    overflow: visible !important;
    max-height: none !important;
  }
}

// 确保卡片内容不被遮挡
.el-card {
  .el-card__body {
    overflow: visible;
    padding: 20px;
  }
}

// 确保页面容器有足够的空间
.NCC-common-layout-main {
  min-height: calc(100vh - 120px);
  overflow: auto;
}

// 新增的样式
.report-tabs {
  .el-tabs__content {
    padding: 20px;
  }
}

.team-detail-section {
  .team-overview {
    margin-bottom: 20px;
  }

  .overview-card {
    .el-card__body {
      padding: 20px;
    }
  }

  .team-summary-card {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 20px;
    background: #fafafa;
    transition: all 0.3s;
    
    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }
    
    .team-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      
      h4 {
        margin: 0;
        font-size: 16px;
        color: #303133;
        font-weight: 600;
      }
      
      .team-total {
        font-size: 14px;
        color: #409EFF;
        font-weight: 500;
        background: #ecf5ff;
        padding: 4px 8px;
        border-radius: 12px;
      }
    }
    
    .team-members {
      .member-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        padding: 8px 12px;
        background: white;
        border-radius: 4px;
        border-left: 3px solid #409EFF;
        
        &:hover {
          background: #f5f7fa;
        }
        
        .member-name {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
        }
        
        .member-count {
          font-size: 14px;
          font-weight: bold;
          color: #409EFF;
          background: #ecf5ff;
          padding: 2px 8px;
          border-radius: 10px;
          min-width: 30px;
          text-align: center;
        }
      }
    }
  }

  .detail-table-section {
    .detail-card {
      .el-card__body {
        padding: 20px;
      }
    }
    
    .detail-table-container {
      .NCC-table {
        .el-table {
          .el-table__row {
            td {
              padding: 12px 0;
              height: auto;
              min-height: 50px;
            }
          }
        }
      }
    }
  }
}

// 确保 tab 内容区域有合适的间距
.el-tabs__content {
  padding: 20px 0;
}

// 战队总览头部样式
.overview-card {
  .el-card__header {
    .header-right {
      float: right;
      display: flex;
      align-items: center;
      
      .total-count {
        font-size: 16px;
        font-weight: 600;
        color: #409EFF;
        background: #ecf5ff;
        padding: 6px 12px;
        border-radius: 16px;
        border: 1px solid #d9ecff;
      }
    }
  }
}

// 战队名称样式
.team-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

// 成员名称样式
.member-name {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

// 成员数量样式
.member-count {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

</style>
