<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>
        
        <!-- 活动选择区域 -->
        <div class="event-selector-container">
          <el-card class="selector-card">
            <div class="selector-content">
              <div class="selector-item">
                <label class="selector-label">选择活动：</label>
                <el-select 
                  v-model="selectedEventId" 
                  placeholder="请选择拓客活动" 
                  clearable 
                  filterable
                  @change="onEventChange"
                  style="width: 300px;">
                  <el-option 
                    v-for="event in eventOptions" 
                    :key="event.id" 
                    :label="event.eventName" 
                    :value="event.id">
                  </el-option>
                </el-select>
              </div>
              <div class="selector-item">
                <el-button type="primary" @click="loadTeamData" :loading="listLoading">
                  <i class="el-icon-search"></i> 查询数据
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 统计概览卡片 -->
        <div class="statistics-overview">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-icon">
                  <i class="el-icon-shop"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ teamDataList.length }}</div>
                  <div class="stat-label">参与门店</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-icon">
                  <i class="el-icon-user-solid"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ getTotalTeams() }}</div>
                  <div class="stat-label">参与战队</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-icon">
                  <i class="el-icon-user"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ getTotalMembers() }}</div>
                  <div class="stat-label">参与人员</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-icon">
                  <i class="el-icon-trophy"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ totalExpansionCount }}</div>
                  <div class="stat-label">总拓客数</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 团队数据报表 - 瀑布流布局 -->
        <div class="team-report-container">
          <div class="report-header">
            <div class="header-left">
              <h3>团队拓客数据统计</h3>
              <span class="subtitle">Team Performance Report</span>
            </div>
            <div class="header-right">
              <el-button type="success" icon="el-icon-camera" @click="saveScreenshot" :loading="screenshotLoading">
                保存截图
              </el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="initData" :loading="listLoading" style="margin-left: 8px;">
                刷新数据
              </el-button>
            </div>
          </div>
          
          <div v-loading="listLoading" class="waterfall-container">
            <div v-for="(store, storeIndex) in teamDataList" :key="store.StoreId" class="store-card">
              <div class="store-header">
                <div class="store-icon">
                  <i class="el-icon-shop"></i>
                </div>
                <div class="store-info">
                  <div class="store-name">{{ store.StoreName || '无' }}</div>
                  <div class="store-total">总计: {{ getStoreTotal(store.TeamList) }}</div>
                </div>
                <div class="store-index">{{ storeIndex + 1 }}</div>
              </div>
              
              <div class="teams-container">
                <div v-for="(team, teamIndex) in store.TeamList" :key="team.TeamName" class="team-card">
                  <div class="team-header">
                    <div class="team-name">
                      <i class="el-icon-user-solid"></i>
                      {{ team.TeamName || '无' }}
                    </div>
                    <div class="team-total">{{ getTeamTotal(team.TeamUserInfo) }}</div>
                  </div>
                  
                  <div class="members-container">
                    <div v-for="member in team.TeamUserInfo" :key="member.ExpansionUserId" class="member-card">
                      <div class="member-name">
                        <i class="el-icon-user"></i>
                        {{ member.ExpansionUserName || '无' }}
                      </div>
                      <div class="member-stats">
                        <div class="stat-item">
                          <span class="stat-label">目标</span>
                          <span class="stat-value target">{{ member.EventTarget || 0 }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">完成</span>
                          <span class="stat-value count">{{ member.ExpansionCount || 0 }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">完成率</span>
                          <span class="completion-rate" :class="getCompletionClass(member.ExpansionCount, member.EventTarget)">
                            {{ getCompletionRate(member.ExpansionCount, member.EventTarget) }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片预览对话框 -->
    <el-dialog
      title="截图预览"
      :visible.sync="previewVisible"
      width="90%"
      :before-close="handlePreviewClose"
      :close-on-click-modal="false"
      class="screenshot-dialog">
      <div class="preview-container">
        <div v-if="screenshotDataUrl" class="image-wrapper">
          <img :src="screenshotDataUrl" alt="统计截图" class="preview-image" />
          <div class="image-info">
            <span class="image-size">{{ getImageSize() }}</span>
          </div>
        </div>
        <div v-else class="no-image">
          <i class="el-icon-picture-outline"></i>
          <p>暂无截图</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="success" @click="downloadScreenshot" :disabled="!screenshotDataUrl">
          <i class="el-icon-download"></i> 下载图片
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'LqTkjlbTeamReport',
  data() {
    return {
      listLoading: true,
      teamDataList: [],
      totalExpansionCount: 0,
      selectedEventId: '',
      eventOptions: [],
      screenshotLoading: false,
      previewVisible: false,
      screenshotDataUrl: '',
      imageWidth: 0,
      imageHeight: 0
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 初始化数据
    async initData() {
      await this.loadEventOptions()
      if (this.selectedEventId) {
        await this.loadTeamData()
      }
    },

    // 加载活动选项
    async loadEventOptions() {
      try {
        const res = await request({
          url: '/api/Extend/lqevent',
          method: 'GET'
        })
        
        this.eventOptions = res.data.list || []
        // 默认选择第一个活动
        if (this.eventOptions.length > 0) {
          this.selectedEventId = this.eventOptions[0].id
        }
      } catch (error) {
        console.error('获取活动列表失败:', error)
        this.$message.error('获取活动列表失败')
      }
    },

    // 加载团队数据
    async loadTeamData() {
      if (!this.selectedEventId) {
        this.$message.warning('请先选择活动')
        return
      }

      this.listLoading = true
      try {
        const res = await request({
          url: '/api/Extend/lqevent/team-data/'+this.selectedEventId,
          method: 'GET',
        })
        
        this.teamDataList = res.data || []
        this.calculateTotalCount()
      } catch (error) {
        console.error('获取团队数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.listLoading = false
      }
    },

    // 活动选择变化
    onEventChange() {
      if (this.selectedEventId) {
        this.loadTeamData()
      } else {
        this.teamDataList = []
        this.totalExpansionCount = 0
      }
    },

    // 计算总拓客数
    calculateTotalCount() {
      this.totalExpansionCount = 0
      this.teamDataList.forEach(store => {
        store.TeamList.forEach(team => {
          team.TeamUserInfo.forEach(member => {
            this.totalExpansionCount += member.ExpansionCount || 0
          })
        })
      })
    },

    // 计算完成率
    getCompletionRate(expansionCount, eventTarget) {
      if (!eventTarget || eventTarget === 0) {
        return '0%'
      }
      const rate = Math.round((expansionCount / eventTarget) * 100)
      return `${rate}%`
    },

    // 获取完成率样式类
    getCompletionClass(expansionCount, eventTarget) {
      if (!eventTarget || eventTarget === 0) {
        return 'completion-zero'
      }
      const rate = (expansionCount / eventTarget) * 100
      if (rate >= 100) {
        return 'completion-excellent'
      } else if (rate >= 80) {
        return 'completion-good'
      } else if (rate >= 60) {
        return 'completion-normal'
      } else {
        return 'completion-poor'
      }
    },

    // 计算团队总计
    getTeamTotal(teamUserInfo) {
      return teamUserInfo.reduce((total, member) => {
        return total + (member.ExpansionCount || 0)
      }, 0)
    },

    // 计算门店总计（所有团队的总和）
    getStoreTotal(teamList) {
      return teamList.reduce((total, team) => {
        return total + this.getTeamTotal(team.TeamUserInfo)
      }, 0)
    },

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

    // 获取总战队数
    getTotalTeams() {
      let total = 0
      this.teamDataList.forEach(store => {
        total += store.TeamList.length
      })
      return total
    },

    // 获取总人员数
    getTotalMembers() {
      let total = 0
      this.teamDataList.forEach(store => {
        store.TeamList.forEach(team => {
          total += team.TeamUserInfo.length
        })
      })
      return total
    },

    // 保存截图
    async saveScreenshot() {
      this.screenshotLoading = true
      try {
        // 动态导入html2canvas
        const html2canvas = await import('html2canvas')
        
        // 获取要截图的容器（包含统计概览和团队数据）
        const element = document.querySelector('.NCC-common-layout-main')
        
        if (!element) {
          this.$message.error('未找到要截图的内容')
          return
        }

        // 等待页面完全渲染
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 临时保存原始样式
        const originalStyles = {
          height: element.style.height,
          overflow: element.style.overflow,
          maxHeight: element.style.maxHeight
        }

        // 临时修改样式以确保完整截图
        element.style.height = 'auto'
        element.style.overflow = 'visible'
        element.style.maxHeight = 'none'

        // 等待样式应用
        await new Promise(resolve => setTimeout(resolve, 200))

        // 配置截图选项 - 专门针对完整内容截图
        const options = {
          allowTaint: true,
          useCORS: true,
          scale: 1.2, // 适中的清晰度
          backgroundColor: '#f5f7fa',
          logging: false,
          imageTimeout: 30000,
          removeContainer: true,
          foreignObjectRendering: true,
          scrollX: 0,
          scrollY: 0,
          width: element.scrollWidth,
          height: element.scrollHeight,
          onclone: (clonedDoc) => {
            // 在克隆的文档中确保所有容器都能完整显示
            const clonedElement = clonedDoc.querySelector('.NCC-common-layout-main')
            if (clonedElement) {
              clonedElement.style.height = 'auto'
              clonedElement.style.overflow = 'visible'
              clonedElement.style.maxHeight = 'none'
              clonedElement.style.position = 'static'
            }
            
            // 确保瀑布流容器完整显示
            const waterfallContainer = clonedDoc.querySelector('.waterfall-container')
            if (waterfallContainer) {
              waterfallContainer.style.height = 'auto'
              waterfallContainer.style.overflow = 'visible'
              waterfallContainer.style.maxHeight = 'none'
            }
            
            // 确保所有卡片完整显示
            const storeCards = clonedDoc.querySelectorAll('.store-card')
            storeCards.forEach(card => {
              card.style.height = 'auto'
              card.style.overflow = 'visible'
              card.style.maxHeight = 'none'
            })
            
            // 确保统计概览完整显示
            const statCards = clonedDoc.querySelectorAll('.stat-card')
            statCards.forEach(card => {
              card.style.height = 'auto'
              card.style.overflow = 'visible'
            })

            // 确保所有团队和成员数据完整显示
            const teamCards = clonedDoc.querySelectorAll('.team-card')
            teamCards.forEach(card => {
              card.style.height = 'auto'
              card.style.overflow = 'visible'
            })

            const memberCards = clonedDoc.querySelectorAll('.member-card')
            memberCards.forEach(card => {
              card.style.height = 'auto'
              card.style.overflow = 'visible'
            })
          },
          ignoreElements: (element) => {
            // 忽略不需要截图的元素
            return element.classList.contains('el-loading-mask') || 
                   element.classList.contains('el-message') ||
                   element.classList.contains('el-dialog__wrapper') ||
                   element.classList.contains('el-tooltip__popper')
          }
        }

        // 生成截图
        const canvas = await html2canvas.default(element, options)
        
        // 恢复原始样式
        element.style.height = originalStyles.height
        element.style.overflow = originalStyles.overflow
        element.style.maxHeight = originalStyles.maxHeight
        
        // 转换为DataURL
        this.screenshotDataUrl = canvas.toDataURL('image/png', 1.0)
        
        // 显示预览对话框
        this.previewVisible = true
        
        this.$message.success('截图生成成功')
      } catch (error) {
        console.error('截图生成失败:', error)
        this.$message.error('截图生成失败，请重试')
      } finally {
        this.screenshotLoading = false
      }
    },

    // 下载截图
    downloadScreenshot() {
      if (!this.screenshotDataUrl) {
        this.$message.error('没有可下载的图片')
        return
      }

      try {
        // 创建下载链接
        const link = document.createElement('a')
        link.download = `团队拓客数据统计_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.png`
        link.href = this.screenshotDataUrl
        
        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        this.$message.success('图片下载成功')
      } catch (error) {
        console.error('图片下载失败:', error)
        this.$message.error('图片下载失败')
      }
    },

    // 关闭预览对话框
    handlePreviewClose(done) {
      this.screenshotDataUrl = ''
      done()
    },

    // 获取图片尺寸信息
    getImageSize() {
      if (!this.screenshotDataUrl) return ''
      
      try {
        // 从DataURL中获取图片尺寸
        const img = new Image()
        img.onload = () => {
          this.imageWidth = img.width
          this.imageHeight = img.height
        }
        img.src = this.screenshotDataUrl
        
        return this.imageWidth && this.imageHeight 
          ? `${this.imageWidth} × ${this.imageHeight} 像素`
          : '正在加载...'
      } catch (error) {
        return '尺寸未知'
      }
    }
  }
}
</script>

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

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

.NCC-common-layout-main {
  height: 100%;
  overflow: auto;
  padding: 16px;
  background: #f5f7fa;
}

// 活动选择区域样式
.event-selector-container {
  margin-bottom: 24px;
  
  .selector-card {
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid #e2e8f0;
    
    .el-card__body {
      padding: 20px;
    }
  }
  
  .selector-content {
    display: flex;
    align-items: center;
    gap: 20px;
    
    .selector-item {
      display: flex;
      align-items: center;
      
      .selector-label {
        font-size: 14px;
        font-weight: 500;
        color: #606266;
        margin-right: 10px;
        white-space: nowrap;
      }
    }
  }
}

// 统计概览卡片样式
.statistics-overview {
  margin-bottom: 16px;
  
  .stat-card {
    background: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e4e7ed;
    transition: all 0.3s ease;
    height: 80px;
    display: flex;
    align-items: center;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
    
    .stat-icon {
      width: 48px;
      height: 48px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      i {
        font-size: 20px;
        color: white;
      }
      
      &:nth-child(1) {
        background: #409EFF;
      }
      
      &:nth-child(2) {
        background: #67C23A;
      }
      
      &:nth-child(3) {
        background: #E6A23C;
      }
      
      &:nth-child(4) {
        background: #F56C6C;
      }
    }
    
    .stat-content {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
        line-height: 1;
      }
      
      .stat-label {
        font-size: 12px;
        color: #909399;
        font-weight: 500;
      }
    }
  }
}

.team-report-container {
  .report-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 4px;
    
    .header-left {
      h3 {
        margin: 0 0 2px 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
      
      .subtitle {
        font-size: 12px;
        color: #909399;
        font-weight: 400;
      }
    }
    
    .header-right {
      .el-button {
        border-radius: 4px;
        padding: 8px 16px;
        font-weight: 500;
        font-size: 14px;
      }
    }
  }

  .waterfall-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 16px;
    
    .store-card {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #e4e7ed;
      overflow: hidden;
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }
      
      .store-header {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        background: #f8f9fa;
        border-bottom: 1px solid #e4e7ed;
        
        .store-icon {
          width: 32px;
          height: 32px;
          border-radius: 6px;
          background: #409EFF;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          
          i {
            color: white;
            font-size: 16px;
          }
        }
        
        .store-info {
          flex: 1;
          
          .store-name {
            font-weight: 600;
            color: #303133;
            font-size: 14px;
            margin-bottom: 2px;
          }
          
          .store-total {
            font-size: 12px;
            color: #909399;
            font-weight: 500;
          }
        }
        
        .store-index {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background: #409EFF;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          font-weight: 600;
        }
      }
      
      .teams-container {
        padding: 12px;
        
        .team-card {
          margin-bottom: 12px;
          border: 1px solid #e4e7ed;
          border-radius: 6px;
          overflow: hidden;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .team-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: #f5f7fa;
            border-bottom: 1px solid #e4e7ed;
            
            .team-name {
              display: flex;
              align-items: center;
              font-weight: 500;
              color: #303133;
              font-size: 13px;
              
              i {
                margin-right: 6px;
                color: #67C23A;
                font-size: 14px;
              }
            }
            
            .team-total {
              font-size: 12px;
              color: #909399;
              font-weight: 500;
              background: #e4e7ed;
              padding: 2px 8px;
              border-radius: 10px;
            }
          }
          
          .members-container {
            .member-card {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 8px 12px;
              border-bottom: 1px solid #f0f0f0;
              
              &:last-child {
                border-bottom: none;
              }
              
              &:hover {
                background: #f8f9fa;
              }
              
              .member-name {
                display: flex;
                align-items: center;
                font-weight: 500;
                color: #606266;
                font-size: 13px;
                
                i {
                  margin-right: 6px;
                  color: #909399;
                  font-size: 12px;
                }
              }
              
              .member-stats {
                display: flex;
                gap: 8px;
                
                .stat-item {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  gap: 2px;
                  
                  .stat-label {
                    font-size: 10px;
                    color: #909399;
                    font-weight: 500;
                  }
                  
                  .stat-value {
                    font-weight: 600;
                    font-size: 12px;
                    padding: 2px 6px;
                    border-radius: 3px;
                    
                    &.target {
                      color: #E6A23C;
                      background: #fdf6ec;
                    }
                    
                    &.count {
                      color: #409EFF;
                      background: #ecf5ff;
                    }
                  }
                  
                  .completion-rate {
                    font-weight: 600;
                    font-size: 11px;
                    padding: 2px 6px;
                    border-radius: 3px;
                    
                    &.completion-excellent {
                      background: #f0f9ff;
                      color: #409EFF;
                    }
                    
                    &.completion-good {
                      background: #f6ffed;
                      color: #67C23A;
                    }
                    
                    &.completion-normal {
                      background: #fef3c7;
                      color: #E6A23C;
                    }
                    
                    &.completion-poor {
                      background: #fef0f0;
                      color: #F56C6C;
                    }
                    
                    &.completion-zero {
                      background: #f5f5f5;
                      color: #909399;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

// 响应式布局优化
@media (max-width: 1200px) {
  .waterfall-container {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
}

@media (max-width: 768px) {
  .waterfall-container {
    grid-template-columns: 1fr;
  }
  
  .statistics-overview {
    .el-row {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}

// 确保表格内容完全显示
.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;
}

// 图片预览对话框样式
.screenshot-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.preview-container {
  text-align: center;
  max-height: 75vh;
  overflow: auto;
  
  .image-wrapper {
    position: relative;
    display: inline-block;
    
    .preview-image {
      max-width: 100%;
      max-height: 70vh;
      border-radius: 8px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      border: 1px solid #e4e7ed;
      display: block;
    }
    
    .image-info {
      position: absolute;
      bottom: 8px;
      right: 8px;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      
      .image-size {
        font-weight: 500;
      }
    }
  }
  
  .no-image {
    padding: 60px 20px;
    color: #909399;
    
    i {
      font-size: 48px;
      margin-bottom: 16px;
      display: block;
    }
    
    p {
      margin: 0;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 8px;
  }
}
</style>