<template>
  <div class="chart-card">
    <div class="chart-card-header">
      <span class="chart-card-title">环比收支分析</span>
    </div>
    <div class="bar-line-chart-container" ref="chartRef"></div>
  </div>
</template>

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

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_YEARDATA_M001',
    }
    const res = await getItemInfoList(params)
    vList.value = res || []
  } catch (error) {
    console.error(error)
    vList.value = []
  }
}

function initChart() {
  const el = chartRef.value
  if (!el) return

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

  const baseOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      backgroundColor: 'rgba(145, 200, 255, 0.9)',
      borderColor: '#409EFF',
      borderWidth: 1,
      textStyle: { color: '#0a3b70' },
      padding: [8, 12],
      borderRadius: 6
    },
    legend: {
      top: '10',
      left: 'center',
      textStyle: { fontSize: 12, color: '#e0e6ff' },
      data: ['收入', '支出', '占比', '上月收入', '上月支出', '收入环比', '支出环比', '本月净利润']
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: [],
        axisLabel: {
          fontSize: 11,
          interval: 0,
          color: '#b4c7e7'
        },
        axisLine: { lineStyle: { color: '#1a508b' } },
        boundaryGap: true
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '金额 (万元)',
        nameTextStyle: { fontSize: 12, color: '#b4c7e7' },
        axisLabel: { formatter: '{value}', color: '#b4c7e7' },
        axisLine: { lineStyle: { color: '#1a508b' } },
        splitLine: { lineStyle: { color: 'rgba(26, 80, 139, 0.3)' } }
      },
      {
        type: 'value',
        name: '占比/环比 (%)',
        nameTextStyle: { fontSize: 12, color: '#b4c7e7' },
        axisLabel: { formatter: '{value} %', color: '#b4c7e7' },
        axisLine: { lineStyle: { color: '#1a508b' } },
        splitLine: { lineStyle: { color: 'rgba(26, 80, 139, 0.2)' } },
        min: 'dataMin',
        max: 'dataMax',
        scale: true
      }
    ],
    series: [
      {
        name: '收入',
        type: 'line',
        yAxisIndex: 0,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#67C23A' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '支出',
        type: 'line',
        yAxisIndex: 0,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#F56C6C' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(245, 108, 108, 0.3)' },
            { offset: 1, color: 'rgba(245, 108, 108, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '占比',
        type: 'line',
        yAxisIndex: 1,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#409EFF' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '上月收入',
        type: 'line',
        yAxisIndex: 0,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#36CFc9' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(54, 207, 201, 0.3)' },
            { offset: 1, color: 'rgba(54, 207, 201, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '上月支出',
        type: 'line',
        yAxisIndex: 0,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#E6A23C' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
            { offset: 1, color: 'rgba(230, 162, 60, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '收入环比',
        type: 'line',
        yAxisIndex: 1,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#722ED1' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(114, 46, 209, 0.3)' },
            { offset: 1, color: 'rgba(114, 46, 209, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '支出环比',
        type: 'line',
        yAxisIndex: 1,
        data: [],
        smooth: true,
        lineStyle: { width: 1.5, color: '#EB2F96' },
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(235, 47, 150, 0.3)' },
            { offset: 1, color: 'rgba(235, 47, 150, 0.0)' }
          ])
        },
        emphasis: {
          lineStyle: { width: 2 },
          symbolSize: 7
        }
      },
      {
        name: '本月净利润',
        type: 'bar',
        yAxisIndex: 0,
        data: [],
        barWidth: '8%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#FF9D28' },
            { offset: 1, color: '#FAAD14' }
          ]),
          borderRadius: [8, 8, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          fontSize: 10,
          color: '#fff',
          formatter: '{c}'
        }
      }
    ]
  }

  if (vList.value.length > 0) {
    const xData = vList.value.map(item => {
      const xaxis = item.xaxis || ''
      return xaxis.includes('月') ? xaxis : `${xaxis}月`;
    })
    const incomeYuan = vList.value.map(item => Number(item.index01 || 0))
    const expenseYuan = vList.value.map(item => Number(item.index02 || 0))
    const rate = vList.value.map(item => Number(item.index03 || 0).toFixed(2))
    const lastMonthIncomeYuan = vList.value.map(item => Number(item.index04 || 0))
    const lastMonthExpenseYuan = vList.value.map(item => Number(item.index05 || 0))
    const netProfitYuan = vList.value.map(item => (Number(item.index01 || 0) - Number(item.index02 || 0)).toFixed(2))

    const incomeRingRatio = vList.value.map((item, idx) => {
      const lastVal = lastMonthIncomeYuan[idx]
      const currVal = incomeYuan[idx] || 0
      return lastVal === 0 ? '0.00' : ((currVal - lastVal) / lastVal * 100).toFixed(2)
    })
    const expenseRingRatio = vList.value.map((item, idx) => {
      const lastVal = lastMonthExpenseYuan[idx]
      const currVal = expenseYuan[idx] || 0
      return lastVal === 0 ? '0.00' : ((currVal - lastVal) / lastVal * 100).toFixed(2)
    })

    const incomeWan = incomeYuan.map(val => (val / 10000).toFixed(2))
    const expenseWan = expenseYuan.map(val => (val / 10000).toFixed(2))
    const lastMonthIncomeWan = lastMonthIncomeYuan.map(val => (val / 10000).toFixed(2))
    const lastMonthExpenseWan = lastMonthExpenseYuan.map(val => (val / 10000).toFixed(2))
    const netProfitWan = netProfitYuan.map(val => (val / 10000).toFixed(2))

    baseOption.tooltip.formatter = function (params) {
      const title = params[0].axisValue
      const idx = params[0].dataIndex
      return `
<div style="text-align:center; font-weight:bold; margin-bottom:6px">${title}</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>
    <td style="border:1px solid #409EFF; padding:4px; font-weight:bold">上月收入(元)</td>
    <td style="border:1px solid #409EFF; padding:4px; font-weight:bold">上月支出(元)</td>
    <td style="border:1px solid #409EFF; padding:4px; font-weight:bold">收入环比(%)</td>
    <td style="border:1px solid #409EFF; padding:4px; font-weight:bold">支出环比(%)</td>
    <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">${incomeYuan[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${expenseYuan[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${lastMonthIncomeYuan[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${lastMonthExpenseYuan[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${incomeRingRatio[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${expenseRingRatio[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${rate[idx]}</td>
    <td style="border:1px solid #409EFF; padding:4px">${netProfitYuan[idx]}</td>
  </tr>
</table>
      `
    }

    baseOption.xAxis[0].data = xData
    baseOption.series[0].data = incomeWan
    baseOption.series[1].data = expenseWan
    baseOption.series[2].data = rate
    baseOption.series[3].data = lastMonthIncomeWan
    baseOption.series[4].data = lastMonthExpenseWan
    baseOption.series[5].data = incomeRingRatio
    baseOption.series[6].data = expenseRingRatio
    baseOption.series[7].data = netProfitWan
  }

  chartInstance.setOption(baseOption, true)
}

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

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

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

.bar-line-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;
  white-space: nowrap !important;
  max-width: none !important;
}
</style>