<template>
  <div class="chart-card">
    <div class="chart-card-header">
      <span class="chart-card-title">支出结构分析</span>
    </div>
    <div class="pie-chart-container" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getItemInfoList } from '@/api/bizApi'

const props = defineProps({
  formParams: {
    type: Object,
    default: () => ({})
  }
})

const vList = ref([])
const chartRef = ref(null)
let chartInstance = null
const resizeHandler = () => chartInstance?.resize()

async function getList() {
  try {
    const params = {
      ...props.formParams,
      itemCode: 'ERP_CATEGORY_Y001',
    }
    const res = await getItemInfoList(params)
    vList.value = res || []
  } catch (error) {
    console.error('获取支出数据失败:', error)
    vList.value = []
  }
}

const initPieChart = () => {
  const el = chartRef.value
  if (!el) return

  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(el)

  const pieData = vList.value.map(item => {
    const originalValue = item.index01 || 0
    const wanValue = (originalValue / 10000).toFixed(2)
    return {
      name: item.xaxis || '未知分类',
      value: Number(wanValue),
      originalValue: originalValue
    }
  }).filter(item => item.value > 0)

  const colorList = [
    '#409EFF', '#36CFc9', '#67C23A', '#E6A23C', '#F56C6C',
    '#909399', '#722ED1', '#EB2F96', '#1890FF', '#52C41A',
    '#FAAD14', '#F5222D', '#8C8C8C', '#A062D4', '#F7BA1E'
  ]

  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(145, 200, 255, 0.9)',
      borderColor: '#409EFF',
      borderWidth: 1,
      textStyle: { color: '#0a3b70', fontSize: 12 },
      padding: [10, 15],
      borderRadius: 6,
      formatter: function(params) {
        return `分类：${params.name}<br/>支出：${params.data.originalValue}元<br/>占比：${params.percent.toFixed(1)}%`
      }
    },
    legend: {
      orient: 'horizontal',
      top: '10%',
      left: 'center',
      textStyle: { fontSize: 11, color: '#e0e6ff' },
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 10,
      pageIconColor: '#409EFF',
      pageTextStyle: { color: '#e0e6ff', fontSize: 10 },
      pageButtonItemGap: 6,
      pageButtonGap: 10,
      type: 'scroll'
    },
    series: [
      {
        name: '支出',
        type: 'pie',
        radius: ['30%', '55%'],
        center: ['50%', '65%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 4,
          borderColor: 'rgba(15, 52, 96, 0.9)',
          borderWidth: 1
        },
        label: {
          show: true,
          position: 'outside',
          fontSize: 10,
          color: '#e0e6ff',
          formatter: '{b} {c}万元 ({d}%)',
          overflow: 'truncate',
          ellipsis: '...',
          distance: 8
        },
        labelLine: {
          show: true,
          length: 12,
          length2: 8,
          lineStyle: { color: '#e0e6ff', width: 1 },
          smooth: 0.2,
          minTurnAngle: 45
        },
        data: pieData,
        color: colorList
      }
    ]
  }

  chartInstance.setOption(option)
}

watch(
  () => props.formParams,
  () => {
    getList()
  },
  { deep: true, immediate: true }
)

watch(vList, () => {
  initPieChart()
}, { deep: true })

onMounted(() => {
  window.addEventListener('resize', resizeHandler)
})

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

<style scoped>
.chart-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chart-card-header {
  height: 40px;
  line-height: 40px;
  padding: 0 16px;
  background-color: rgba(26, 80, 139, 0.5);
  border-bottom: 1px solid #1a508b;
  display: flex;
  align-items: center;
}

.chart-card-title {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  letter-spacing: 0.5px;
}

.pie-chart-container {
  flex: 1;
  width: 100%;
  height: calc(100% - 40px);
  margin: 0;
  padding: 0;
}

:deep(.echarts-tooltip) {
  background-color: rgba(145, 200, 255, 0.9) !important;
  border-color: #409EFF !important;
  color: #0a3b70 !important;
  border-radius: 6px !important;
}

:deep(.echarts-legend-scroll) {
  background-color: transparent !important;
}
:deep(.echarts-legend-scroll-text) {
  color: #e0e6ff !important;
  font-size: 11px !important;
}
:deep(.echarts-legend-scroll-button) {
  border-color: #1a508b !important;
}
:deep(.echarts-legend-scroll-button-icon) {
  color: #409EFF !important;
}

:deep(.ec-label) {
  z-index: 9999 !important;
  white-space: nowrap !important;
  font-size: 10px !important;
  color: #e0e6ff !important;
}

:deep(.ec-label-line) {
  stroke: #e0e6ff !important;
  stroke-width: 1px !important;
}
</style>