<script setup>
import * as echarts from 'echarts'

const props = defineProps({
  data: [],
})

const fsdhztjRef = $ref()

const option = {
  grid: {
    x: 60,
    y: 80,
    x2: 80,
    y2: 60,
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  xAxis: {
    type: 'category',
    axisTick: false,
    name: '分数段\n（分）',
    nameTextStyle: {
      color: '#fff',
      fontSize: '12px',
      verticalAlign: 'top',
      lineHeight: 16,
      padding: [8, 0, 0, -10],
    },
    axisLabel: {
      textStyle: {
        color: '#fff',
        fontSize: '12px',
      },
    },
    axisLine: {
      lineStyle: {
        type: 'solid',
        color: 'rgba(83,198,222,0.24)', // 左边线的颜色
        width: '1', // 坐标线的宽度
      },
    },
    data: ['0~30', '30~60', '60~90', '90~120'],
  },
  yAxis: {
    type: 'value',
    name: '（人）',
    nameTextStyle: {
      color: '#68D5EA',
      fontSize: '14px',
      padding: [0, 0, 15, -40],
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: 'rgba(83,198,222,0.24)',
        width: 1,
        type: 'solid',
      },
    },
    axisLabel: {
      textStyle: {
        color: '#68D5EA',
        fontSize: '16px',
      },
    },
  },
  series: [
    {
      data: [120, 200, 150, 80],
      type: 'bar',
      barWidth: 15,
      color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
        {
          offset: 0,
          color: '#07ba74',
        },
        {
          offset: 1,
          color: '#fedb65',
        },
      ]),
    },
  ],
}
let myChart = null

const allData = ref([])
function initData() {
  const arr1 = []
  const arr2 = []
  allData.value.map((item) => {
    arr1.push(item.name)
    arr2.push(item.value)
  })
  option.xAxis.data = [...arr1]
  option.series[0].data = [...arr2]
  nextTick(() => {
    init()
  })
}

function init() {
  myChart = echarts.init(fsdhztjRef)
  option && myChart.setOption(option)
}

watch(
  () => props.data,
  (newVal, oldVal) => {
    if (newVal) {
      allData.value = newVal
      initData()
    }
  },
  { immediate: true },
)

window.addEventListener('resize', async () => {
  myChart?.resize()
})
</script>

<template>
  <div class="fsdhztjDiv">
    <div ref="fsdhztjRef" class="w-full h-full" />
  </div>
</template>
