<template>
    <div ref='chartRef' class='my-chart' />
</template>
<script setup lang='ts'>
import * as echarts from 'echarts' // 全引入
import { color, gradeColor3 } from './color'
import { useConfig } from '@/stores/config'
import { defineExpose, onBeforeUnmount, onMounted, ref, watch } from 'vue'

const config = useConfig()
color[0] = config.layout.elementUiPrimary[0]
const chartRef = ref<HTMLDivElement>()

const props = defineProps(['options'])
let chart: echarts.ECharts | any = null
let throttle: ReturnType<typeof setTimeout>

const resizeHandler = () => {
    // 不在视野中的时候不进行resize
    if (!chartRef.value) return
    if (chartRef.value.offsetHeight == 0) return
    chart.getZr().painter.getViewportRoot().style.display = 'none'
    requestAnimationFrame(() => {
        chart.resize()
        chart.getZr().painter.getViewportRoot().style.display = ''
    })
}

const initChart = () => {
    chart?.dispose()
    chart = echarts.init(chartRef.value as HTMLDivElement)
    const options = {
        title: {
            left: 'center',
            textStyle: {
                color: '#000',
                fontSize: 18
            },
            ...(props.options?.title || null)
        },
        radar: props.options?.radar,
        tooltip: props.options?.tooltip,
        legend: {
            right: 20,
            top: 0,
            itemGap: 10,
            itemStyle: {},
            textStyle: {
                fontSize: 12,
                padding: [2, 0, 0, 0] //[上、右、下、左]
            },
            itemWidth: 15,
            itemHeight: 10,
            ...(props.options?.legend || null)
        },

        color: props.options?.color || color,
        series: props.options?.series,
        ...props.options?.options
    }
    // 处理柱状图
    chart.setOption(options)
    setTimeout(() => {
        chart.resize()
    }, 0)
}


// 动态计算table高度
const resizeObserver = new ResizeObserver(entries => {
    for (const entry of entries) {
        if (throttle) {
            clearTimeout(throttle)
        }
        throttle = setTimeout(() => {
            resizeHandler()
        }, 100)
    }
})
onMounted(() => {
    initChart()
    resizeObserver.observe(chartRef.value!)
})
defineExpose({ initChart })
onBeforeUnmount(() => {
    resizeObserver.unobserve(chartRef.value!)
    chart?.dispose()
})
watch(
    () => props.options,
    (newVal, oldVal) => {
        initChart()
    }
)


</script>

<style lang='scss' scoped>
.my-chart {
    height: 100%;
    width: 100%;
}
</style>
