<template>
  <div class="lottery-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h1>开奖信息查询</h1>
        <p class="subtitle">实时开奖结果，历史数据查询</p>
      </div>
    </div>

    <!-- 彩票种类选择区域 -->
    <el-card class="lottery-types" shadow="never">
      <h2 class="section-title">选择彩票种类</h2>
      
      <div class="lottery-options">
        <!-- 中国福彩 -->
        <div class="lottery-category">
          <h3 class="category-title">中国福彩</h3>
          <div class="lottery-category-options">
            <!-- 双色球 -->
            <div 
              class="lottery-option" 
              :class="{ active: currentLotteryType === 'ssq' }" 
              @click="switchLotteryType('ssq')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/shuangseqiu.png" alt="双色球" />
              </div>
              <div class="lottery-option-name">双色球</div>
            </div>

            <!-- 福彩3D -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('3d')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/3D.png" alt="福彩3D" />
              </div>
              <div class="lottery-option-name">福彩3D</div>
            </div>

            <!-- 七乐彩 -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('qlc')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/7lecai.png" alt="七乐彩" />
              </div>
              <div class="lottery-option-name">七乐彩</div>
            </div>

            <!-- 快乐8 -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('kl8')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/kuaile8.png" alt="快乐8" />
              </div>
              <div class="lottery-option-name">快乐8</div>
            </div>
          </div>
        </div>

        <!-- 中国体彩 -->
        <div class="lottery-category">
          <h3 class="category-title">中国体彩</h3>
          <div class="lottery-category-options">
            <!-- 大乐透 -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('dlt')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/daletou.png" alt="大乐透" />
              </div>
              <div class="lottery-option-name">大乐透</div>
            </div>

            <!-- 排列3 -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('pl3')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/pailie3.png" alt="排列3" />
              </div>
              <div class="lottery-option-name">排列3</div>
            </div>

            <!-- 排列5 -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('pl5')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/pailie5.png" alt="排列5" />
              </div>
              <div class="lottery-option-name">排列5</div>
            </div>

            <!-- 七星彩 -->
            <div 
              class="lottery-option" 
              @click="switchLotteryType('qxc')"
            >
              <div class="lottery-option-image">
                <img src="@/assets/7星彩.png" alt="七星彩" />
              </div>
              <div class="lottery-option-name">七星彩</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 搜索区域 - 只有在选择彩票种类后才显示 -->
    <el-card v-if="currentLotteryType" class="search-section" shadow="never">
      <el-tabs v-model="searchType" type="border-card">
        <el-tab-pane label="期号查询" name="period">
          <div class="search-form">
            <el-input
            v-model="searchPeriod"
            placeholder="请输入期号，例如：2025056"
              clearable
              @keyup.enter="searchByPeriod"
              style="max-width: 400px;"
            >
              <template #append>
                <el-button 
                  type="primary"
            @click="searchByPeriod"
                  :loading="loading" 
                  :disabled="!searchPeriod"
          >
                  查询
                </el-button>
              </template>
            </el-input>
          </div>
        </el-tab-pane>
        <el-tab-pane label="日期查询" name="date">
          <div class="search-form">
            <el-date-picker
              v-model="searchDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="margin-right: 10px;"
            />
            <el-button 
              type="primary"
              @click="searchByDate" 
              :loading="loading"
            >
              查询
            </el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="表相查询" name="table">
          <div class="search-form">
            <div class="table-analysis-info">
              <p>表相分析提供基于最新100期开奖数据的详细表格分析</p>
              <el-button 
                type="primary"
                @click="goToTableAnalysis"
              >
                进入表相分析
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        @close="clearError"
        style="margin-top: 15px;"
      />
    </el-card>

    <!-- 搜索结果 -->
    <el-card v-if="searchResults.length > 0" class="results-section" shadow="never">
       <template #header>
        <div class="card-header">
          <span>查询结果</span>
        </div>
      </template>
      <div class="lottery-records">
        <div v-for="item in searchResults" :key="item.drawId" class="lottery-record-item">
          <div class="lottery-record-header">
            <span class="lottery-period">{{ item.drawId }}期</span>
            <span class="lottery-date">{{ formatDate(item.drawDate) }}</span>
          </div>
          <div class="lottery-balls-container">
            <div class="red-balls-container">
              <span v-for="ball in getRedBalls(item)" :key="ball" class="ball-red">
                {{ String(ball).padStart(2, '0') }}
              </span>
            </div>
              <span class="ball-blue">{{ String(item.blueBall).padStart(2, '0') }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 近期开奖记录 -->
    <el-card class="recent-section" shadow="never" v-loading="loadingRecent" element-loading-text="加载中...">
      <template #header>
        <div class="card-header">
          <span>近期开奖记录</span>
      </div>
      </template>
      <el-alert
        v-if="recentError"
        :title="recentError"
        type="error"
        show-icon
        style="margin-bottom: 15px;"
      />
      <div v-if="!recentError" class="lottery-records">
        <div v-for="item in recentDraws" :key="item.drawId" class="lottery-record-item">
          <div class="lottery-record-header">
            <span class="lottery-period">{{ item.drawId }}期</span>
            <span class="lottery-date">{{ formatDate(item.drawDate) }}</span>
          </div>
          <div class="lottery-balls-container">
            <div class="red-balls-container">
              <span v-for="ball in getRedBalls(item)" :key="ball" class="ball-red">
                {{ String(ball).padStart(2, '0') }}
              </span>
            </div>
              <span class="ball-blue">{{ String(item.blueBall).padStart(2, '0') }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 开发中提示 -->
    <div v-if="showTip" class="tip-overlay" @click="hideTip">
      <div class="tip-content" @click.stop>
        <div class="tip-icon">🚧</div>
        <h3>功能开发中</h3>
        <p>该彩票种类查询功能正在开发中，目前仅支持双色球查询，请稍后再试或选择双色球进行查询。</p>
        <button class="tip-button" @click="hideTip">我知道了</button>
      </div>
    </div>
  </div>
</template>

<script>
import { lotteryApi } from '../api'
import { ElCard, ElTabs, ElTabPane, ElInput, ElButton, ElDatePicker, ElAlert, ElTable, ElTableColumn, ElLoading } from 'element-plus'

export default {
  name: 'LotteryInfo',
  components: {
    ElCard,
    ElTabs,
    ElTabPane,
    ElInput,
    ElButton,
    ElDatePicker,
    ElAlert,
    ElTable,
    ElTableColumn
  },
  directives: {
    loading: ElLoading.directive,
  },
  data() {
    return {
      searchType: 'period', // 'period' 或 'date'
      loading: false,
      loadingRecent: false,
      currentLotteryType: '', // 默认为空，不选择任何彩票
      showTip: false, // 提示框显示状态
      
      // 搜索相关
      searchPeriod: '',
      searchDateRange: [], // [startDate, endDate]
      searchResults: [],
      
      // 近期开奖
      recentDraws: [],
      
      // 错误信息
      errorMessage: '',
      recentError: ''
    }
  },
  computed: {
    searchStartDate() {
      return this.searchDateRange ? this.searchDateRange[0] : ''
    },
    searchEndDate() {
      return this.searchDateRange ? this.searchDateRange[1] : ''
    }
  },
  mounted() {
    // 不再自动加载近期开奖记录，需要用户先选择彩票种类
  },
  methods: {
    // 加载近期开奖记录
    async loadRecentDraws() {
      // 如果未选择彩票种类，不加载数据
      if (!this.currentLotteryType) {
        this.recentDraws = [];
        return;
      }

      this.loadingRecent = true;
      this.recentError = '';
      try {
        // 根据不同彩票类型调用不同的API
        // 这里假设API支持传递彩票类型参数
        const response = await lotteryApi.getRecentDraws(10, this.currentLotteryType);
        
        if (response.success === true) {
          this.recentDraws = response.data;
        } else {
          this.recentError = response.message || '获取近期开奖信息失败';
          console.error('获取近期开奖信息失败:', response.message);
        }
      } catch (error) {
        this.recentError = error?.response?.data?.message || error?.message || '网络连接失败，请稍后重试';
        console.error('获取近期开奖信息失败:', error);
      } finally {
        this.loadingRecent = false;
      }
    },

    // 按期号搜索
    async searchByPeriod() {
      if (!this.searchPeriod || !this.currentLotteryType) return;
      
      this.loading = true;
      this.clearError();
      this.searchResults = [];
      try {
        // 传递彩票类型
        const response = await lotteryApi.getDrawById(parseInt(this.searchPeriod), this.currentLotteryType);
        
        if (response.success === true && response.data) {
          this.searchResults = [response.data];
        } else {
          this.showError(response.message || `未找到期号为 ${this.searchPeriod} 的记录`);
          this.searchResults = [];
        }
      } catch (error) {
        console.error('期号查询失败:', error);
        this.showError(error?.response?.data?.message || error?.message || '网络连接失败，请检查网络连接');
        this.searchResults = [];
      } finally {
        this.loading = false;
      }
    },

    // 按日期范围搜索
    async searchByDate() {
      if (!this.searchStartDate || !this.searchEndDate || !this.currentLotteryType) {
        this.showError('请选择开始和结束日期');
        return;
      }
      this.loading = true;
      this.clearError();
      this.searchResults = [];
      try {
        // 传递彩票类型
        const response = await lotteryApi.queryDraws(
          this.searchStartDate, 
          this.searchEndDate, 
          this.currentLotteryType
        );
        
        if (response.success === true) {
          this.searchResults = response.data;
          if (this.searchResults.length === 0) {
            this.showError('该日期范围内未找到开奖记录');
          }
        } else {
          this.showError(response.message || '查询失败，请重试');
          this.searchResults = [];
        }
      } catch (error) {
        console.error('日期查询失败:', error);
        this.showError(error?.response?.data?.message || error?.message || '网络连接失败，请检查网络连接');
        this.searchResults = [];
      } finally {
        this.loading = false;
      }
    },

    // 解析红球号码字符串
    parseRedBalls(redBallsStr) {
      if (!redBallsStr) return []
      return redBallsStr.split(',').map(ball => parseInt(ball.trim()))
    },

    // 获取红球号码数组（适配API返回的数据结构）
    getRedBalls(item) {
      // 如果是新的API结构（redBall1-6字段）
      if (item.redBall1 !== undefined) {
        return [
          item.redBall1,
          item.redBall2, 
          item.redBall3,
          item.redBall4,
          item.redBall5,
          item.redBall6
        ].filter(ball => ball !== undefined && ball !== null)
      }
      // 如果是旧的API结构（redBalls字符串）
      if (item.redBalls) {
        return this.parseRedBalls(item.redBalls)
      }
      return []
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },

    // 显示错误信息
    showError(message) {
      this.errorMessage = message
    },

    // 清除错误信息
    clearError() {
      this.errorMessage = ''
    },

    // 添加彩票类型切换方法
    switchLotteryType(type) {
      // 只有双色球功能可用，其他彩票类型显示开发中提示
      if (type !== 'ssq') {
        this.showDevelopingTip();
        return;
      }
      
      this.currentLotteryType = type;
      // 清除之前的搜索结果
      this.searchResults = [];
      this.searchPeriod = '';
      this.searchDateRange = [];
      this.clearError();
      // 加载新选择的彩票类型的数据
      this.loadRecentDraws();
    },

    // 显示开发中提示
    showDevelopingTip() {
      this.showTip = true;
    },

    // 隐藏提示
    hideTip() {
      this.showTip = false;
    },

    // 跳转到表相分析页面
    goToTableAnalysis() {
      this.$router.push({ name: 'TableAnalysis' });
    }
  }
}
</script>

<style scoped>
.lottery-container {
  padding: 20px 20px 0px 20px;
  background-color: #f0f2f5;
}

.search-section, .results-section, .recent-section, .lottery-types {
  margin-bottom: 20px;
  border-radius: 8px; /* 添加圆角，与第一个卡片保持一致 */
  overflow: hidden; /* 确保内容不超出圆角范围 */
}

.search-form {
  display: flex;
  align-items: center;
  padding: 20px 10px;
}

.card-header {
  font-weight: bold;
}

.red-balls-container {
  display: flex;
  flex-wrap: nowrap;
}

.ball-red, .ball-blue {
  display: inline-block;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  text-align: center;
  line-height: 28px;
  color: white;
  font-weight: bold;
  margin: 0 3px;
  }

.ball-red {
  background-color: #e53e3e;
  }

  .ball-blue {
  background-color: #3b82f6;
}

.page-header {
  background: url('@/assets/banner/backend1.png') center/cover no-repeat, linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  padding: 45px 20px 25px;
  text-align: center;
  position: relative;
  margin-bottom: 20px;
  border-radius: 8px;
}

.page-title {
  margin: 0;
  text-align: center;
}

.page-title h1 {
  font-size: 38px;
  margin: 0 auto 10px;
  font-weight: 700;
  color: white;
  text-shadow: 0 2px 6px rgba(0,0,0,0.7), 0 0 15px rgba(0,0,0,0.4);
  letter-spacing: 2px;
  text-align: center;
  width: 100%;
}

.page-title p {
  font-size: 22px;
  opacity: 0.9;
  color: white;
  text-shadow: 0 2px 6px rgba(0,0,0,0.7), 0 0 15px rgba(0,0,0,0.4);
  text-align: center;
  width: 100%;
  margin: 0 auto;
  font-weight: 500;
}

/* 彩票类型选择区域 */
.section-title {
  text-align: center;
  color: #333;
  font-size: 20px;
  margin-bottom: 25px;
  font-weight: 600;
}

.lottery-options {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
}

.lottery-category {
  margin-bottom: 25px;
}

.category-title {
  text-align: left;
  color: #333;
  font-size: 18px;
  margin-bottom: 15px;
  font-weight: 600;
  padding-bottom: 5px;
  border-bottom: 1px solid #f0f0f0;
}

.lottery-category-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: flex-start;
}

.lottery-option {
  width: 100px;
  padding: 15px 10px;
  border-radius: 12px;
  text-align: center;
  background: white;
  border: 1px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;
}

.lottery-option.active {
  border-color: #4caf50;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.2);
  transform: translateY(-2px);
  background-color: #f1f8e9;
}

.lottery-option:hover:not(.active) {
  transform: translateY(-3px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
  border-color: #e0e0e0;
}

.lottery-option-image {
  width: 50px;
  height: 50px;
  margin: 0 auto 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lottery-option-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.lottery-option-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

/* 开发中提示框 */
.tip-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.tip-content {
  background: white;
  padding: 30px;
  border-radius: 16px;
  text-align: center;
  max-width: 320px;
  width: 90%;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}

.tip-icon {
  font-size: 40px;
  margin-bottom: 15px;
}

.tip-content h3 {
  font-size: 20px;
  margin-bottom: 10px;
}

.tip-content p {
  color: #666;
  margin-bottom: 20px;
}

.tip-button {
  background: #e53e3e;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.tip-button:hover {
  background: #c53030;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .lottery-container {
    padding: 10px 10px 0px 10px;
  }
  .search-form {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .lottery-options {
    gap: 12px;
  }

  .lottery-option {
    width: 100px;
    padding: 12px;
  }
  
  .page-title h1 {
    font-size: 28px;
  }
  
  .page-title p {
    font-size: 16px;
  }

  .lottery-category-options {
    justify-content: center;
    gap: 10px;
  }

  .lottery-option {
    width: calc(25% - 10px);
    min-width: 80px;
    padding: 10px 5px;
  }

  .lottery-option-image {
    width: 40px;
    height: 40px;
  }

  .lottery-option-name {
    font-size: 12px;
  }

  .category-title {
    text-align: center;
    font-size: 16px;
  }
  
  .table-analysis-info {
    padding: 5px 0;
  }
  
  .table-analysis-info p {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .lottery-option {
    width: calc(33% - 10px);
  }
}

.lottery-records {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.lottery-record-item {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.lottery-record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.lottery-period {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.lottery-date {
  color: #666;
  font-size: 14px;
}

.lottery-balls-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.table-analysis-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 10px 0;
}

.table-analysis-info p {
  color: #666;
  margin: 0;
  text-align: center;
}
</style> 