<script setup lang="ts">
import { $font_color } from '@/styles/variate'
import * as echarts from 'echarts'

const props = withDefaults(
  defineProps<{
    data: {
      xData: string[]
      seriesVal: anyObj[]
    }
    title?: string
    yName?: string
  }>(),
  {},
)

const emit = defineEmits(['handleBarClick'])

const widthRate = window.screen.width / 1920

const chartContainer = ref<HTMLDivElement | null>(null)

let myChart = reactive<anyObj>({})

const option = reactive<anyObj>({
  title: {
    text: '',
    textStyle: {
      color: $font_color,
      fontSize: widthRate * 28,
      fontWeight: 'normal',
    },
    top: 0,
    left: 'center',
  },
  xAxis: {
    data: [],
    axisLabel: {
      show: true,
      textStyle: {
        fontSize: widthRate * 22, // 修改字体大小
        color: $font_color,
      },
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: '#8A94FD70',
        width: widthRate * 4,
      },
    },
  },
  yAxis: {
    type: 'value',
    minInterval: 1,
    // name: '（人）',
    nameLocation: 'end',
    // nameGap: widthRate * -35,
    nameTextStyle: {
      color: $font_color,
      fontSize: widthRate * 22,
    },
    axisLabel: {
      show: true,
      textStyle: {
        fontSize: widthRate * 22, // 修改字体大小
        color: $font_color,
      },
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: 'rgba(138, 148, 253, 0.25)',
        width: widthRate * 4,
      },
    },
    splitLine: {
      lineStyle: {
        type: [5, 10],
        color: 'rgba(138, 148, 253, 0.25)',
        width: 2,
      },
    },
  },
  series: {
    data: [],
    type: 'bar',
    barMaxWidth: widthRate * 80,
    label: {
      show: true,
      position: 'top',
      fontSize: widthRate * 20,
      color: $font_color,
    },
  },
})

async function drawGraph() {
  await nextTick()
  if (myChart) {
    myChart.dispose?.()
    myChart = echarts.init(chartContainer.value)
  }

  option.xAxis.data = props.data?.xData
  option.series.data = props.data?.seriesVal
  option.title.text = props.title
  option.yAxis.name = props.yName || ''
  myChart.setOption(option)
  myChart.off('click').on('click', async (params: anyObj) => {
    emit('handleBarClick', params)
  })
  myChart.resize()
}

onMounted(() => {
  drawGraph()
})
defineExpose({ drawGraph })
</script>
<template>
  <div ref="chartContainer" class="echarts-bar"></div>
</template>
<style scoped lang="scss">
.echarts-bar {
  width: 100%;
  height: 100%;
}
</style>
