<template>
    <div ref="chartDom" class="charts"></div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import * as echarts from "echarts";
import { barOption } from "./options/barOption.js";

const props = defineProps({
    styleName: {
        type: String,
        default: "styleName1",
    },
    xData: {
        type: Array,
        default: () => [],
    },
    yData: {
        type: Array,
        default: () => [],
    },
});

const chartDom = ref(null);
const myChart = ref(null);
const options = ref(null);

const initData = () => {
    if (props.styleName === "styleName2") {
        const arr = [];
        props.yData.forEach((item, index) => {
            arr.push({
                value: item.startNum,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: item.startColor,
                        },
                        {
                            offset: 1,
                            color: item.endColor,
                        },
                    ]),
                },
            });
        });
        barOption[props.styleName].series[0].data = arr;
    } else {
        barOption[props.styleName].series[0].data = props.yData;
    }
    barOption[props.styleName].xAxis.data = props.xData;
    
    options.value = barOption[props.styleName];
    myChart.value.setOption(options.value);
};

onMounted(() => {
    myChart.value = echarts.init(chartDom.value);
});

watch(()=>props.xData,(newValue,oldValue) =>{
    if(newValue){
        initData();
    }
})

watch(()=>props.yData,(newValue,oldValue) =>{
    if(newValue){
        initData();
    }
})
</script>

<style lang="scss" scoped>
.charts {
    width: 100%;
    height: 100%;
}
</style>
