<!--
  资产分布图组件
  展示按机构、类型的资产分布
-->

<template>
  <div class="asset-distribution-chart">
    <BarChart
      :data="chartData"
      title="资产分布统计"
      type="vertical"
      :x-axis-label="xLabel"
      y-axis-label="数量"
      :show-data-zoom="chartData.length > 10"
      height="400px"
      @click="handleClick"
    />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import BarChart from '../BarChart.vue'
import type { AssetDistributionStatistics, AssetTypeStatistics } from '@/types/charts'

/** Props */
interface Props {
  data: Array<AssetDistributionStatistics | AssetTypeStatistics>
  type?: 'organization' | 'deviceType'
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  type: 'organization',
  loading: false,
})

/** Emits */
interface Emits {
  (e: 'click', item: any): void
}

const emit = defineEmits<Emits>()

/** X轴标签 */
const xLabel = computed(() => {
  return props.type === 'organization' ? '机构' : '设备类型'
})

/** 图表数据 */
const chartData = computed(() => {
  return props.data.map(item => {
    const name = props.type === 'organization'
      ? (item as AssetDistributionStatistics).organizationName
      : (item as AssetTypeStatistics).typeName

    return {
      name: name || '未知',
      value: item.count,
      original: item,
    }
  }).sort((a, b) => b.value - a.value)
})

/** 处理点击 */
const handleClick = (item: any) => {
  emit('click', item.original)
}
</script>

<style scoped lang="scss">
.asset-distribution-chart {
  width: 100%;
  height: 100%;
}
</style>
