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

<script setup>
import * as echarts from 'echarts'
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
const props = defineProps({
    datas: {
        type: Object,
        default: () => ({})
    },
    config: {
        type: Object,
        default: () => ({})
    },
})

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

//监听
watch(() => [
    props.datas
], ([data]) => {
    datas.value = data
    setDatas(data)
})

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

//设置数据
const setDatas = (data) => {
    let AxisData = [];
    const {name, key} = props.config;
    for (let i = 0; i < name.length; i++) {
        AxisData.push({
            name: name[i],
            value: data[key[i]]
        })
    }
    setOptions(AxisData)
}

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

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

//设置图表
const setOptions = (AxisData) => {
    const {color, label} = props.config;
    chart.setOption({
        color: color,
        tooltip: {
            trigger: 'item'
        },
        series: [
            {
                name: label,
                type: 'pie',
                radius: ['50%', '80%'],
                center: ["50%", "50%"],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 5,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                data: AxisData
            }
        ]
    })
}

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

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

const onResize = () => {
    nextTick(() => {
        chart.resize();
    })
}

// 暴露出去
defineExpose({
    onResize
})
</script>

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