<template>
  <div class="home-container">
    <!-- 更新数据按钮区域 -->
    <el-row :gutter="20" class="update-row">
      <el-col :span="24">
        <el-card class="update-card">
          <template #header>
            <div class="card-header">
              <span>早点补货</span>
              <div class="update-buttons">
                <el-button 
                  type="primary" 
                  :loading="updatingSSQ" 
                  @click="updateSSQData"
                  :disabled="updatingAll"
                >
                  <el-icon><Refresh /></el-icon>
                  补红蓝球煎饼
                </el-button>
                <el-button 
                  type="success" 
                  :loading="updatingDLT" 
                  @click="updateDLTData"
                  :disabled="updatingAll"
                >
                  <el-icon><Refresh /></el-icon>
                  补大乐斗豆浆
                </el-button>
                <el-button 
                  type="warning" 
                  :loading="updatingAll" 
                  @click="updateAllData"
                  :disabled="updatingSSQ || updatingDLT"
                >
                  <el-icon><Refresh /></el-icon>
                  补全场早点
                </el-button>
              </div>
            </div>
          </template>
          <div v-if="updateMessage" class="update-message">
            <el-alert 
              :title="updateMessage" 
              :type="updateMessageType" 
              :closable="false"
              show-icon
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="single-col-row">
      <el-col :span="12">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>红蓝球煎饼新鲜出锅</span>
              <el-button type="primary" link @click="refreshSSQData">再来一份</el-button>
            </div>
          </template>
          <div v-if="ssqLatest" class="lottery-info">
            <div class="issue-info">
              <span class="label">早点编号：</span>
              <span class="value">{{ ssqLatest.issue }}</span>
            </div>
            <div class="draw-time">
              <span class="label">出锅时间：</span>
              <span class="value">{{ formatDate(ssqLatest.open_time) }}</span>
            </div>
            <div class="numbers">
              <div class="red-balls">
                <span v-for="i in 6" :key="i" class="ball red">{{ ssqLatest['red_ball_' + i] }}</span>
              </div>
              <div class="blue-balls">
                <span class="ball blue">{{ ssqLatest.blue_ball }}</span>
              </div>
            </div>
          </div>
          <div v-else class="loading">
            <el-skeleton :rows="3" animated />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>大乐斗豆浆新鲜出锅</span>
              <el-button type="primary" link @click="refreshDLTData">再来一份</el-button>
            </div>
          </template>
          <div v-if="dltLatest" class="lottery-info">
            <div class="issue-info">
              <span class="label">早点编号：</span>
              <span class="value">{{ dltLatest.issue }}</span>
            </div>
            <div class="draw-time">
              <span class="label">出锅时间：</span>
              <span class="value">{{ formatDate(dltLatest.open_time) }}</span>
            </div>
            <div class="numbers">
              <div class="front-balls">
                <span v-for="i in 5" :key="i" class="ball red">{{ dltLatest['front_ball_' + i] }}</span>
              </div>
              <div class="back-balls">
                <span v-for="i in 2" :key="i" class="ball blue">{{ dltLatest['back_ball_' + i] }}</span>
              </div>
            </div>
          </div>
          <div v-else class="loading">
            <el-skeleton :rows="3" animated />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <div class="quick-row">
      <el-button v-for="(item, idx) in quickActions" :key="idx" class="quick-btn" @click="navigateTo(item.route)">
        <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
        {{ item.label }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { lotteryApi } from '../api/lottery'
import { Document, TrendCharts, MagicStick, Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

const router = useRouter()
const ssqLatest = ref(null)
const dltLatest = ref(null)

// 更新状态
const updatingSSQ = ref(false)
const updatingDLT = ref(false)
const updatingAll = ref(false)
const updateMessage = ref('')
const updateMessageType = ref('info')

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取双色球最新开奖
const fetchSSQLatest = async () => {
  try {
    const response = await lotteryApi.getLatestSSQ()
    if (response && response.data) {
      ssqLatest.value = response.data
    }
  } catch (error) {
    console.error('获取双色球最新开奖失败:', error)
  }
}

// 获取大乐透最新开奖
const fetchDLTLatest = async () => {
  try {
    const response = await lotteryApi.getLatestDLT()
    if (response && response.data) {
      dltLatest.value = response.data
    }
  } catch (error) {
    console.error('获取大乐透最新开奖失败:', error)
  }
}

// 刷新双色球数据
const refreshSSQData = () => {
  fetchSSQLatest()
}

// 刷新大乐透数据
const refreshDLTData = () => {
  fetchDLTLatest()
}

// 更新双色球数据
const updateSSQData = async () => {
  updatingSSQ.value = true
  updateMessage.value = ''
  
  try {
    const response = await lotteryApi.updateSSQData()
    if (response && response.data && response.data.success) {
      updateMessage.value = response.data.message
      updateMessageType.value = 'success'
      ElMessage.success(response.data.message)
      // 刷新最新开奖数据
      await fetchSSQLatest()
    } else {
      throw new Error(response?.data?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新双色球数据失败:', error)
    updateMessage.value = `更新双色球数据失败: ${error.message}`
    updateMessageType.value = 'error'
    ElMessage.error(`更新双色球数据失败: ${error.message}`)
  } finally {
    updatingSSQ.value = false
  }
}

// 更新大乐透数据
const updateDLTData = async () => {
  updatingDLT.value = true
  updateMessage.value = ''
  
  try {
    const response = await lotteryApi.updateDLTData()
    if (response && response.data && response.data.success) {
      updateMessage.value = response.data.message
      updateMessageType.value = 'success'
      ElMessage.success(response.data.message)
      // 刷新最新开奖数据
      await fetchDLTLatest()
    } else {
      throw new Error(response?.data?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新大乐透数据失败:', error)
    updateMessage.value = `更新大乐透数据失败: ${error.message}`
    updateMessageType.value = 'error'
    ElMessage.error(`更新大乐透数据失败: ${error.message}`)
  } finally {
    updatingDLT.value = false
  }
}

// 更新所有数据
const updateAllData = async () => {
  updatingAll.value = true
  updateMessage.value = ''
  
  try {
    const response = await lotteryApi.updateAllLotteryData()
    if (response && response.data && response.data.success) {
      updateMessage.value = response.data.message
      updateMessageType.value = 'success'
      ElMessage.success(response.data.message)
      // 刷新最新开奖数据
      await Promise.all([fetchSSQLatest(), fetchDLTLatest()])
    } else {
      throw new Error(response?.data?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新所有数据失败:', error)
    updateMessage.value = `补货失败: ${error.message}`
    updateMessageType.value = 'error'
    ElMessage.error(`补货失败: ${error.message}`)
  } finally {
    updatingAll.value = false
  }
}

// 页面导航
const navigateTo = (route) => {
  const routeMap = {
    'ssq': 'SSQ',
    'dlt': 'DLT',
    'statistics': 'Statistics',
    'generator': 'NumberGenerator'
  }
  router.push({ name: routeMap[route] })
}

const quickActions = [
  { label: '红蓝球煎饼', route: 'ssq', icon: Document },
  { label: '大乐斗豆浆', route: 'dlt', icon: Document },
  { label: '数据小菜', route: 'statistics', icon: TrendCharts },
  { label: '一键下单', route: 'generator', icon: MagicStick }
]

onMounted(() => {
  fetchSSQLatest()
  fetchDLTLatest()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.update-row {
  margin-bottom: 20px;
}

.update-card {
  margin-bottom: 20px;
}

.update-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.update-message {
  margin-top: 10px;
}

.mt-20 {
  margin-top: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.lottery-info {
  padding: 10px 0;
}

.issue-info,
.draw-time {
  margin-bottom: 10px;
}

.label {
  color: #606266;
  margin-right: 10px;
}

.value {
  font-weight: bold;
}

.numbers {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.ball {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin: 0 5px;
  color: white;
  font-weight: bold;
}

.red {
  background-color: #f56c6c;
}

.blue {
  background-color: #409eff;
}

.red-balls,
.blue-balls,
.front-balls,
.back-balls {
  display: flex;
  align-items: center;
}

.blue-balls,
.back-balls {
  margin-left: 20px;
}

.quick-row {
  margin-top: 24px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px 8px;
}

.quick-btn {
  min-width: 110px;
  height: 40px;
  border-radius: 20px !important;
  background: #f8f5f0;
  color: #a67c52;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 2px 8px 0 rgba(166,124,82,0.08);
  border: none;
  transition: background 0.2s, color 0.2s;
  padding: 0 18px;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quick-btn:hover, .quick-btn:focus {
  background: #ffe9c6;
  color: #d4a15a;
}

@media (max-width: 600px) {
  .quick-row {
    gap: 8px 0;
  }
  .quick-btn {
    min-width: 0;
    flex: 1 1 45%;
    font-size: 15px;
    padding: 0 8px;
    margin-bottom: 0;
  }
}
</style> 