<template>
    <div class="chartsbar"></div>
</template>
<!--end-->
<script>
import * as echarts from "echarts";
export default {
    name: 'chartsbar',
    props: ['seriesData', 'eOption'],
    // 数据
    data() {
        return {
            chart: null,
            time: null,
            index: 0
        };
    },
    watch: {
        eOption: {
            deep: true,
            handler() {
                this.updateChartView();
            }
        }
    },
    mounted() {
        this.chart = echarts.init(this.$el);
        this.updateChartView();
        window.addEventListener('resize', this.handleWindowResize);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.handleWindowResize);
        clearInterval(this.time)
    },
    methods: {
        /**
         * 更新echart视图
         */
        updateChartView() {
            clearInterval(this.time)
            if (!this.chart) return;
            this.chart.clear();
            setTimeout(() => {
                this.chart.setOption(this.eOption, true);
                this.index = 0
                let num = 0
                this.seriesData.forEach(item => {
                    num = num + item.value
                })
                let option = JSON.parse(JSON.stringify(this.eOption))
                if (this.time) {
                    return false
                }
                this.time = setInterval(() => {
                    this.index = this.index + 1
                    console.log(this.seriesData.length)
                    if (this.index >= this.seriesData.length) {
                        this.index = 0
                    }
                    let pie = Number(this.seriesData[this.index].value / num * 100).toFixed(0)
                    option.title[0].text = this.seriesData[this.index].name
                    option.title[1].text = pie + '%'
                    this.chart.setOption(option, false);
                }, 5000)
            }, 200);
        },

        /**
         * 当窗口缩放时，echart动态调整自身大小
         */
        handleWindowResize() {
            if (!this.chart) return;
            // clearInterval(this.time)
            this.chart.resize();
        }
    }
};
</script>
<style scope>
.chartsbar {
    width: 100%;
    height: 100%;
}
</style>