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

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

  const { id, setOption } = useEchart()

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

  watch(
    () => props.series,
    (val) => {
      if (val.length) {
        setTimeout(() => {
          init()
        }, 1000)
      }
    },
    { immediate: true }
  )

  let params = null

  const getSeriesData = () => {
    return props.series
  }
  const getXAxisData = () => {
    return props.data
  }
  const init = () => {
    if (!params) {
      params = {
        grid: {
          left: '8%',
          right: '8%',
          top: '10%',
          bottom: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(5, 72, 134, 1)'
            }
          },
          axisLabel: {
            fontSize: fitChartSize(20),
            color: 'rgba(255,255,255,0.9)'
          },
          data: getXAxisData()
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            show: false,
            fontSize: fitChartSize(20),
            color: 'rgba(255,255,255,0.9)'
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'rgba(0, 150, 255,0.4)',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            type: 'bar',
            data: getSeriesData(),
            barWidth: fitChartSize(40),
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              fontSize: fitChartSize(20),
              formatter: (res) => {
                let valueMap = {
                  1: '畅通',
                  2: '缓行',
                  3: '拥堵',
                  4: '严重拥堵'
                }
                return valueMap[res.value]
              }
            },
            itemStyle: {
              color: (res) => {
                let colorMap = {
                  1: '#00c000',
                  2: '#ffa700',
                  3: '#ff0000',
                  4: '#b50000'
                }
                return colorMap[res.value]
              }
            }
          }
        ]
      }
    } else {
      params.xAxis.data = getXAxisData()
      params.series[0].data = getSeriesData()
    }
    setOption(params)
  }
</script>

<style scoped lang="scss">
  .traffic-jam {
    width: 100%;
    height: vh(430);
	margin-top:vh(30);
  }
</style>
