<template>
  <Box title="稻虾流向（吨）">
    <div class="h-full flex flex-col">
      <div class="flex-1" ref="chartRef"> </div>
    </div>
  </Box>
</template>

<script lang="ts">
  import { defineComponent, reactive, ref, Ref, onBeforeMount, watch, onBeforeUnmount } from 'vue'
  import Box from './Box.vue'
  import { useECharts } from '/@/hooks/web/useECharts'
  import { getRiceShrimpFlow } from '/@/api/sys/other'
  import { useVisualizationStore } from '/@/store/modules/visualization'
  import { chartLineColors } from './colors'
  import { useVContext } from '../useVContext'
  export default defineComponent({
    components: {
      Box,
    },
    setup() {
      const { rootEmitter } = useVContext()
      const Data = reactive({
        x_axis: [],
        series: [],
      })

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

      const visualizationStore = useVisualizationStore()

      const { setOptions, getInstance } = useECharts(chartRef as Ref<HTMLDivElement>)

      async function getData(init = true) {
        const resData = await getRiceShrimpFlow({
          year: visualizationStore.getYear,
        })
        Data.x_axis = resData.x_axis
        Data.series = resData.series

        if (init) {
          chartsInit()
        } else {
          chartLineAmi()
        }
      }

      let legendData = [] as any

      function formatChartData() {
        const obj = {
          legendData: [] as any,
          series: [] as any,
        }

        Data.series.forEach(({ name, data }, index) => {
          const color = chartLineColors[index % chartLineColors.length]
          obj.legendData.push(name + '')
          obj.series.push({
            name: name,
            data: data,
            type: 'line',
            smooth: false,
            // symbol: 'none',
            stack: 'Total',
            itemStyle: {
              color: color.itemColor,
            },
            areaStyle: {
              color: color.areaColor,
            },
          })
        })
        legendData = obj.legendData
        return obj
      }

      const chartsInit = () => {
        const obj = formatChartData()
        setOptions({
          grid: { left: '2%', right: '20px', top: '10%', bottom: '2%', containLabel: true },
          legend: {
            data: obj.legendData,
            top: '0%',
            right: '0',
            textStyle: {
              color: '#ffffff',
            },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              lineStyle: {
                width: 1,
                color: '#019680',
              },
            },
          },
          xAxis: {
            type: 'category',
            data: Data.x_axis,
            boundaryGap: false,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: '#fff',
            },
          },
          yAxis: [
            {
              type: 'value',
              axisTick: {
                show: false,
              },
              splitLine: {
                lineStyle: {
                  type: 'solid',
                  color: '#8EEEFF',
                  opacity: 0.3,
                },
              },
              axisLabel: {
                color: '#fff',
              },
            },
          ],
          series: obj.series,
          animationDuration: 2000,
        })

        chartAmi()
      }

      let timer: any = null

      function chartAmi() {
        let index = 0
        const timerNumber = 3000
        timer && clearInterval(timer)
        let currentIndex = 0
        let sleep = 0
        const fo = 2
        timer = setInterval(() => {
          currentIndex = index % 4
          sleep = index % (4 * fo)
          getInstance()?.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: currentIndex,
          })
          if (sleep + 1 >= 4 * fo) {
            timer && clearInterval(timer)
            setTimeout(() => {
              getInstance()?.dispatchAction({
                type: 'hideTip',
              })
            }, timerNumber)
            getData(false)
          }
          index++
        }, timerNumber)
      }

      function chartLineAmi() {
        const obj = formatChartData()
        let index = 0
        let currentIndex = 0
        const timerNumber = 3000
        timer && clearInterval(timer)
        timer = setInterval(() => {
          currentIndex = index % legendData.length
          if (currentIndex == 0) {
            legendData.forEach((_, index) => {
              getInstance()?.dispatchAction({
                type: 'legendUnSelect',
                name: legendData[index],
              })
            })
          }
          getInstance()?.setOption({
            series: [obj.series[currentIndex]],
          })
          getInstance()?.dispatchAction({
            type: 'legendSelect',
            name: legendData[currentIndex],
          })
          if (currentIndex == legendData.length - 1) {
            timer && clearInterval(timer)
            setTimeout(() => {
              chartAmi()
            }, timerNumber)
          }

          index++
        }, timerNumber)
      }

      onBeforeMount(() => {
        getData()

        rootEmitter.on('interval:auto', () => {
          // getData()
        })
      })

      onBeforeUnmount(() => {
        timer && clearInterval(timer)
      })

      watch(
        () => visualizationStore.getYear,
        () => getData(),
      )

      return {
        chartRef,
      }
    },
  })
</script>

<style scoped lang="less">
  .active {
    @apply font-bold text-15px text-[#76E9F0];
  }
</style>
