<template>
    <echartsBase :option="setOption"/>
</template>

<script setup>
import echartsBase from './index.vue'
import { nextTick, onMounted, ref, watch } from 'vue'

const props = defineProps({
    color: {
        type: Array,
        default: () => (['#5087EC', '#68BBC4'])
    },
    unit: {
        type: String,
        default: '元'
    },
    datas: {
        type: Array,
        default: () => ([])
    },
})

//初始变量
const setOption = ref({})
const colors = ref(props.color)
const units = ref(props.unit)
const datas = ref(props.datas)

watch(() => [
    props.color,
    props.unit,
], ([color, unit]) => {
    colors.value = color
    units.value = unit
    setOptions()
})

//深度监听数据变化
watch(() => [
    props.datas,
], ([data]) => {
    datas.value = data
    setDataFormat()
}, { deep: true })

//处理数据
const setDataFormat = () => {
    let series = [], lables = [], data = datas.value;
    //处理数据
    for (let i = 0; i < data.length; i++) {
        if (data[i].name) {
            lables.push(data[i].name)
            series.push(data[i].value)
        }
    }
    setOptions(lables, series)
}

//设置图表
const setOptions = (lables = [], series = []) => {
    setOption.value = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            top: '20px',
            left: '0',
            right: '4px',
            bottom: '0',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: lables,
            }
        ],
        yAxis: [{
            type: 'value',
            axisLabel: {
                formatter: '{value}' + units.value
            },
        }],
        series: [
            {
                data: series,
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }
        ]
    }
}

//渲染完成
onMounted(() => {
    nextTick(() => {
        setDataFormat()
    })
})
</script>
