<template>
    <div class="es-piechart" ref="pieChart"></div>
</template>

<script>
// 引入基本模板
let echarts = require('echarts/lib/echarts');
// 引入柱状图组件
require('echarts/lib/chart/pie');
// 引入提示框和title组件
require('echarts/lib/component/legend');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
require('echarts/lib/component/legendScroll');
export default {
    name: 'es-piechart',
    props: {
        // 数据源： 元素为对象，例如{value:10, name:'直接访问'}，value为值，name为某个类别
        dataList: {
            type: Array,
            required: true
        },
        // 表格标题
        title: {
            type: String,
            required: false,
            default: ''
        },
        width: {
            type: String,
            default: '100%'
        },
        height: {
            type: String,
            default: '100%'
        }
    },
    mounted() {},
    methods: {
        initPieChart() {
            let self = this;
            // 图表
            let pieChart = echarts.init(self.$refs.pieChart);
            pieChart.clear();
            pieChart.setOption({
                title: {
                    text: self.title,
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                legend: {
                    // 解决title与legend重叠
                    data: self.dataList.map(value => {
                        return value.name;
                    }),
                    type: 'scroll'
                },
                series: [
                    {
                        name: self.title,
                        type: 'pie',
                        radius: '55%',
                        center: ['50%', '60%'],
                        data: self.dataList,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            });
        }
    },
    watch: {
        dataList: {
            handler(value) {
                if (value && value.length > 0) {
                    let self = this;
                    self.$nextTick(() => {
                        self.$refs.pieChart.style.width = self.width;
                        self.$refs.pieChart.style.height = self.height;
                        self.initPieChart();
                    });
                }
            },
            deep: true,
            immediate: true
        }
    }
};
</script>

<style lang="scss" scoped>
.es-piechart {
    width: 100%;
    height: 500px;
    position: relative;
}
</style>
