<template>
  <div class="market-price-container">
    <!-- 产品类型选项卡 -->
    <div class="product-tabs">
      <a-tabs v-model:activeKey="activeProductTab" @change="handleTabChange">
        <a-tab-pane key="beef" tab="育肥牛"></a-tab-pane>
        <a-tab-pane key="dairy" tab="繁殖牛"></a-tab-pane>
        <a-tab-pane key="milk" tab="奶牛"></a-tab-pane>
      </a-tabs>
    </div>
    
    <div class="content-layout">
      <!-- 左侧内容 -->
      <div class="left-content">
        <!-- 本市价格信息卡片 -->
        <a-card class="price-info-card">
          <template #title>
            <div class="card-title">
              <span>本市{{ productTypeText }}价格</span>
              <span class="price-date">{{ priceDate }}</span>
            </div>
          </template>
          <div class="price-info">
            <div class="current-price">
              <span class="price-value">{{ currentPrice }}</span>
              <span class="price-unit">元/公斤</span>
            </div>
            <div class="price-change">
              <span class="change-value" :style="{ color: isPriceIncrease ? '#52c41a' : '#ff4d4f' }">
                {{ priceChange }}
              </span>
              <span class="change-percent" :style="{ color: isPriceIncrease ? '#52c41a' : '#ff4d4f' }">
                {{ priceChangePercent }}
              </span>
            </div>
          </div>
        </a-card>
        
        <!-- 价格走势图表 -->
        <a-card class="chart-card" title="价格走势">
          <div ref="priceChartRef" class="chart-container"></div>
        </a-card>
      </div>
      
      <!-- 右侧内容 -->
      <div class="right-content">
        <!-- 各省价格对比图表 -->
        <a-card class="province-chart-card" title="各省价格对比">
          <div ref="provinceChartRef" class="province-chart-container"></div>
        </a-card>
      </div>
    </div>
  </div>
</template>

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

// 当前选中的产品类型
const activeProductTab = ref('beef')

// 响应式数据
const currentPrice = ref('--')
const priceChange = ref('--')
const priceChangePercent = ref('--')
const priceDate = ref('--')
const priceTrendData = ref([])
const provincePricesData = ref([])
const isPriceIncrease = ref(true)

// 图表引用
const priceChartRef = ref(null)
const provinceChartRef = ref(null)

// 图表实例
let priceChart = null
let provinceChart = null

// 产品类型文本映射
const productTypeText = computed(() => {
  const map = {
    beef: '育肥牛',
    dairy: '繁殖牛',
    milk: '奶牛'
  }
  return map[activeProductTab.value] || '育肥牛'
})

// 从后端获取市场行情数据（统一封装）
import api from '@/utils/api-redesigned'

const fetchMarketPriceData = async (type = 'beef') => {
  try {
    const data = await api.dashboard.getMarketPrice({ type })
    
    // 更新数据
    currentPrice.value = data.currentPrice
    priceChange.value = data.priceChange
    priceChangePercent.value = data.priceChangePercent
    priceDate.value = data.priceDate
    priceTrendData.value = data.priceTrend
    provincePricesData.value = data.provincePrices
    
    // 判断价格是否上涨
    isPriceIncrease.value = data.priceChange.startsWith('+')
    
    // 初始化或更新图表
    updatePriceChart()
    updateProvinceChart()
  } catch (error) {
    console.error('获取市场行情数据失败:', error)
  }
}

// 初始化或更新价格走势图表
const updatePriceChart = () => {
  if (!priceChartRef.value) return
  
  // 如果图表实例不存在，则创建
  if (!priceChart) {
    priceChart = echarts.init(priceChartRef.value)
    
    // 添加窗口大小改变时的响应式调整
    window.addEventListener('resize', () => {
      if (priceChart) {
        priceChart.resize()
      }
    })
  }
  
  // 提取日期和价格数据
  const dates = priceTrendData.value.map(item => item.date)
  const prices = priceTrendData.value.map(item => item.price)
  
  // 计算Y轴范围
  const minPrice = Math.min(...prices) * 0.9
  const maxPrice = Math.max(...prices) * 1.1
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 45,
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      min: Math.floor(minPrice),
      max: Math.ceil(maxPrice),
      interval: Math.ceil((maxPrice - minPrice) / 5)
    },
    series: [
      {
        type: 'line',
        data: prices,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#1890ff'
        },
        lineStyle: {
          width: 2
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  }
  
  priceChart.setOption(option)
}

// 初始化或更新各省价格对比图表
const updateProvinceChart = () => {
  if (!provinceChartRef.value) return
  
  // 如果图表实例不存在，则创建
  if (!provinceChart) {
    provinceChart = echarts.init(provinceChartRef.value)
    
    // 添加窗口大小改变时的响应式调整
    window.addEventListener('resize', () => {
      if (provinceChart) {
        provinceChart.resize()
      }
    })
  }
  
  // 提取省份和价格数据
  const provinces = provincePricesData.value.map(item => item.province)
  const prices = provincePricesData.value.map(item => item.price)
  
  // 计算X轴范围
  const maxPrice = Math.max(...prices) * 1.1
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: 0,
      max: Math.ceil(maxPrice),
      interval: Math.ceil(maxPrice / 5)
    },
    yAxis: {
      type: 'category',
      data: provinces,
      axisLabel: {
        fontSize: 10
      }
    },
    series: [
      {
        type: 'bar',
        data: prices,
        itemStyle: {
          color: '#4e7bff'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        }
      }
    ]
  }
  
  provinceChart.setOption(option)
}

// 处理选项卡切换
const handleTabChange = (key) => {
  activeProductTab.value = key
  fetchMarketPriceData(key)
}

// 组件挂载时初始化数据和图表
onMounted(() => {
  // 延迟执行，确保DOM已完全渲染
  setTimeout(() => {
    fetchMarketPriceData(activeProductTab.value)
  }, 100)
})

// 组件卸载时销毁图表实例
const onUnmounted = () => {
  if (priceChart) {
    priceChart.dispose()
    priceChart = null
  }
  if (provinceChart) {
    provinceChart.dispose()
    provinceChart = null
  }
}
</script>

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

.product-tabs {
  margin-bottom: 20px;
}

.content-layout {
  display: flex;
  gap: 20px;
}

.left-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.right-content {
  flex: 1;
}

.price-info-card {
  margin-bottom: 0;
}

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

.price-date {
  font-size: 14px;
  color: #999;
}

.price-info {
  display: flex;
  align-items: flex-end;
  gap: 20px;
  padding: 10px 0;
}

.current-price {
  display: flex;
  align-items: baseline;
}

.price-value {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
  line-height: 1;
}

.price-unit {
  font-size: 14px;
  color: #666;
  margin-left: 5px;
}

.price-change {
  display: flex;
  flex-direction: column;
}

.change-value {
  font-size: 16px;
  color: #52c41a;
}

.change-percent {
  font-size: 14px;
  color: #52c41a;
}

.chart-container {
  height: 300px;
}

.province-chart-container {
  height: 600px;
}
</style>