<template>
  <BaseCard title="综合销售统计">
    <div class="stats-container">
      <div class="tab-container">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          type="button"
          class="tab-item"
          :class="{ active: activeTab === tab.key }"
          @click="switchTab(tab.key)"
        >
          {{ tab.name }}
        </button>
      </div>

      <div class="chart-container">
        <div ref="chartRef" class="chart"></div>
      </div>

      <div v-if="legendItems.length" class="legend-panel">
        <div
          v-for="item in legendItems"
          :key="getItemLabel(item)"
          class="legend-item"
        >
          <span class="legend-dot" :style="{ background: item.color }"></span>
          <span class="legend-name">{{ getItemLabel(item) }}:</span>
          <span class="legend-percent">{{ formatPercent(item.percent) }}%</span>
          <span class="legend-value">{{ item.yakNumber }}头</span>
        </div>
      </div>
    </div>
  </BaseCard>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, computed, watch } from 'vue'
import * as echarts from 'echarts'
import 'echarts-gl'
import BaseCard from './BaseCard.vue'
import { buildPie3DOption, buildEmptyPie3DPlaceholder, enrichPieData } from '../utils/pie3d.js'

const chartRef = ref(null)
let chartInstance = null

const API_URL = '/api/dashboard/comprehensive-sales-stats'
const COLORS = ['#26c6c6', '#1e4bb8', '#85c7e9', '#f29f20', '#f26522', '#4dd9ff']

const CHART_VIEW = {
  internalDiameterRatio: 0.58,
  boxHeight: 40,
  viewAlpha: 28,
  viewBeta: 48,
  viewDistance: 185
}

const activeTab = ref('monthlySales')

const tabs = [
  { key: 'monthlySales', name: '本月销售统计' },
  { key: 'overallSalesDistribution', name: '总体销售分布' },
  { key: 'purchaseRegionDistribution', name: '采购地区分布' }
]

const statsData = reactive({
  monthlySales: [],
  overallSalesDistribution: [],
  purchaseRegionDistribution: []
})

const currentRawData = computed(() => statsData[activeTab.value] || [])

const getItemLabel = (item) => {
  if (activeTab.value === 'purchaseRegionDistribution') {
    return item.buyerPlace || '未知地区'
  }
  return item.originPlace || '未知地区'
}

const getItemValue = (item) => Number(item.yakNumber) || 0

const legendItems = computed(() => {
  return enrichPieData(
    currentRawData.value.map((item) => ({
      ...item,
      name: getItemLabel(item),
      value: getItemValue(item)
    })),
    COLORS
  ).filter((item) => item.value > 0)
})

const switchTab = (tabKey) => {
  activeTab.value = tabKey
}

const formatPercent = (value) => {
  return Number(value || 0).toFixed(2)
}

const buildFullOption = (data) => {
  const pieData = enrichPieData(
    data.map((item) => ({
      ...item,
      name: activeTab.value === 'purchaseRegionDistribution'
        ? (item.buyerPlace || '未知地区')
        : (item.originPlace || '未知地区'),
      value: Number(item.yakNumber) || 0
    })),
    COLORS
  ).filter((item) => item.value > 0)

  if (!pieData.length) {
    return buildEmptyPie3DPlaceholder(COLORS, CHART_VIEW)
  }

  return buildPie3DOption({
    pieData,
    ...CHART_VIEW
  })
}

const updateChart = () => {
  if (!chartInstance) return
  chartInstance.clear()
  chartInstance.setOption(buildFullOption(currentRawData.value), true)
  chartInstance.resize()
}

const loadData = async () => {
  try {
    const response = await fetch(API_URL)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const result = await response.json()
    if (result.code !== 1 || !result.data) {
      throw new Error(result.message || '接口返回异常')
    }

    statsData.monthlySales = result.data.monthlySales || []
    statsData.overallSalesDistribution = result.data.overallSalesDistribution || []
    statsData.purchaseRegionDistribution = result.data.purchaseRegionDistribution || []
    updateChart()
  } catch (error) {
    console.error('加载综合销售统计数据失败:', error)
  }
}

const handleResize = () => {
  chartInstance?.resize()
}

watch(activeTab, () => {
  updateChart()
})

onMounted(async () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
  }
  await loadData()
  window.addEventListener('resize', handleResize)
  window.addEventListener('dataReloaded', loadData)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('dataReloaded', loadData)
  chartInstance?.dispose()
})
</script>

<style scoped>
.stats-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.tab-container {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  height: 32px;
  padding: 0 6px;
  border: 1px solid rgba(45, 189, 255, 0.35);
  background: rgba(8, 36, 72, 0.75);
  color: #d8ecff;
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 13px;
  font-weight: 400;
  cursor: pointer;
  transition: all 0.25s ease;
}

.tab-item:hover {
  border-color: rgba(255, 200, 100, 0.55);
  color: #fff0c8;
}

.tab-item.active {
  border-color: rgba(255, 190, 80, 0.85);
  background: linear-gradient(180deg, rgba(120, 72, 18, 0.95) 0%, rgba(78, 46, 10, 0.95) 100%);
  color: #fff0c8;
  font-weight: 700;
  box-shadow: 0 0 12px rgba(255, 170, 60, 0.25);
}

.chart-container {
  position: relative;
  flex: 1;
  min-height: 200px;
}

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

.legend-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 18px;
  justify-content: center;
  padding: 6px 4px 2px;
  flex-shrink: 0;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 14px;
  color: #d8ecff;
  white-space: nowrap;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  flex-shrink: 0;
}

.legend-name {
  color: #ffffff;
}

.legend-percent {
  color: #8ecfff;
  font-weight: 700;
}

.legend-value {
  color: #ffffff;
}
</style>
