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

/**
 * 文件职责：财务概览构成环图卡片。
 */
import type { FinanceOverviewCompositionViewItem } from '../types';

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

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

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

interface Props {
  items: FinanceOverviewCompositionViewItem[];
  title: string;
  totalAmount: number;
  totalLabel: string;
}

const props = defineProps<Props>();

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

function renderChart() {
  renderEcharts({
    tooltip: {
      trigger: 'item',
      formatter(params: unknown) {
        const record = params as {
          name?: string;
          percent?: number;
          value?: number;
        };
        return `${record.name ?? ''}<br/>${formatCurrency(Number(record.value ?? 0))} (${formatPercent(Number(record.percent ?? 0))})`;
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['55%', '76%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        label: {
          show: false,
        },
        data: props.items.map((item) => ({
          name: item.name,
          value: item.amount,
          itemStyle: {
            color: item.color,
          },
        })),
      },
    ],
  });
}

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

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

<template>
  <div class="fo-section-card">
    <div class="fo-section-title">{{ props.title }}</div>

    <div class="fo-composition-wrap">
      <div class="fo-composition-chart-wrap">
        <EchartsUI ref="chartRef" class="fo-composition-chart" />

        <div class="fo-composition-center">
          <div class="fo-composition-center-value">
            {{ formatCurrency(props.totalAmount) }}
          </div>
          <div class="fo-composition-center-label">{{ props.totalLabel }}</div>
        </div>
      </div>

      <div class="fo-composition-legend">
        <div
          v-for="item in props.items"
          :key="item.key"
          class="fo-composition-legend-item"
        >
          <span
            class="fo-composition-dot"
            :style="{ backgroundColor: item.color }"
          ></span>
          <span class="fo-composition-name">{{ item.name }}</span>
          <span class="fo-composition-percent">{{
            formatPercent(item.percentage)
          }}</span>
          <span class="fo-composition-amount">{{
            formatCurrency(item.amount)
          }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
