<script setup lang="ts">
import type { SalespersonDashboardTrendItem } from '../api';

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

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

const props = defineProps<{
  /** 来自 dashboardData.trend：按时间桶聚合的录入趋势 */
  data: SalespersonDashboardTrendItem[];
}>();

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

/** 录入总数兜底：兼容旧接口未返回 input_total 的情况 */
function resolveInputTotal(item: SalespersonDashboardTrendItem) {
  return item.input_total ?? item.clinic_count + item.pharmacy_count;
}

/**
 * 将 trend 数据映射为 ECharts series
 * - 堆叠柱：录入诊所 / 录入药店
 * - 折线：录入总数
 */
async function renderChart() {
  const labels = props.data.map((item) => item.label);
  const clinicData = props.data.map((item) => item.clinic_count);
  const pharmacyData = props.data.map((item) => item.pharmacy_count);
  const totalData = props.data.map((item) => resolveInputTotal(item));

  await renderEcharts({
    tooltip: { trigger: 'axis' },
    legend: { data: ['录入诊所', '录入药店', '录入总数'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: labels,
      axisLabel: { rotate: labels.length > 10 ? 45 : 0 },
    },
    yAxis: { type: 'value', name: '录入数(家)', minInterval: 1 },
    series: [
      {
        name: '录入诊所',
        type: 'bar',
        stack: 'input',
        data: clinicData,
        itemStyle: { color: '#1677ff' },
      },
      {
        name: '录入药店',
        type: 'bar',
        stack: 'input',
        data: pharmacyData,
        itemStyle: { color: '#52c41a' },
      },
      {
        name: '录入总数',
        type: 'line',
        smooth: true,
        data: totalData,
        itemStyle: { color: '#722ed1' },
      },
    ],
  });
  await nextTick();
  resize();
}

watch(() => props.data, renderChart, { deep: true, immediate: true });
</script>

<template>
  <EchartsUI ref="chartRef" class="dashboard-chart" />
</template>

<style scoped>
.dashboard-chart {
  width: 100%;
  height: 360px;
}
</style>
