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

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

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

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

//处理数据
const setDataFormat = () => {
    let series = [], lables = [], data = datas.value;
    if (isMonths.value) {
        for (let i = 1; i < 13; i++) {
            lables = [...lables, i + '月']
        }
    } else {
        lables = xAxis.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: '20px',
            left: '0',
            right: '4px',
            bottom: '0',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: lables,
            }
        ],
        yAxis: [{
            type: 'value',
            axisLabel: {
                formatter: '{value}' + units.value
            },
        }],
        series: series
    }
}

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