<template>
    <div class="BarChart-box">
        <div ref="echart" class="BarChart-echarts" :style="`width : ${chart?.clientWidth}px`"/>
    </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'

//初始变量
let chart = null;
const echart = ref(null)

//初始化图表
const initChart = () => {
    chart = echarts.init(echart.value)
    setOptions()
}

//监听浏览器窗口变化
const windowResize = () => {
    window.addEventListener("resize", resizeEvent);
}

const resizeEvent = () => {
    window.requestAnimationFrame(() => {
        chart.resize();
    })
}

//设置图表
const setOptions = () => {
    chart.setOption({
        color: ['#4094C2', '#6DC8E1'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['内业', '外业']
        },
        xAxis: [
            {
                type: 'category',
                data: ['名称1', '名称2', '名称3', '名称4', '名称5', '名称6', '名称7'],
                axisLabel: { interval: 0, rotate: 30 }
            }
        ],
        yAxis: [
            {
                type: 'value',
                interval: 30,
                axisLabel: {
                    formatter: '{value}%'
                }
            }
        ],
        series: [
            {
                name: '内业',
                type: 'bar',
                stack: '名称1',
                data: [320, 332, 301, 334, 390, 330, 320],
                tooltip: {
                    valueFormatter(value) {
                        return value + '%';
                    }
                },
            },
            {
                name: '外业',
                type: 'bar',
                stack: '名称1',
                data: [120, 132, 101, 134, 90, 230, 210],
                tooltip: {
                    valueFormatter(value) {
                        return value + '%';
                    }
                },
            }
        ],
    })
}

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

//被卸载
onUnmounted(() => {
    window.removeEventListener("resize",resizeEvent);
    chart.dispose()
    chart = null
})
</script>

<style lang="scss" scoped>
.BarChart-box {
    height: 100%;
    overflow: hidden;
    position: relative;
    .BarChart-echarts {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 2;
        width: 100%;
        height: 100%;
    }
}
</style>
