<template>
  <div class="price-trend-card">
    <div class="card-header">
      <div class="title-container">
        <h2 class="card-title">
          活牛、鲜肉价格趋势
          <span class="title-tibetan">སྲོག་ཆགས་དང་ཤ་ཡི་གོང་རིས་འགྱུར་ལྡོག</span>
        </h2>
      </div>
      
      <div class="controls-container">
        <div class="period-buttons">
          <button 
            v-for="(period, index) in periodTypes" 
            :key="period"
            :class="['period-btn', { active: currentPeriodIndex === index }]"
            @click="switchToPeriod(index)"
          >
            <div class="btn-text">{{ priceData[period]?.title || '加载中' }}</div>
            <div class="btn-text-tibetan">{{ priceData[period]?.title_tibetan || '' }}</div>
          </button>
        </div>
        
        <div class="auto-switch-control">
          <!-- <button 
            :class="['auto-btn', { active: autoSwitch }]"
            @click="toggleAutoSwitch"
          >
            <div class="btn-text">{{ autoSwitch ? '自动切换中' : '手动模式' }}</div>
            <div class="btn-text-tibetan">{{ autoSwitch ? 'རང་འགུལ་བརྗེ་བ།' : 'ལག་རིས་བེད་སྤྱོད།' }}</div>
          </button> -->
        </div>
      </div>
    </div>
    
    <div v-if="loading" class="loading-message">
      <div class="loading-spinner"></div>
      <div>正在加载价格数据...</div>
    </div>
    
    <div v-else-if="error" class="error-message">
      <div>{{ error }}</div>
    </div>
    
    <div v-else class="chart-container">
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
let chartInstance = null
let switchTimer = null

// 响应式数据
const priceData = ref({})
const loading = ref(true)
const error = ref('')
const currentPeriodType = ref('daily')
const currentPeriod = ref({ title: '日统计', title_tibetan: 'ཉིན་རེའི་གོང་རིས།' })
const autoSwitch = ref(true)

// 周期类型循环
const periodTypes = ['daily', 'weekly', 'monthly']
const currentPeriodIndex = ref(0)

// 生成基于当前日期的动态数据
const generateDynamicData = () => {
  const now = new Date()
  
  // 日统计 - 过去10天
  const dailyDates = []
  const dailyLiveCattle = []
  const dailyFreshMeat = []
  
  for (let i = 9; i >= 0; i--) {
    const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    dailyDates.push(`${date.getMonth() + 1}/${date.getDate()}`)
    // 固定模拟数据：活牛价格改为元/斤，价格相应调整
    dailyLiveCattle.push(Math.round((28 + Math.sin(i * 0.5) * 2 + Math.cos(i * 0.3) * 1.5) * 10) / 10)
    dailyFreshMeat.push(Math.round((76.5 + Math.sin(i * 0.4) * 1.2 + Math.cos(i * 0.6) * 0.8) * 10) / 10)
  }
  
  // 周统计 - 过去10周
  const weeklyDates = []
  const weeklyLiveCattle = []
  const weeklyFreshMeat = []
  
  for (let i = 9; i >= 0; i--) {
    const startDate = new Date(now.getTime() - i * 7 * 24 * 60 * 60 * 1000)
    const endDate = new Date(startDate.getTime() + 6 * 24 * 60 * 60 * 1000)
    
    // 处理跨月情况
    const startMonth = startDate.getMonth() + 1
    const startDay = startDate.getDate()
    const endMonth = endDate.getMonth() + 1
    const endDay = endDate.getDate()
    
    if (startMonth === endMonth) {
      weeklyDates.push(`${startMonth}/${startDay}-${endDay}`)
    } else {
      weeklyDates.push(`${startMonth}/${startDay}-${endMonth}/${endDay}`)
    }
    
    // 周统计价格稍高，固定数据（活牛价格调整为元/斤）
    weeklyLiveCattle.push(Math.round((29.5 + Math.sin(i * 0.6) * 2.5 + Math.cos(i * 0.4) * 2.0) * 10) / 10)
    weeklyFreshMeat.push(Math.round((78.8 + Math.sin(i * 0.7) * 2.0 + Math.cos(i * 0.5) * 1.5) * 10) / 10)
  }
  
  // 月统计 - 过去12个月
  const monthlyDates = []
  const monthlyLiveCattle = []
  const monthlyFreshMeat = []
  
  for (let i = 11; i >= 0; i--) {
    const monthDate = new Date(now.getFullYear(), now.getMonth() - i, 1)
    const year = monthDate.getFullYear()
    const month = monthDate.getMonth() + 1
    monthlyDates.push(`${year}年${month}月`)
    
    // 月统计有更大波动范围，固定数据（活牛价格调整为元/斤）
    monthlyLiveCattle.push(Math.round((27.5 + Math.sin(i * 0.8) * 3.5 + Math.cos(i * 0.6) * 2.8) * 10) / 10)
    monthlyFreshMeat.push(Math.round((76.0 + Math.sin(i * 0.9) * 3.0 + Math.cos(i * 0.7) * 2.5) * 10) / 10)
  }
  
  return {
    daily: {
      title: '日统计',
      title_tibetan: 'ཉིན་རེའི་གོང་རིས།',
      dates: dailyDates,
      liveCattlePrice: dailyLiveCattle,
      freshMeatPrice: dailyFreshMeat
    },
    weekly: {
      title: '周统计',
      title_tibetan: 'གཟའ་འཁོར་གོང་རིས།',
      dates: weeklyDates,
      liveCattlePrice: weeklyLiveCattle,
      freshMeatPrice: weeklyFreshMeat
    },
    monthly: {
      title: '月统计',
      title_tibetan: 'ཟླ་བའི་གོང་རིས།',
      dates: monthlyDates,
      liveCattlePrice: monthlyLiveCattle,
      freshMeatPrice: monthlyFreshMeat
    }
  }
}

// 从JSON文件加载价格数据
const loadPriceData = async () => {
  try {
    loading.value = true
    error.value = ''
    
    // 直接使用动态生成的数据
    priceData.value = generateDynamicData()
    
    // 设置初始周期
    updateCurrentPeriod()
    
    console.log('价格数据生成成功:', priceData.value)
  } catch (err) {
    console.error('生成价格数据失败:', err)
    error.value = '生成价格数据失败，请稍后重试'
    
    // 使用最简单的后备数据
    const fallbackDate = new Date()
    priceData.value = {
      daily: {
        title: '日统计',
        title_tibetan: 'ཉིན་རེའི་གོང་རིས།',
        dates: [`${fallbackDate.getMonth() + 1}/${fallbackDate.getDate()}`],
        liveCattlePrice: [5600],
        freshMeatPrice: [76.5]
      }
    }
    updateCurrentPeriod()
  } finally {
    loading.value = false
  }
}

// 更新当前周期
const updateCurrentPeriod = () => {
  const periodType = periodTypes[currentPeriodIndex.value]
  currentPeriodType.value = periodType
  
  if (priceData.value[periodType]) {
    currentPeriod.value = {
      title: priceData.value[periodType].title,
      title_tibetan: priceData.value[periodType].title_tibetan
    }
    
    // 更新图表
    if (chartInstance && !loading.value) {
      initChart()
    }
  }
}

// 自动切换周期
const switchPeriod = () => {
  currentPeriodIndex.value = (currentPeriodIndex.value + 1) % periodTypes.length
  updateCurrentPeriod()
}

// 手动切换到指定周期
const switchToPeriod = (index) => {
  currentPeriodIndex.value = index
  updateCurrentPeriod()
  console.log(`手动切换到: ${periodTypes[index]}`)
}

// 切换自动/手动模式
const toggleAutoSwitch = () => {
  autoSwitch.value = !autoSwitch.value
  
  if (autoSwitch.value) {
    // 启动自动切换
    if (switchTimer) {
      clearInterval(switchTimer)
    }
    switchTimer = setInterval(() => {
      switchPeriod()
    }, 10000)
    console.log('启动自动切换模式')
  } else {
    // 停止自动切换
    if (switchTimer) {
      clearInterval(switchTimer)
      switchTimer = null
    }
    console.log('切换到手动模式')
  }
}

const initChart = () => {
  if (!chartRef.value || loading.value) return
  
  const currentData = priceData.value[currentPeriodType.value]
  if (!currentData) return
  
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(15, 25, 45, 0.95)',
      borderColor: '#409EFF',
      borderWidth: 2,
      textStyle: {
        color: '#fff',
        fontSize: 36
      },
      formatter: function(params) {
        let result = `<div style="padding: 20px;">`
        result += `<strong style="color: #409EFF; font-size: 40px;">${params[0].axisValue}</strong><br/>`
        params.forEach(param => {
          result += `<span style="color: ${param.color}; font-size: 36px;">● ${param.seriesName}: ${param.value.toFixed(param.seriesName.includes('活牛') ? 1 : 1)}元/斤</span><br/>`
        })
        result += `</div>`
        return result
      }
    },
    legend: {
      data: ['活牛价格', '鲜肉价格'],
      top: '8%',
      textStyle: {
        color: '#a0a8b8',
        fontSize: 40
      },
      itemWidth: 50,
      itemHeight: 35
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '18%',
      top: '25%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: currentData.dates,
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 2
        }
      },
      axisLabel: {
        color: '#a0a8b8',
        fontSize: 32
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '价格(元/斤)',
      nameTextStyle: {
        color: '#ffffff',
        fontSize: 36,
        padding: [0, 0, 0, 20]
      },
      position: 'left',
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 2
        }
      },
      axisLabel: {
        color: '#a0a8b8',
        fontSize: 32,
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          width: 1
        }
      }
    },
    series: [
      {
        name: '活牛价格',
        type: 'line',
        data: currentData.liveCattlePrice,
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        lineStyle: {
          color: '#409EFF',
          width: 6
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
            ]
          }
        }
      },
      {
        name: '鲜肉价格',
        type: 'line',
        data: currentData.freshMeatPrice,
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        lineStyle: {
          color: '#67C23A',
          width: 6
        },
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.05)' }
            ]
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option, true)
}

onMounted(async () => {
  // 加载数据
  await loadPriceData()
  
  // 初始化图表
  initChart()
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
  
  // 根据autoSwitch状态启动自动切换
  if (autoSwitch.value) {
    switchTimer = setInterval(() => {
      switchPeriod()
    }, 10000)
    console.log('PriceTrendChart组件已加载，自动切换模式已启动')
  } else {
    console.log('PriceTrendChart组件已加载，手动模式')
  }
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  if (switchTimer) {
    clearInterval(switchTimer)
    switchTimer = null
  }
  
  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})
</script>

<style scoped>
.price-trend-card {
  height: 100%;
  background: rgba(15, 25, 45, 0.4);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 32px;
  padding: 48px;
  display: flex;
  flex-direction: column;
  box-shadow: 
    0 16px 64px rgba(0, 0, 0, 0.3),
    0 8px 32px rgba(64, 158, 255, 0.1),
    inset 0 2px 0 rgba(255, 255, 255, 0.1);
}

.card-header {
  margin-bottom: 32px;
}

.title-container {
  width: 100%;
}

.card-title {
  font-size: 48px;
  font-weight: 700;
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
  text-align: left;
  line-height: 1.2;
}

.title-tibetan {
  font-size: 36px;
  font-weight: 600;
  color: #a0a8b8;
  margin-left: 16px;
  display: inline;
  white-space: nowrap;
}

.loading-message {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #a0a8b8;
  font-size: 32px;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 4px solid rgba(64, 158, 255, 0.2);
  border-top: 4px solid #409EFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

.error-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #F56C6C;
  font-size: 32px;
  text-align: center;
}

.chart-container {
  flex: 1;
  min-height: 0;
}

.chart {
  width: 100%;
  height: 100%;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.controls-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  gap: 32px;
}

.period-buttons {
  display: flex;
  gap: 16px;
}

.period-btn {
  background: rgba(64, 158, 255, 0.1);
  border: 2px solid rgba(64, 158, 255, 0.3);
  border-radius: 16px;
  padding: 16px 32px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #a0a8b8;
  font-size: 32px;
  min-width: 160px;
}

.period-btn:hover {
  background: rgba(64, 158, 255, 0.2);
  border-color: rgba(64, 158, 255, 0.5);
  transform: translateY(-2px);
}

.period-btn.active {
  background: rgba(64, 158, 255, 0.3);
  border-color: #409EFF;
  color: #409EFF;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.3);
}

.period-btn .btn-text {
  font-weight: 600;
  margin-bottom: 4px;
}

.period-btn .btn-text-tibetan {
  font-size: 28px;
  opacity: 0.8;
}

.auto-switch-control {
  margin-left: auto;
}

.auto-btn {
  background: rgba(103, 194, 58, 0.1);
  border: 2px solid rgba(103, 194, 58, 0.3);
  border-radius: 16px;
  padding: 16px 32px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #a0a8b8;
  font-size: 32px;
  min-width: 200px;
}

.auto-btn:hover {
  background: rgba(103, 194, 58, 0.2);
  border-color: rgba(103, 194, 58, 0.5);
  transform: translateY(-2px);
}

.auto-btn.active {
  background: rgba(103, 194, 58, 0.3);
  border-color: #67C23A;
  color: #67C23A;
  box-shadow: 0 8px 24px rgba(103, 194, 58, 0.3);
}

.auto-btn .btn-text {
  font-weight: 600;
  margin-bottom: 4px;
}

.auto-btn .btn-text-tibetan {
  font-size: 28px;
  opacity: 0.8;
}
</style> 