<template>
    <div class="container-echart">
        <div :id="'echart' + timeId" class="interface-echart"></div>
    </div>
</template>
<script lang="ts" setup>
import * as echarts from 'echarts'
import { EChartsType } from 'echarts'
import { onMounted, ref, watch, onBeforeUnmount, nextTick } from 'vue'

const props = defineProps({
    message: {
        type: Array,
        default: true
    }
})

let myEchart: EChartsType
const timeId = ref(Math.floor(new Date().getTime() * Math.random())); // 使该图表保持唯id
const myEchartData = () => {
    const option = {
        title: {
            text: '能源消费总量',
            textStyle: {
                color: 'white' // 设置字体颜色为红色
            }
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['一次能源消费量', '二次能源消费量'],
            textStyle: {
                color: 'white' // 设置字体颜色为红色
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '一次能源消费量',
                type: 'line',
                stack: 'Total',
                data: [320, 302, 301, 334, 390, 330, 320, 301, 334, 390, 330, 320]
            },
            {
                name: '二次能源消费量',
                type: 'line',
                stack: 'Total',
                data: [120, 132, 101, 134, 90, 230, 210, 301, 334, 390, 330, 320]
            }
        ]
    };
    // { notMerge: true } 解决删除数据时,数据不刷新的问题
    myEchart.setOption(option, { notMerge: true })
}
watch(
    //监控数据变化
    () => props.message,
    () => {
        setTimeout(() => {
            myEchartData()
        }, 500)
    },
    { deep: true }
)
onMounted(() => {
    setTimeout(() => {
        const dom = document.getElementById(`echart${timeId.value}`) as any
        myEchart = echarts.init(dom)
        myEchartData()
    }, 500)

    // 当窗口发生变化时
    window.addEventListener('resize', () => {
        myEchart.resize()
    })
})
onBeforeUnmount(() => {
    window.removeEventListener('resize', () => {
        myEchart.resize()
    })
})
</script>
<style scoped lang="scss">
.container-echart {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

.interface-echart {
    width: 100%;
    height: 100%;
}
</style>