<script setup lang="ts">
import type { EchartsUIType } from '@vben/plugins/echarts';

/**
 * 文件职责：成本分析近 6 月趋势图。
 */
import type { FinanceCostTrendPointDto } from '#/api/finance/cost';

import { nextTick, onMounted, ref, watch } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

import { formatCurrency } from '../composables/cost-page/helpers';

interface Props {
  trend: FinanceCostTrendPointDto[];
}

const props = defineProps<Props>();

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

function renderChart() {
  const source = props.trend ?? [];
  renderEcharts({
    color: ['#2563eb', '#16a34a'],
    tooltip: {
      trigger: 'axis',
      formatter(params: unknown) {
        if (!Array.isArray(params)) return '';
        const records = params as Array<{
          axisValue?: string;
          seriesName?: string;
          value?: number;
        }>;
        const month = String(records[0]?.axisValue ?? '');
        const cost = Number(
          records.find((item) => item.seriesName === '总成本')?.value ?? 0,
        );
        const revenue = Number(
          records.find((item) => item.seriesName === '营业额')?.value ?? 0,
        );
        return `${month}<br/>总成本：${formatCurrency(cost)}<br/>营业额：${formatCurrency(revenue)}`;
      },
    },
    grid: {
      left: '3%',
      right: '3%',
      bottom: '1%',
      containLabel: true,
    },
    legend: {
      data: ['总成本', '营业额'],
      top: 0,
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      axisTick: { show: false },
      data: source.map((item) => item.month.slice(5)),
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#f1f5f9',
          type: 'dashed',
        },
      },
      axisLabel: {
        formatter: (value: number) => `${Math.round(value / 1000)}k`,
      },
    },
    series: [
      {
        name: '总成本',
        type: 'bar',
        barWidth: 22,
        data: source.map((item) => item.totalCost),
        itemStyle: {
          borderRadius: [6, 6, 0, 0],
        },
      },
      {
        name: '营业额',
        type: 'line',
        smooth: true,
        data: source.map((item) => item.revenue),
      },
    ],
  });
}

watch(
  () => props.trend,
  async () => {
    await nextTick();
    renderChart();
  },
  { deep: true },
);

onMounted(() => {
  renderChart();
});
</script>

<template>
  <div class="fc-chart-card">
    <div class="fc-section-title">近6个月成本趋势</div>
    <EchartsUI ref="chartRef" class="fc-trend-chart" />
  </div>
</template>
