<template>
  <BaseCard title="牦牛销售类型统计">
    <div class="sales-container">
      <div class="chart-wrapper">
        <div ref="chartRef" class="chart"></div>
      </div>
      <div class="legend-container">
        <div v-for="item in chartItems" :key="item.name" class="legend-item">
          <span class="legend-dot" :style="{ backgroundColor: item.color }"></span>
          <div class="legend-text">
            <span class="legend-name">{{ item.name }}：</span>
            <span class="legend-percent">{{ formatPercent(item.percent) }}%</span>
            <span class="legend-count">{{ item.value }}头</span>
          </div>
        </div>
      </div>
    </div>
  </BaseCard>
</template>

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

const API_URL = '/api/dashboard/yak-sales-type-stats'

const TYPE_COLORS = {
  屠宰: '#0051ea',
  养殖: '#f0a517',
  其他: '#d1d2d3'
}

const FALLBACK_COLORS = ['#0051ea', '#f0a517', '#d1d2d3', '#4dd9ff', '#ff6b6b']

const EMPTY_PLACEHOLDER_TYPES = [
  { name: '屠宰', value: 0, percent: 0 },
  { name: '养殖', value: 0, percent: 0 },
  { name: '其他', value: 0, percent: 0 }
]

const CHART_VIEW = {
  internalDiameterRatio: 0.58,
  boxHeight: 40,
  viewAlpha: 28,
  viewBeta: 48,
  viewDistance: 185,
  preserveOrder: true,
  labelMode: 'none',
  autoRotate: true,
  autoRotateSpeed: 5
}

const SLICE_OPACITY = 0.78

const chartRef = ref(null)
const salesData = ref([...EMPTY_PLACEHOLDER_TYPES])
let chartInstance = null

const colorList = computed(() => salesData.value.map((item, index) => (
  TYPE_COLORS[item.name] || FALLBACK_COLORS[index % FALLBACK_COLORS.length]
)))

const chartItems = computed(() => {
  return enrichPieData(salesData.value, colorList.value).map((item) => ({
    ...item,
    color: TYPE_COLORS[item.name] || item.color,
    opacity: SLICE_OPACITY
  }))
})

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

const buildFullOption = (data) => {
  const pieData = chartItems.value.filter((item) => item.value > 0)

  if (!pieData.length) {
    return buildEmptyPie3DPlaceholder(
      EMPTY_PLACEHOLDER_TYPES.map((item) => TYPE_COLORS[item.name]),
      CHART_VIEW
    )
  }

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

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

const normalizeItems = (items) => {
  const list = Array.isArray(items) ? items : []
  if (!list.length) {
    return [...EMPTY_PLACEHOLDER_TYPES]
  }

  return list.map((item) => ({
    name: item.name || '其他',
    value: Number(item.value ?? item.yakNumber) || 0,
    percent: Number(item.percent) || 0
  }))
}

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 || '接口返回异常')
    }

    salesData.value = normalizeItems(result.data)
    updateChart()
  } catch (error) {
    console.error('加载牦牛销售类型统计失败:', error)
  }
}

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

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>
.sales-container {
  display: flex;
  align-items: stretch;
  height: 100%;
  min-height: 0;
  gap: 12px;
  padding: 4px 6px 8px;
}

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

.chart {
  width: 100%;
  height: 100%;
  min-height: 180px;
}

.legend-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 18px;
  width: 168px;
  flex-shrink: 0;
  padding-right: 4px;
}

.legend-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  flex-shrink: 0;
  margin-top: 4px;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.25);
}

.legend-text {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 4px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: #ffffff;
}

.legend-name {
  color: #ffffff;
  font-weight: 500;
}

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

.legend-count {
  color: #ffffff;
  font-weight: 400;
}
</style>
