<script setup>
import {useCpuUsage} from "src/utils/system/cpu";
import {computed, onMounted, reactive, ref, watch} from "vue";
import * as echarts from "echarts";
import moment from "moment";
const props = defineProps({
    showLabel: {
        type:Boolean,
        default: true,
    },
    label: {
        type: String,
        default: "CPU使用率",
    },
    labelPosition :{
        type: String,
        default: "center",
    },
    labelStyle: {
        type: Object,
        default: {
            fontSize: 14
        }
    },
    maxStep:{
        type: Number,
        default: 600
    }
})
const cpuUsage = useCpuUsage()
const singleUsage = computed(()=>{
    return Number((cpuUsage.value[0] || 0).toFixed(2))
})
const colors = [
    { color: '#f56c6c', percentage: 100 },
    { color: '#e6a23c', percentage: 80 },
    { color: '#5cb87a', percentage: 30 },
]

const chartRef = ref()
const chart = reactive({
    title: {
        left: props.labelPosition,
        text: props.label,
        textStyle: props.labelStyle
    },
    tooltip: {
        trigger: 'axis',
        formatter:  (params)=> {
            params = params[0];
            return `
                <div>${params.value[0]}</div>
                 <div class="text-center">${params.value[1]}%</div>
                `;
        },
        axisPointer: {
            animation: false
        }
    },
    xAxis: {
        type: 'category',
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        splitLine: {
            show: false
        },
        min: 0,
        max: 100
    },
    visualMap: {
        show: false,
        pieces: [
            {
                gte: 0,
                lte: 30,
                color: '#5cb87a'
            },
            {
                gt: 30,
                lte: 80,
                color: '#e6a23c'
            },
            {
                gt: 80,
                lte: 100,
                color: '#f56c6c'
            },
        ]
    },
    series: [
        {
            name: 'CPU使用率',
            type: 'line',
            showSymbol: false,
            data: [],
            areaStyle: {
                origin: 'start'
            }
        }
    ]
})

onMounted(()=>{
    const chartInst = echarts.init(chartRef.value)
    chartInst.setOption(chart)
    chartInst.resize()

    watch(singleUsage,(v)=>{
        let data = chart.series[0].data
        data.push({
            name: moment().format("HH:mm:ss"),
            value: [moment().format("HH:mm:ss"), v]
        })
        if(data.length > props.maxStep){
            data.splice(0,1)
        }
        chartInst.setOption(chart)
    })
    window.addEventListener("resize",()=>{
        chartInst.resize()
    })
})

</script>

<template>
    <div ref="chartRef" class="w-full h-full"></div>
</template>

<style scoped>
.percentage-value {
    font-size: 18px;
}
.percentage-text {
    font-size: 14px;
}
</style>
