<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
    },
    legend: {
        type: Object,
        default:  () => ({})
    },
})

//初始变量
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)
const legendval=ref(props.legend)


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


//深度监听数据变化
watch(() => [
    props.datas,
    props.legend,
,
], ([data,legend]) => {
    datas.value = data
    legendval.value=legend
    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,legendval.value)
}

//设置图表
const setOptions = (lables = [], series = [],legend={}) => {
    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}' + units.value
            },
        }],
        series: series,
        legend:legend
    }
}

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