<template>
    <div ref="chartRef" style="width: 100%; height: 80vh;"></div>
</template>
   
<script setup>
// import { onMounted, onBeforeUnmount, ref } from 'vue';
import {
    ref,
    onMounted,
    onDeactivated,
    onBeforeUnmount,
} from "vue";

import * as echarts from 'echarts';
import { getOutputValueData } from "@/api/buscmonitoring/index";
const chartRef = ref(null);
const chartInstance = ref(null);

// 重新窗口变化时，重新计算
const resize = () => {
    chartInstance.value && chartInstance.value.resize();
};

const fetchData = async () => {
    try {
        const response = await getOutputValueData().then(res => { return res.data })
        const namesArray = response.map(obj => obj.detailedUnitName);
        const valuesArray = response.map(obj => obj.industrialOutputValue);
        const valuesLastArray = response.map(obj => obj.industrialOutputValueLastYear);

        const options = {
                title: {
                    text: 'World Population'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {},
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: namesArray
                },
                series: [
                    {
                        name: '2011',
                        type: 'bar',
                        data: valuesArray
                    },
                    {
                        name: '2012',
                        type: 'bar',
                        data: valuesLastArray
                    }
                ]
            };

        chartInstance.value.setOption(options);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

onMounted(() => {
    chartInstance.value = echarts.init(chartRef.value);
    fetchData();
    window.addEventListener("resize", resize);
});

// 页面keepAlive时，不监听页面
onDeactivated(() => {
    window.removeEventListener("resize", resize);
});

onBeforeUnmount(() => {
    window.removeEventListener("resize", resize);
});

</script>