<script setup>
import { defineProps, onMounted, onUnmounted, ref, nextTick, watch } from 'vue'
import { uuid } from 'vue-uuid'
import * as echarts from 'echarts';
// 引入静态文件
import echartNoData from '@/assets/images/echartsNoData.png'

const props = defineProps({
  timerDate: {
    type: Number,
    default: 0
  },
  options: {
    type: Object,
    default: () => ({})
  },
  echartHeight: {
    type: Number,
    default: 155
  },
  isShowNo: {
    type: Boolean,
    default: false
  }
})

const isShowNoData = ref(false)
const echartRef = ref(null)
echartRef.value = uuid.v1().replace(/-/g, '')

let BarChart = null

// 初始化图表
const initEchart = () => {
  BarChart = echarts.init(echartRef.value)
  setOptions()
}

// 挂在窗口变化事件
const windowResize = () => {
  window.addEventListener('resize', resizeEvent)
}

// 使用requestAnimationFrame监听浏览器窗口变化
const resizeEvent = () => {
  window.requestAnimationFrame(() => {
    BarChart.resize()
  })
}
// 设置图表
const setOptions = () => {
  setTimeout(() => {
    BarChart.setOption(props.options)
  }, 300)
  nextTick()
}
// timerDate改变 重新渲染echarts
watch(() => props.timerDate, (newValue) => {
  initEchart()
},{
  deep: true
})
watch(() => props.options, (newValue) => {
  initEchart()
},{
  deep: true
})

// timerDate改变 重新渲染echarts
watch(() => props.isShowNo, (newValue) => {
  isShowNoData.value = newValue
})

// 渲染完成
onMounted(() => {
  nextTick(() => {
    initEchart()
    windowResize()
  })
})

// 被卸载
onUnmounted(() => {
  // 移除窗口变化事件
  window.removeEventListener('resize', resizeEvent)
  // 清空图表实例
  BarChart.dispose()
  BarChart = null
})
</script>

<template>
  <div class="videoEchartsBox">
    <div class="echartBox">
      <div ref="echartRef" class="echartContent" :style="{ height: echartHeight + 'px' }"></div>
      <div v-if="isShowNoData" class="echartsNoData">
        <img :src="echartNoData"/>
        <p>暂无数据</p>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.videoEchartsBox{
  margin-top: 10px;
  .echartBox{
    position: relative;
    width: 100%;
    .echartsNoData{
      width: 100%;
      height: 100%;
      position: absolute;
      top: 20px;
      text-align: center;
      background-color: #0e233b;
      z-index: 2;
      img{
        width: 30%;
        margin-top: 60px;
      }
      p{
        font-size: 14px;
        color: #ffffff;
      }
    }
    .echartContent{
      width: 100%;
    }
  }
}
</style>
