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

<script setup>
import * as echarts from 'echarts'
import {useAppStore} from "~src/store";
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
const props = defineProps({
    ratio: {
        type: [Number,String],
        default: 0
    }
})

//初始变量
let chart = null;
const echart = ref(null)
const useAppState = useAppStore()
const AppColor = ref(useAppState.getColor);

watch(() => [
    props.ratio
], ([ratio]) => {
    setOptions(ratio, 100 - ratio)
})

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

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

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

//设置图表
const setOptions = (val1,val2) => {
    nextTick(() => {
        chart.setOption({
            tooltip: {
                trigger: "item",
                formatter: "{d}%"
            },
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    radius: ['100%', '70%'],
                    center: ["50%", "50%"],
                    label: {
                        show: false,
                        position: "center",
                    },
                    labelLine: {
                        show: false,
                    },
                    data: [
                        {
                            value: val1,
                            name: "完成率",
                            itemStyle: {
                                color: AppColor.value?.color ?? "#0081ff",
                            }
                        },
                        {
                            value: val2,
                            name: "",
                            itemStyle: {
                                color: "#D4DDE9",
                            }
                        },
                    ]
                }
            ]
        })
    })
}

//渲染完成
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>
.RoundChart-box {
    display: block;
    height: 100%;
    overflow: hidden;
    position: relative;
    .RoundChart-echarts {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 2;
        width: 100%;
        height: 100%;
    }
}
</style>
