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

/**
 * 文件职责：成本分析构成环图与图例。
 */
import type { FinanceCostCompositionDto } from '#/api/finance/cost';

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

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

import { COST_CATEGORY_COLOR_MAP } from '../composables/cost-page/constants';
import {
  formatCurrency,
  formatPercent,
} from '../composables/cost-page/helpers';

interface Props {
  composition: FinanceCostCompositionDto[];
}

const props = defineProps<Props>();

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

const totalCost = computed(() =>
  (props.composition ?? []).reduce(
    (sum, item) => sum + Number(item.amount || 0),
    0,
  ),
);

function renderChart() {
  const source = props.composition ?? [];
  renderEcharts({
    tooltip: {
      trigger: 'item',
      formatter(params: unknown) {
        const data = params as {
          name?: string;
          percent?: number;
          value?: number;
        };
        return `${data.name ?? ''}<br/>${formatCurrency(data.value ?? 0)} (${formatPercent(data.percent ?? 0)})`;
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['52%', '76%'],
        center: ['50%', '50%'],
        data: source.map((item) => ({
          name: item.categoryText,
          value: item.amount,
          itemStyle: {
            color: COST_CATEGORY_COLOR_MAP[item.category] ?? '#2563eb',
          },
        })),
        label: {
          show: false,
        },
      },
    ],
  });
}

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

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

<template>
  <div class="fc-composition-card">
    <div class="fc-section-title">成本构成</div>

    <div class="fc-composition-body">
      <div class="fc-composition-chart-wrap">
        <EchartsUI ref="chartRef" class="fc-composition-chart" />
        <div class="fc-composition-center">
          <div class="fc-composition-center-value">
            {{ formatCurrency(totalCost) }}
          </div>
          <div class="fc-composition-center-label">总成本</div>
        </div>
      </div>

      <div class="fc-composition-legend">
        <div
          v-for="item in props.composition"
          :key="item.category"
          class="fc-composition-legend-item"
        >
          <span
            class="fc-composition-dot"
            :style="{ backgroundColor: COST_CATEGORY_COLOR_MAP[item.category] }"
          ></span>
          <span class="fc-composition-name">{{ item.categoryText }}</span>
          <span class="fc-composition-amount">{{
            formatCurrency(item.amount)
          }}</span>
          <span class="fc-composition-percent">{{
            formatPercent(item.percentage)
          }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
