<template>
  <div class="trend-analysis">
    <div class="header">
      <!-- 返回按钮 -->
      <div class="back-button-container">
        <el-button @click="goBack" icon="ArrowLeft" size="medium">
          返回
        </el-button>
      </div>
      
      <h2>活跃性分析</h2>
      <p>查看前区球和后区球历史数据统计</p>
      
      <!-- 球类选择切换 -->
      <div class="ball-type-tabs">
        <el-radio-group v-model="ballType" @change="switchBallType">
          <el-radio-button label="frontend">🔴 前区球</el-radio-button>
          <el-radio-button label="backend">🔵 后区球</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 功能按钮区域 -->
    <div class="analysis-buttons">
      <el-card 
        class="analysis-card" 
        :class="{ active: currentView === 'all' }"
        @click="loadData('all')"
        shadow="hover"
      >
        <div class="btn-icon">
          <el-icon size="32" color="#5856d6"><Document /></el-icon>
        </div>
        <div class="btn-text">
          <div class="btn-title">历史数据</div>
          <div class="btn-desc">查看所有历史数据</div>
        </div>
      </el-card>

      <el-card 
        class="analysis-card"
        :class="{ active: currentView === 'top' }"
        @click="loadData('top')"
        shadow="hover"
      >
        <div class="btn-icon">
          <el-icon size="32" color="#ff9500"><Sort /></el-icon>
        </div>
        <div class="btn-text">
          <div class="btn-title">历史排行</div>
          <div class="btn-desc">历史数据排行榜</div>
        </div>
      </el-card>

      <el-card 
        class="analysis-card"
        :class="{ active: currentView === '100' }"
        @click="loadData('100')"
        shadow="hover"
      >
        <div class="btn-icon">
          <el-icon size="32" color="#34c759"><Histogram /></el-icon>
        </div>
        <div class="btn-text">
          <div class="btn-title">百期数据</div>
          <div class="btn-desc">最近100期数据</div>
        </div>
      </el-card>

      <el-card 
        class="analysis-card"
        :class="{ active: currentView === 'top100' }"
        @click="loadData('top100')"
        shadow="hover"
      >
        <div class="btn-icon">
          <el-icon size="32" color="#ff3b30"><Menu /></el-icon>
        </div>
        <div class="btn-text">
          <div class="btn-title">百期排行</div>
          <div class="btn-desc">最近100期数据排行</div>
        </div>
      </el-card>
    </div>

    <!-- 数据显示区域 -->
    <el-card class="data-container" shadow="never">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="10" animated />
      </div>

      <el-alert
        v-else-if="error"
        :title="error"
        type="error"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template #default>
          <el-button @click="retryLoad" type="primary" size="small">重试</el-button>
        </template>
      </el-alert>

      <div v-else-if="tableData.length > 0" class="data-table-container">
        <div class="table-header">
          <h3>
            {{ getTableTitleText() }}
            <span v-if="latestDrawId" class="draw-id-suffix">
              （引用数据截至<span class="draw-id-number">{{ latestDrawId }}</span>期）
            </span>
          </h3>
          <div class="table-info">
            <span>共 {{ tableData.length }} 条记录</span>
          </div>
        </div>

        <el-table :data="paginatedData" stripe style="width: 100%">
          <el-table-column 
            v-for="column in getTableColumns()" 
            :key="column.key" 
            :prop="column.key"
            :label="column.title"
          >
            <template #default="scope">
              <span :class="getColumnClass(column.key, scope.row[column.key])">
                {{ formatValue(column.key, scope.row[column.key], scope.$index) }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination" v-if="totalPages > 1">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="tableData.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
          />
        </div>
      </div>

      <el-empty v-else-if="!loading" description="暂无数据" />
    </el-card>
  </div>
</template>

<script>
import { dltLotteryApi } from '@/api/dlt'
import {
  ElButton,
  ElCard,
  ElRadioGroup,
  ElRadioButton,
  ElSkeleton,
  ElAlert,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElEmpty,
  ElIcon
} from 'element-plus'
import { 
  ArrowLeft, 
  Document, 
  Sort, 
  Histogram, 
  Menu 
} from '@element-plus/icons-vue'

export default {
  name: 'DltTrendAnalysis',
  components: {
    ElButton,
    ElCard,
    ElRadioGroup,
    ElRadioButton,
    ElSkeleton,
    ElAlert,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElEmpty,
    ElIcon,
    Document,
    Sort,
    Histogram,
    Menu
  },
  data() {
    return {
      loading: false,
      error: null,
      currentView: '',
      ballType: 'frontend', // 'frontend' 或 'backend'
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      latestDrawId: null // 最新期号
    }
  },
  mounted() {
    // 获取最新期号
    this.fetchLatestDrawId()
  },
  computed: {
    totalPages() {
      return Math.ceil(this.tableData.length / this.pageSize)
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.tableData.slice(start, start + this.pageSize)
    }
  },
  methods: {
    async loadFrontendHistoryAll() {
      this.currentView = 'all'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getFrontendHistoryAll()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取前区历史全部记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    async loadFrontendHistory100() {
      this.currentView = '100'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getFrontendHistory100()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取前区最近100期记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    async loadFrontendHistoryTop() {
      this.currentView = 'top'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getFrontendHistoryTop()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取前区历史排行记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    async loadFrontendHistoryTop100() {
      this.currentView = 'top100'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getFrontendHistoryTop100()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取前区100期排行记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    // 后区数据获取方法
    async loadBackendHistoryAll() {
      this.currentView = 'all'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getBackendHistoryAll()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取后区历史全部记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    async loadBackendHistory100() {
      this.currentView = '100'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getBackendHistory100()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取后区最近100期记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    async loadBackendHistoryTop() {
      this.currentView = 'top'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getBackendHistoryTop()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取后区历史排行记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    async loadBackendHistoryTop100() {
      this.currentView = 'top100'
      this.currentPage = 1
      this.loading = true
      this.error = null
      
      try {
        const response = await dltLotteryApi.getBackendHistoryTop100()
        if (response.success) {
          this.tableData = response.data || []
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取后区100期排行记录失败:', error)
        this.error = '网络请求失败，请重试'
      } finally {
        this.loading = false
      }
    },

    // 切换球类型
    switchBallType() {
      this.currentView = ''
      this.tableData = []
      this.currentPage = 1
      this.error = null
    },

    // 统一的数据加载方法
    loadData(viewType) {
      if (this.ballType === 'frontend') {
        switch (viewType) {
          case 'all':
            this.loadFrontendHistoryAll()
            break
          case '100':
            this.loadFrontendHistory100()
            break
          case 'top':
            this.loadFrontendHistoryTop()
            break
          case 'top100':
            this.loadFrontendHistoryTop100()
            break
        }
      } else {
        switch (viewType) {
          case 'all':
            this.loadBackendHistoryAll()
            break
          case '100':
            this.loadBackendHistory100()
            break
          case 'top':
            this.loadBackendHistoryTop()
            break
          case 'top100':
            this.loadBackendHistoryTop100()
            break
        }
      }
    },

    getTableTitleText() {
      const ballTypeText = this.ballType === 'frontend' ? '前区球' : '后区球'
      const titles = {
        'all': `${ballTypeText}历史数据`,
        '100': `${ballTypeText}最近100期数据`,
        'top': `${ballTypeText}历史数据排行`,
        'top100': `${ballTypeText}最近100期数据排行`
      }
      return titles[this.currentView] || '数据列表'
    },

    // 获取最新期号
    async fetchLatestDrawId() {
      try {
        const response = await dltLotteryApi.getRecentDraws(1)
        if (response.data && response.data.length > 0) {
          this.latestDrawId = response.data[0].drawId
        }
      } catch (error) {
        console.error('获取最新期号失败:', error)
      }
    },

    getTableColumns() {
      // 根据不同的视图返回不同的列配置
      if (this.currentView === 'all') {
        // 历史全部记录 - 显示完整数据
        return [
          { key: 'ballNumber', title: '球号' },
          { key: 'frequencyCount', title: '出现次数' },
          { key: 'frequencyPercentage', title: '出现频率(%)' },
          { key: 'averageHiddenAppear', title: '平均隐现期' },
          { key: 'maxHiddenInterval', title: '最长隐现期' },
          { key: 'maxConsecutive', title: '最大连出期' },
          { key: 'activeCoefficient', title: '活跃系数' }
        ]
      } else if (this.currentView === '100') {
        // 最近100期 - 只显示有数据的列
        return [
          { key: 'ballNumber', title: '球号' },
          { key: 'frequencyCount', title: '出现次数' },
          { key: 'averageHiddenAppear', title: '平均隐现期' },
          { key: 'nowInterval', title: '当前隐现期' },
          { key: 'maxConsecutive', title: '最大连出期' },
          { key: 'activeCoefficient', title: '活跃系数' }
        ]
      } else if (this.currentView === 'top' || this.currentView === 'top100') {
        return [
          { key: 'ranking', title: '排名' },
          { key: 'ballNumber', title: '球号' },
          { key: 'activeCoefficient', title: '活跃系数' }
        ]
      }
      return []
    },

    getColumnClass(key, value) {
      if (key === 'ballNumber') {
        return this.ballType === 'frontend' ? 'ball-number red-ball' : 'ball-number blue-ball'
      } else if (key === 'activeCoefficient') {
        return 'point-coefficient'
      } else if (key === 'ranking') {
        return 'ranking'
      }
      return ''
    },

    formatValue(key, value, index) {
      if (key === 'ranking') {
        // 稠密排名（同分同名次，名次不跳跃），基于整表数据
        const realIndex = (this.currentPage - 1) * this.pageSize + index
        if (!Array.isArray(this.tableData) || realIndex < 0 || realIndex >= this.tableData.length) {
          return realIndex + 1
        }
        let rank = 1
        let lastVal = null
        for (let i = 0; i <= realIndex; i++) {
          const item = this.tableData[i]
          const val = item ? item.activeCoefficient : null
          if (i === 0) {
            lastVal = val
          } else if (val !== lastVal) {
            rank++
            lastVal = val
          }
        }
        return rank
      } else if (key === 'frequencyPercentage' && typeof value === 'number') {
        return value.toFixed(2)
      }
      return value
    },

    getRealRanking(currentIndex) {
      // 如果不是排行榜视图，使用简单的索引排名
      if (this.currentView !== 'top' && this.currentView !== 'top100') {
        return (this.currentPage - 1) * this.pageSize + currentIndex + 1
      }

      // 获取当前项的系数值
      const currentItem = this.paginatedData[currentIndex]
      if (!currentItem || !currentItem.activeCoefficient) {
        return (this.currentPage - 1) * this.pageSize + currentIndex + 1
      }

      const currentCoefficient = currentItem.activeCoefficient
      let realRank = 1

      // 遍历所有数据，计算真实排名
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i]
        if (item && item.activeCoefficient > currentCoefficient) {
          realRank++
        }
      }

      return realRank
    },

    retryLoad() {
      if (this.currentView) {
        this.loadData(this.currentView)
      }
    },

    // 返回上一页
    goBack() {
      // 获取当前彩票类型，优先使用路由参数，否则使用默认值 'dlt'
      const lotteryType = this.$route.query.lotteryType || 'dlt'
      this.$router.push({
        path: '/data-analysis',
        query: { lotteryType: lotteryType }
      })
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
      }
    }
  }
}
</script>

<style scoped>
.trend-analysis {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.back-button-container {
  position: absolute;
  left: 20px;
  top: 0;
}

.header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 700;
}

.header p {
  color: #7f8c8d;
  font-size: 16px;
}

.ball-type-tabs {
  margin-top: 10px;
}

.analysis-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.analysis-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.analysis-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(52, 152, 219, 0.15);
  border-color: #3498db;
}

.analysis-card.active {
  background-color: #eaf5ff;
  border-color: #3498db;
  box-shadow: 0 8px 25px rgba(52, 152, 219, 0.2);
}

.analysis-card.active :deep(.el-card__body) {
  background: transparent;
  color: #303133;
}

/* 减少卡片内边距 */
:deep(.el-card__body) {
  padding: 10px !important;
}

.btn-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 40px;
  height: 40px;
  margin-bottom: 12px;
  transition: transform 0.2s ease;
}

.analysis-card:hover .btn-icon {
  transform: scale(1.1);
}

.btn-text {
  text-align: center;
}

.btn-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.analysis-card.active .btn-title {
  color: #2980b9;
}

.btn-desc {
  font-size: 14px;
  opacity: 0.8;
}

.analysis-card.active .btn-desc {
  color: #3498db;
}

.data-container {
  overflow: hidden;
}

.loading {
  padding: 40px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
}

.draw-id-suffix {
  font-size: 13px;
  font-weight: normal;
  color: #666;
  margin-left: 4px;
}

.draw-id-number {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-weight: 600;
}

.table-info {
  font-size: 14px;
  color: #909399;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.ball-number {
  color: white;
  padding: 4px 8px;
  border-radius: 50%;
  font-weight: 700;
  font-size: 14px;
  min-width: 30px;
  text-align: center;
  display: inline-block;
}

.red-ball {
  background: #e74c3c;
}

.blue-ball {
  background: #3498db;
}

.point-coefficient {
  color: #e74c3c;
  font-weight: 700;
}

.ranking {
  background: linear-gradient(135deg, #8e9aaf 0%, #6c757d 100%);
  color: white;
  padding: 6px 10px;
  border-radius: 6px;
  font-weight: 700;
  display: inline-block;
  min-width: 28px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(108, 117, 125, 0.25);
  transition: all 0.2s ease;
}

.ranking:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(108, 117, 125, 0.35);
}

@media (max-width: 768px) {
  .trend-analysis {
    padding: 15px;
  }
  
  .back-button-container {
    position: static;
    text-align: left;
    margin-bottom: 0px;
  }
  
  .header {
    margin-bottom: 15px;
  }
  
  .analysis-buttons {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .table-header h3 {
    font-size: 16px;
    line-height: 1.5;
  }
  
  .draw-id-suffix {
    display: block;
    margin-left: 0;
    margin-top: 4px;
    font-size: 12px;
  }
  
  .ranking {
    padding: 4px 8px;
    border-radius: 4px;
    min-width: 24px;
    font-size: 13px;
  }
}
</style>
