<template>
  <div class="traffic-flow" :id="id" />
</template>

<script setup>
  import { fitChartSize } from '@/utils/dataUtil'
  import { useEchart } from '@/hooks/echart'

  const { id, setOption } = useEchart()

  let props = defineProps({
    list: {
      type: Array,
      default: () => []
    }
  })

  watch(
    () => props.list,
    (val) => {
      if (val.length) {
        setTimeout(() => {
          init()
        }, 1000)
      }
    },
    {
      immediate: true
    }
  )
  let params = null

  const getXAxisData = () => {
    return props.list.map((item) => item.name)
  }
  const getSeriesData = () => {
    return props.list.map((item) => item.value)
  }
  const init = () => {
    if (!params) {
      params = {
        grid: {
          left: '4%',
          right: '4%',
          top: '10%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          boundaryGap: true,
          type: 'category',
          data: getXAxisData(),
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(5, 72, 134, 1)'
            }
          },
          axisLabel: {
            fontSize: fitChartSize(12),
            color: 'rgba(255,255,255,0.9)'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            fontSize: fitChartSize(12),
            color: 'rgba(255,255,255,0.9)'
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'rgba(0, 150, 255,0.4)',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            type: 'bar',
            showBackground: true,
            barWidth: fitChartSize(16),
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(0, 99, 255, 1)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(2, 249, 250, 1)'
                  }
                ]
              }
            },
            backgroundStyle: {
              color: 'rgba(0, 150, 255, 0.15)'
            },
            data: getSeriesData()
          }
        ]
      }
    } else {
      params.xAxis.data = getXAxisData()
      params.series[0].data = getSeriesData()
    }
    setOption(params)
  }

  onMounted(() => {
    init()
  })
</script>

<style scoped lang="scss">
  .traffic-flow {
    width: vw(260);
    height: vh(300);
  }
</style>
