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

/**
 * 文件职责：财务概览利润走势图卡片。
 */
import type {
  FinanceOverviewProfitTrendPointDto,
  FinanceOverviewTrendRange,
} from '#/api/finance/overview';

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

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

import {
  formatAxisAmount,
  formatCurrency,
} from '../composables/overview-page/helpers';

interface Props {
  points: FinanceOverviewProfitTrendPointDto[];
  range: FinanceOverviewTrendRange;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'update:range', value: FinanceOverviewTrendRange): void;
}>();

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

function renderChart() {
  renderEcharts({
    tooltip: {
      trigger: 'axis',
      formatter(params: unknown) {
        if (!Array.isArray(params) || params.length === 0) return '';
        const records = params as Array<{
          axisValue?: string;
          seriesName?: string;
          value?: number;
        }>;

        const date = records[0]?.axisValue ?? '';
        const revenue = Number(
          records.find((item) => item.seriesName === '营收')?.value ?? 0,
        );
        const cost = Number(
          records.find((item) => item.seriesName === '成本')?.value ?? 0,
        );
        const netProfit = Number(
          records.find((item) => item.seriesName === '净利润')?.value ?? 0,
        );

        return `${date}<br/>营收：${formatCurrency(revenue)}<br/>成本：${formatCurrency(cost)}<br/>净利润：${formatCurrency(netProfit)}`;
      },
    },
    grid: {
      left: '1%',
      right: '2%',
      bottom: '2%',
      top: '8%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisTick: { show: false },
      axisLine: {
        lineStyle: {
          color: '#e5e7eb',
        },
      },
      data: props.points.map((item) => item.dateLabel),
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => formatAxisAmount(value),
      },
      splitLine: {
        lineStyle: {
          color: '#f1f5f9',
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '营收',
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: '#1677ff',
          width: 2.5,
        },
        data: props.points.map((item) => item.revenueAmount),
      },
      {
        name: '成本',
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: '#ef4444',
          width: 2,
          type: 'dashed',
        },
        data: props.points.map((item) => item.costAmount),
      },
      {
        name: '净利润',
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: '#22c55e',
          width: 2.5,
        },
        data: props.points.map((item) => item.netProfitAmount),
      },
    ],
  });
}

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

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

<template>
  <div class="fo-section-card">
    <div class="fo-section-head">
      <div class="fo-section-title">利润走势</div>

      <div class="fo-pills">
        <button
          class="fo-pill"
          :class="{ 'is-active': props.range === '7' }"
          type="button"
          @click="emit('update:range', '7')"
        >
          近7天
        </button>
        <button
          class="fo-pill"
          :class="{ 'is-active': props.range === '30' }"
          type="button"
          @click="emit('update:range', '30')"
        >
          近30天
        </button>
      </div>
    </div>

    <EchartsUI ref="chartRef" class="fo-profit-chart" />

    <div class="fo-profit-legend">
      <div class="fo-profit-legend-item">
        <span class="fo-profit-legend-line is-revenue"></span>
        营收
      </div>
      <div class="fo-profit-legend-item">
        <span class="fo-profit-legend-line is-cost"></span>
        成本
      </div>
      <div class="fo-profit-legend-item">
        <span class="fo-profit-legend-line is-net"></span>
        净利润
      </div>
    </div>
  </div>
</template>
