<template>
    <div ref="chart" :style="{ height: height }"></div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
    used: Number,
    total: Number,
    height: { type: String, default: '120px' }
})

const chart = ref(null)
let chartInstance = null
const colorMap = {
    used: '#f56c6c',
    free: '#e4e7ed'
}

const initChart = () => {
    chartInstance = echarts.init(chart.value)

    const option = {
        tooltip: {
            formatter: `{a}<br/>{b}: {c}GB ({d}%)`
        },
        series: [{
            name: '磁盘使用',
            type: 'pie',
            radius: ['65%', '80%'],
            avoidLabelOverlap: false,
            label: {
                show: false
            },
            data: [
                { value: props.used.toFixed(2), name: '已使用' },
                { value: (props.total - props.used).toFixed(2), name: '可用' }
            ],
            itemStyle: {
                color: (params) => params.dataIndex === 0 ? colorMap.used : colorMap.free
            }
        }]
    }

    chartInstance.setOption(option)
}

watch(() => [props.used, props.total], () => {
    if (chartInstance) {
        chartInstance.setOption({
            series: [{
                data: [
                    { value: props.used, name: '已使用' },
                    { value: props.total - props.used, name: '可用' }
                ],
                itemStyle: {
                    color: (params) => params.dataIndex === 0 ? colorMap.used : colorMap.free
                }
            }]
        })
    }
})

onMounted(initChart)
onBeforeUnmount(() => chartInstance?.dispose())
</script>