<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>拓客活动报表</h2>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="活动ID">
          <el-input
            v-model="queryParams.eventId"
            placeholder="请输入活动ID"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 团队数据报表 -->
    <div class="report-section">
      <div class="section-header">
        <h3>团队数据报表</h3>
      </div>
      <div v-loading="teamLoading" class="report-content">
        <div v-if="teamData.length === 0" class="no-data">
          暂无数据
        </div>
        <div v-else class="waterfall-container">
          <div v-for="store in teamData" :key="store.StoreId" class="store-card-waterfall">
            <div class="store-header">
              <h4>{{ store.StoreName }}</h4>
            </div>
            <div class="teams-container">
              <div v-for="team in store.TeamList" :key="team.TeamName" class="team-card">
                <div class="team-header">
                  <span class="team-name">{{ team.TeamName }}</span>
                </div>
                <div class="team-members">
                  <div v-for="member in team.TeamUserInfo" :key="member.ExpansionUserId" class="member-row">
                    <div class="member-info">
                      <span class="member-name">{{ member.ExpansionUserName }}</span>
                    </div>
                    <div class="member-stats">
                      <span class="target">目标: {{ member.EventTarget }}</span>
                      <span class="count">完成: {{ member.ExpansionCount }}</span>
                      <span class="rate" :class="getCompletionRateClass(member.ExpansionCount, member.EventTarget)">
                        完成率: {{ getCompletionRate(member.ExpansionCount, member.EventTarget) }}%
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 门店数据报表 -->
    <div class="report-section">
      <div class="section-header">
        <h3>门店数据报表</h3>
      </div>
      <div v-loading="storeLoading" class="report-content">
        <div v-if="storeData.length === 0" class="no-data">
          暂无数据
        </div>
        <div v-else class="store-table">
          <el-table :data="storeData" stripe style="width: 100%">
            <el-table-column prop="StoreName" label="门店名称" width="150" />
            <el-table-column prop="TotalTarget" label="目标数据" width="80" align="center" />
            <el-table-column prop="CompletedTarget" label="完成数量" width="80" align="center" />
            <el-table-column label="完成率" width="150" align="center">
              <template slot-scope="scope">
                <div class="progress-container">
                  <div class="progress-bar">
                    <div 
                      class="progress-fill" 
                      :style="{ width: scope.row.CompletionRate + '%' }"
                    ></div>
                  </div>
                  <span class="progress-text">{{ scope.row.CompletionRate }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="Ranking" label="排名" width="60" align="center">
              <template slot-scope="scope">
                <span class="ranking" :class="getRankingClass(scope.row.Ranking)">
                  {{ scope.row.Ranking }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 个人数据报表 -->
    <div class="report-section">
      <div class="section-header">
        <h3>个人数据报表</h3>
      </div>
      <div v-loading="personLoading" class="report-content">
        <div v-if="personData.length === 0" class="no-data">
          暂无数据
        </div>
        <div v-else class="person-table">
          <el-table :data="personData" stripe style="width: 100%">
            <el-table-column prop="UserName" label="姓名" width="80" />
            <el-table-column prop="StoreName" label="门店" width="120" />
            <el-table-column prop="TeamName" label="团队" width="80" />
            <el-table-column prop="PersonalTarget" label="个人目标" width="70" align="center" />
            <el-table-column prop="CompletedTarget" label="完成数量" width="70" align="center" />
            <el-table-column label="完成率" width="120" align="center">
              <template slot-scope="scope">
                <div class="progress-container">
                  <div class="progress-bar">
                    <div 
                      class="progress-fill" 
                      :style="{ width: Math.min(scope.row.CompletionRate, 100) + '%' }"
                    ></div>
                  </div>
                  <span class="progress-text">{{ scope.row.CompletionRate }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="Ranking" label="排名" width="60" align="center">
              <template slot-scope="scope">
                <span class="ranking" :class="getRankingClass(scope.row.Ranking)">
                  {{ scope.row.Ranking }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="最后拓客时间" width="140" align="center">
              <template slot-scope="scope">
                {{ formatTime(scope.row.LastExpansionTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getTeamData, getStoreData, getPersonData } from '@/api/lqTkjlb'

export default {
  name: 'TkjlbReport',
  data() {
    return {
      queryParams: {
        eventId: '740360861859710213'
      },
      teamData: [],
      storeData: [],
      personData: [],
      teamLoading: false,
      storeLoading: false,
      personLoading: false
    }
  },
  created() {
    this.handleQuery()
    // 添加测试数据，确保页面正常显示
    this.addTestData()
  },
  methods: {
    // 查询数据
    handleQuery() {
      if (!this.queryParams.eventId) {
        this.$message.warning('请输入活动ID')
        return
      }
      this.getTeamData()
      this.getStoreData()
      this.getPersonData()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams.eventId = ''
      this.teamData = []
      this.storeData = []
      this.personData = []
    },

    // 获取团队数据
    async getTeamData() {
      this.teamLoading = true
      try {
        console.log('正在获取团队数据...')
        const response = await getTeamData(this.queryParams.eventId)
        console.log('团队数据响应:', response)
        this.teamData = response.data || []
        console.log('团队数据:', this.teamData)
      } catch (error) {
        console.error('获取团队数据失败:', error)
        this.$message.error('获取团队数据失败: ' + error.message)
        this.teamData = []
      } finally {
        this.teamLoading = false
      }
    },

    // 获取门店数据
    async getStoreData() {
      this.storeLoading = true
      try {
        console.log('正在获取门店数据...')
        const response = await getStoreData(this.queryParams.eventId)
        console.log('门店数据响应:', response)
        this.storeData = response.data || []
        console.log('门店数据:', this.storeData)
      } catch (error) {
        console.error('获取门店数据失败:', error)
        this.$message.error('获取门店数据失败: ' + error.message)
        this.storeData = []
      } finally {
        this.storeLoading = false
      }
    },

    // 获取个人数据
    async getPersonData() {
      this.personLoading = true
      try {
        console.log('正在获取个人数据...')
        const response = await getPersonData(this.queryParams.eventId)
        console.log('个人数据响应:', response)
        this.personData = response.data || []
        console.log('个人数据:', this.personData)
      } catch (error) {
        console.error('获取个人数据失败:', error)
        this.$message.error('获取个人数据失败: ' + error.message)
        this.personData = []
      } finally {
        this.personLoading = false
      }
    },

    // 计算完成率
    getCompletionRate(completed, target) {
      if (target === 0) return 0
      return Math.round((completed / target) * 100)
    },

    // 获取完成率样式类
    getCompletionRateClass(completed, target) {
      const rate = this.getCompletionRate(completed, target)
      if (rate >= 100) return 'rate-excellent'
      if (rate >= 80) return 'rate-good'
      if (rate >= 60) return 'rate-normal'
      return 'rate-poor'
    },

    // 获取排名样式类
    getRankingClass(ranking) {
      if (ranking <= 3) return 'ranking-top'
      if (ranking <= 6) return 'ranking-good'
      return 'ranking-normal'
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '无'
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN')
    },

    // 添加测试数据
    addTestData() {
      // 如果API调用失败，添加一些测试数据确保页面正常显示
      setTimeout(() => {
        if (this.teamData.length === 0) {
          this.teamData = [
            {
              "StoreId": "1649328471923847186",
              "StoreName": "绿纤骑士郡店",
              "TeamList": [
                {
                  "TeamName": "咕噜队",
                  "TeamUserInfo": [
                    {
                      "ExpansionUserId": "17882512738",
                      "ExpansionUserName": "梁诗雨",
                      "ExpansionCount": 6,
                      "EventTarget": 100
                    },
                    {
                      "ExpansionUserId": "admin",
                      "ExpansionUserName": "管理员",
                      "ExpansionCount": 0,
                      "EventTarget": 6
                    }
                  ]
                }
              ]
            }
          ]
        }
        
        if (this.storeData.length === 0) {
          this.storeData = [
            {
              "StoreId": "1649328471923847190",
              "StoreName": "绿纤亚洲湾店",
              "TotalTarget": 6,
              "CompletedTarget": 6,
              "CompletionRate": 100,
              "Ranking": 1
            },
            {
              "StoreId": "1649328471923847169",
              "StoreName": "绿纤紫荆店",
              "TotalTarget": 3,
              "CompletedTarget": 3,
              "CompletionRate": 100,
              "Ranking": 2
            }
          ]
        }
        
        if (this.personData.length === 0) {
          this.personData = [
            {
              "UserId": "19982024821",
              "UserName": "谢珂欣",
              "StoreId": "1649328471923847190",
              "StoreName": "绿纤亚洲湾店",
              "TeamName": "9444",
              "PersonalTarget": 1,
              "CompletedTarget": 6,
              "CompletionRate": 600,
              "Ranking": 1,
              "LastExpansionTime": 1758699730000
            },
            {
              "UserId": "17780181798",
              "UserName": "王任燕",
              "StoreId": "1649328471923847175",
              "StoreName": "绿纤468店",
              "TeamName": "222",
              "PersonalTarget": 1,
              "CompletedTarget": 3,
              "CompletionRate": 300,
              "Ranking": 2,
              "LastExpansionTime": 1758699412000
            }
          ]
        }
      }, 2000) // 2秒后添加测试数据
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 12px;
  background-color: #f5f5f5;
  min-height: 100vh;
  overflow-y: scroll;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 12px;
  
  h2 {
    margin: 0;
    color: #303133;
    font-size: 20px;
    font-weight: 500;
  }
}

.filter-container {
  background: white;
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.report-section {
  background: white;
  border-radius: 6px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  background: #409EFF;
  color: white;
  padding: 10px 16px;
  
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }
}

.report-content {
  padding: 12px;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 20px 0;
  font-size: 14px;
}

// 瀑布流容器
.waterfall-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: flex-start;
}

// 团队数据样式 - 瀑布流版本
.store-card-waterfall {
  width: calc(25% - 9px); // 25%宽度减去gap的一半
  margin-bottom: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  
  // 响应式设计
  @media (max-width: 1200px) {
    width: calc(33.333% - 8px); // 3列
  }
  
  @media (max-width: 900px) {
    width: calc(50% - 6px); // 2列
  }
  
  @media (max-width: 600px) {
    width: 100%; // 1列
  }
}

// 原有的store-card样式保留，用于其他报表
.store-card {
  margin-bottom: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.store-header {
  background: #f8f9fa;
  padding: 8px 12px;
  border-bottom: 1px solid #e4e7ed;
  
  h4 {
    margin: 0;
    color: #303133;
    font-size: 14px;
    font-weight: 500;
  }
}

.teams-container {
  padding: 8px;
}

.team-card {
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.team-header {
  background: #f0f2f5;
  padding: 6px 8px;
  border-bottom: 1px solid #e4e7ed;
  
  .team-name {
    font-weight: 500;
    color: #606266;
    font-size: 13px;
  }
}

.team-members {
  padding: 6px;
}

.member-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  border-bottom: 1px solid #f0f2f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.member-info {
  flex: 1;
  min-width: 0; // 防止内容溢出
  
  .member-name {
    font-weight: 500;
    color: #303133;
    font-size: 12px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.member-stats {
  display: flex;
  gap: 8px;
  flex-shrink: 0; // 防止统计信息被压缩
  
  span {
    font-size: 10px;
    white-space: nowrap;
    
    &.target {
      color: #606266;
    }
    
    &.count {
      color: #409EFF;
      font-weight: 500;
    }
    
    &.rate {
      font-weight: 500;
      
      &.rate-excellent {
        color: #67C23A;
      }
      
      &.rate-good {
        color: #409EFF;
      }
      
      &.rate-normal {
        color: #E6A23C;
      }
      
      &.rate-poor {
        color: #F56C6C;
      }
    }
  }
}

// 表格样式
.store-table{
  width: 100%;
}
.store-table, .person-table {
  .el-table {
    border-radius: 4px;
    overflow: hidden;
    font-size: 12px;
  }
  
  .el-table th {
    padding: 8px 0;
    font-size: 12px;
  }
  
  .el-table td {
    padding: 6px 0;
    font-size: 12px;
  }
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 6px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #f0f2f5;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #409EFF;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 11px;
  color: #606266;
  min-width: 35px;
  text-align: right;
}

.ranking {
  font-weight: 500;
  font-size: 12px;
  
  &.ranking-top {
    color: #F56C6C;
  }
  
  &.ranking-good {
    color: #E6A23C;
  }
  
  &.ranking-normal {
    color: #606266;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }
  
  .waterfall-container {
    gap: 8px;
  }
  
  .store-card-waterfall {
    width: 100% !important; // 移动端强制单列
  }
  
  .member-stats {
    gap: 4px;
    
    span {
      font-size: 9px;
    }
  }
  
  .progress-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 2px;
  }
}
</style>
