<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';

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

import { Card, Empty, Statistic } from 'ant-design-vue';

import type { SalespersonDashboardRegionItem } from '../api';

const props = defineProps<{
  /** 来自 dashboardData.region_stats：按角色维度（省/市）聚合的录入分布 */
  data: SalespersonDashboardRegionItem[];
}>();

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

/** 无数据时展示空态 */
const showEmpty = computed(() => !props.data.length);
/** 市经理仅一条本市数据时展示 Statistic 卡片 */
const isSingleCity = computed(() => props.data.length === 1);
/** 多地区时展示横向柱状图（用 v-show 保持 ECharts 实例，避免切换时间段后组件丢失） */
const showChart = computed(() => props.data.length > 1);

/** 多地区横向柱状图：Y 轴地区名，X 轴录入总数 */
async function renderChart() {
  if (!showChart.value) return;

  const names = props.data.map((item) => item.region_name);
  const counts = props.data.map((item) => item.input_count);

  // 等待 v-show 切换完成后再渲染，避免 chartRef 尚未挂载
  await nextTick();
  await renderEcharts({
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '8%', bottom: '3%', containLabel: true },
    xAxis: { type: 'value', minInterval: 1 },
    yAxis: {
      type: 'category',
      data: names,
      inverse: true,
    },
    series: [
      {
        type: 'bar',
        data: counts,
        itemStyle: { color: '#13c2c2' },
        label: { show: true, position: 'right' },
      },
    ],
  });
  await nextTick();
  resize();
}

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

<template>
  <Empty
    v-if="showEmpty"
    class="region-empty"
    description="暂无地区录入数据"
  />
  <div v-else-if="isSingleCity" class="region-single">
    <Card size="small" class="region-single__card">
      <Statistic
        :title="data[0]?.region_name || '本市'"
        :value="data[0]?.input_count || 0"
        suffix="家录入"
      />
      <div class="region-single__sub">
        诊所 {{ data[0]?.clinic_count || 0 }} 家 · 药店 {{ data[0]?.pharmacy_count || 0 }} 家
      </div>
    </Card>
  </div>
  <!-- 始终挂载图表容器，用 v-show 控制显隐，防止时间段切换时 v-if 销毁 ECharts -->
  <EchartsUI v-show="showChart" ref="chartRef" class="dashboard-chart" />
</template>

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

.region-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 320px;
}

.region-single {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 320px;
}

.region-single__card {
  min-width: 240px;
  text-align: center;
}

.region-single__sub {
  margin-top: 8px;
  font-size: 13px;
  color: #86909c;
}
</style>
