<template>
  <div class="horizontal-bar-chart">
    <h3 class="chart-title">{{ title }}</h3>
    <chartsCard
      :option="chartOption"
      :width="width"
      :height="height"
      @chart-ready="handleChartReady"
    />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import chartsCard from './chartsCard.vue'

const props = defineProps({
  title: {
    type: String,
    default: '拜访人均分布情况'
  },
  data: {
    type: Array,
    required: true
    // 数据格式示例：
    // [
    //   { name: '业务员1', value: 78, color: '#fcd36e' },
    //   { name: '业务员2', value: 68, color: '#f28b8b' },
    //   { name: '业务员3', value: 50, color: '#a491f2' },
    //   { name: '业务员4', value: 42, color: '#fbbc58' },
    //   { name: '业务员5', value: 32, color: '#7ecb5c' },
    //   { name: '业务员6', value: 30, color: '#68c0cf' },
    //   { name: '业务员7', value: 28, color: '#66b1fc' },
    // ]
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  }
})
const colors = [
  '#fcd36e', // 暖黄
  '#f28b8b', // 暖红
  '#a491f2', // 浅紫
  '#fbbc58', // 橘黄
  '#7ecb5c', // 草绿
  '#68c0cf', // 青蓝
  '#66b1fc', // 浅蓝
  '#d670d6', // 粉紫
  '#ffd700', // 金黄
  '#00ced1' // 青碧
]
const sortedData = computed(() => {
  return [...props.data].sort((a, b) => b.value - a.value)
})

const chartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{b} : {c}' // 格式化提示内容，显示名称和数值
  },
  grid: {
    left: '60px', // 左侧留出空间显示业务员名称
    right: '40px',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    // min: 0, // 最小值
    max: (value: any) => (sortedData.value.length > 0 ? sortedData.value[0].value * 1.2 : 0),
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      color: '#666'
    },
    splitLine: {
      lineStyle: {
        color: '#eee'
      }
    }
  },
  yAxis: {
    type: 'category',
    data: props.data.map((item) => item.name),
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      color: '#333',
      fontSize: 14
    }
  },
  series: [
    {
      name: '拜访人均分布',
      type: 'bar',
      barCategoryGap: '10%', // 柱子之间的间距
      barWidth: 20, // 柱子宽度
      data: props.data.map((item) => item.value),
      itemStyle: {
        color: (params: { dataIndex: number }) => {
          const item = props.data[params.dataIndex]
          return item.color || colors[params.dataIndex % colors.length]
        },
        borderRadius: [0, 6, 6, 0] // 仅右侧圆角，适配横向柱状图
      },
      label: {
        show: true,
        position: 'right', // 数值显示在柱子右侧
        color: '#333',
        fontSize: 12
      }
    }
  ]
}))

const handleChartReady = (chart: any) => {
  // 可在此处对图表进行更多自定义操作，如监听事件等
}
</script>

<style scoped lang="scss">
.horizontal-bar-chart {
  .chart-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    color: '#333';
  }
}
</style>
