<template>
  <div class="chart-card">
    <div class="chart-card-header">
      <span class="chart-card-title">支出排名分析</span>
    </div>
    <div class="rank-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_YEARRANK_Y001',
    }
    const res = await getItemInfoList(params)
    vList.value = res || []
  } catch (error) {
    console.error(error)
    vList.value = []
  }
}

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

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(el)

  const sortedList = [...vList.value]
    .sort((a, b) => Number(b.index01 || 0) - Number(a.index01 || 0))
    .slice(0, 10)

  const yData = sortedList.map((item, index) => `${index + 1}. ${item.xaxis || '未知'}`)
  const valueData = sortedList.map(item => Number((Number(item.index01 || 0) / 10000).toFixed(2)) || 0)
  const percentData = sortedList.map(item => Number(Number(item.index02 || 0).toFixed(2)) || 0)
  const originalData = sortedList.map(item => Number(item.index01 || 0))

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(145, 200, 255, 0.9)',
      borderColor: '#409EFF',
      borderWidth: 1,
      textStyle: { color: '#0a3b70' },
      padding: [8, 12],
      borderRadius: 6,
      formatter: params => {
        const idx = params[0].dataIndex
        const name = params[0].name
        const amount = originalData[idx]
        const rate = percentData[idx]
        return `
<div style="text-align:center; font-weight:bold; margin-bottom:6px">${name}</div>
<table style="width:100%; border-collapse:collapse; text-align:center">
  <tr>
    <td style="border:1px solid #409EFF; padding:4px; font-weight:bold">支出(元)</td>
    <td style="border:1px solid #409EFF; padding:4px; font-weight:bold">占比(%)</td>
  </tr>
  <tr>
    <td style="border:1px solid #409EFF; padding:4px">${amount}</td>
    <td style="border:1px solid #409EFF; padding:4px">${rate}</td>
  </tr>
</table>
        `
      }
    },
    legend: {
      show: false
    },
    grid: {
      left: '5%',
      right: '15%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'value',
        axisLabel: { fontSize: 11, color: '#b4c7e7' },
        axisLine: { lineStyle: { color: '#1a508b' } },
        splitLine: { lineStyle: { color: 'rgba(26, 80, 139, 0.3)' } }
      }
    ],
    yAxis: [
      {
        type: 'category',
        data: yData,
        axisLabel: { fontSize: 11, color: '#b4c7e7' },
        axisLine: { lineStyle: { color: '#1a508b' } },
        inverse: true
      }
    ],
    series: [
      {
        name: '支出',
        type: 'bar',
        barWidth: '12%',
        data: valueData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#409EFF' },
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#1890FF' }
          ])
        },
        label: {
          show: true,
          position: 'right',
          fontSize: 10,
          color: '#e0e6ff',
          formatter: params => `${params.value} 万元 (${percentData[params.dataIndex]}%)`
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

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

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

onMounted(() => {
  initRankChart()
  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;
}

.rank-chart-container {
  flex: 1;
  width: 100%;
  height: calc(100% - 40px);
}

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