<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: () => ([])
    },
    datas: {
        type: Array,
        default: () => ([])
    },
    lables: {
        type: Array,
        default: () => ([])
    },
    isMonth: {
        type: Boolean,
        default: false
    },
})

//初始变量
const setOption = ref({})
const colors = ref(props.color)
const datas = ref(props.datas)
const isMonths = ref(props.isMonth)
const xAxis = ref(props.lables)


watch(() => [
    props.color,
    props.isMonth,
    props.lables,
], ([color, isMonth, lables]) => {
    colors.value = color
    isMonths.value = isMonth
    xAxis.value = lables
    setOptions()
})


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

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

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

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