<template>
    <div ref="chartElement" class="echart" :style="{ width: width, height: height }">
        <template v-if="empty">
            <div class="echart__empty">暂无数据</div>
        </template>
        <template v-else>
            <div class="echart__container" v-for="i in options.length" :key="i"></div>
        </template>
    </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: Array as PropType<EChartsOption[]>,
            default: [],
        },
        loading: {
            type: Boolean,
            default: true,
        },
        empty: {
            type: Boolean,
            default: false,
        },
    },
    setup(props) {
        // 图表容器元素
        const chartElement = ref<HTMLElement>();

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

            watchEffect(() => {
                showLoading(props.loading);
            });

            watch(
                () => props.options,
                (val) => {
                    if (!props.loading && !props.empty) {
                        // 设置图表配置项
                        setOptions(val);
                    }
                }
            );
        });

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

<style lang="less">
@import './index.less';
</style>