<template>
    <div class="echart" :style="{ width: width, height: height }">
        <div ref="chartElement" class="echart__container"></div>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, PropType, watch, watchEffect } from 'vue';
import { EChartsOption } from 'echarts';
import { useEchart } from './setup';

export default defineComponent({
    name: 'Echart',
    props: {
        // 图表宽度
        width: {
            type: String,
            default: '100%',
        },
        // 图表高度
        height: {
            type: String,
            default: '100%',
        },
        // 图表配置项
        options: {
            type: Object as PropType<EChartsOption>,
            required: true,
        },
        loading: {
            type: Boolean,
            default: true,
        },
    },
    setup(props, context) {
        // 图表容器元素
        const chartElement = ref<HTMLElement>();

        onMounted(() => {
            const { echart, setOptions, showLoading } = useEchart(chartElement.value!, context);

            watchEffect(() => {
                if (props.loading) {
                    echart.clear();
                    showLoading(true);
                }
            });

            watch(
                () => props.options,
                (option) => {
                    // 设置图表配置项
                    setOptions(option);
                }
            );
        });

        return {
            chartElement,
        };
    },
});
</script>

<style lang="less">
.echart {
    position: relative;
    overflow: hidden;

    &__container {
        width: 100%;
        height: 100%;
    }
}
</style>