<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, watch } from 'vue'
const props = defineProps({
    datas: {
        type: Array,
        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 = {image: 0, video: 0};
    for (let i = 0; i < data.length; i++) {
        AxisData.image = data[i].imageAmount
        AxisData.video = data[i].videoAmount
    }
    setOptions(AxisData)
}

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

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

//设置图表
const setOptions = (AxisData) => {
    chart.setOption({
        color: ['#FF8F3E', '#1573FF'],
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center'
        },
        series: [
            {
                name: '图像媒体资料',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ["50%", "55%"],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '40',
                        fontWeight: 'bold'
                    }
                },
                data: [
                    { value: AxisData.image, name: '图片' },
                    { value: AxisData.video, name: '视频' },
                ]
            }
        ]
    })
}

//渲染完成
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>
.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>
