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

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

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

const props = defineProps<{
  /** 本周期 trend，用于环比柱状图「本周期」系列 */
  current: SalespersonDashboardTrendItem[];
  /** 上一等长周期 compare_trend，用于「上周期」系列 */
  previous: SalespersonDashboardTrendItem[];
}>();

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

const maxLen = computed(() => Math.max(props.current.length, props.previous.length));

function resolveInputTotal(item: SalespersonDashboardTrendItem) {
  return item.input_total ?? item.clinic_count + item.pharmacy_count;
}

/** 按序号对齐本周期与上周期录入总数，tooltip 展示真实时间标签 */
async function renderChart() {
  const labels = Array.from({ length: maxLen.value }, (_, i) => `T${i + 1}`);
  const currentData = props.current.map((item) => resolveInputTotal(item));
  const previousData = props.previous.map((item) => resolveInputTotal(item));

  await renderEcharts({
    tooltip: {
      trigger: 'axis',
      formatter(params: any) {
        const list = Array.isArray(params) ? params : [params];
        const idx = list[0]?.dataIndex ?? 0;
        const cur = props.current[idx];
        const prev = props.previous[idx];
        const lines = [`序号 ${idx + 1}`];
        if (cur) lines.push(`本周期 ${cur.label}：${resolveInputTotal(cur)} 家`);
        if (prev) lines.push(`上周期 ${prev.label}：${resolveInputTotal(prev)} 家`);
        return lines.join('<br/>');
      },
    },
    legend: { data: ['本周期录入', '上周期录入'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: labels },
    yAxis: { type: 'value', name: '录入数(家)', minInterval: 1 },
    series: [
      {
        name: '本周期录入',
        type: 'bar',
        data: currentData,
        itemStyle: { color: '#1677ff' },
      },
      {
        name: '上周期录入',
        type: 'bar',
        data: previousData,
        itemStyle: { color: '#bfbfbf' },
      },
    ],
  });
  await nextTick();
  resize();
}

watch([() => props.current, () => props.previous], renderChart, { deep: true, immediate: true });
</script>

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

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