<template>
    <div :id="id" class="ap-chart-ctn"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    name: "ApChart",
    props: {
        options: {
            type: Object,
            required: true
        }
    },
    data() {
        let defaultOption = {
            backgroundColor: 'transparent',
            colors: {
                light: ['#60acfc', '#23c2db', '#63d5b2', '#d4ec59', '#feb64d', '#fa816d', '#d15b7f'], // 浅色(冷色)
                dark: ['#7079df', '#d15b7f', '#fb6e6c', '#ff9f69', '#feb64d', '#ffda43', '#ffe88e'], // 深色(暖色)
            },
            // 折线图
            line: {
                type: 'line',
                name: '折线图',
                smooth: true,
                data: [],
            },
            // 柱状图
            bar: {
                type: 'bar',
                name: '柱状图',
                data: [],
            }
        };
        return {
            id: '',
            chart: null,
            defaultOption: defaultOption, // 默认参数
        }
    },
    mounted() {
        // 图表id
        this.handelId();
        // 配色
        this.handelColor();
        //处理背景色
        this.handleBackGround();
        this.$nextTick(() => {
            let mode = this.options.mode ? this.options.mode : ''
            // 获取图表容器
            this.chart = echarts.init(document.getElementById(this.id),mode);
            // 设置图表参数
            this.chart.setOption(this.options);
            // 暴露click事件
            this.chart.on('click', (params) => {
                this.$emit('click', params)
            })
        })
    },
    methods: {
        handelId() {
            if (this.options.id) {
                this.id = this.options.id;
            } else {
                this.id = 'ap-chart-' + new Date().getTime(); // 默认【ap-chart-时间戳】
            }
        },
        handelColor() {
            let color = this.options.color;
            if (!color) {
                return;
            }
            if (Array.isArray(color)) {
                return;
            }
            if (typeof color !== 'string') {
                return;
            }
            this.options.color = this.defaultOption.colors[color];
        },
        handleBackGround(){
            if(this.options.mode){
                this.options.backgroundColor = "transparent"
            }
        },
        // 更新图表数据
        refresh() {
            this.$nextTick(() => {
                this.handelColor();
                this.handleBackGround();
                this.chart.setOption(this.options, {
                    notMerge: true
                });
            })
        },
        // 更新图表尺寸
        resize() {
            this.chart.resize()
        },
    },
}
</script>

<style scoped>
.ap-chart-ctn {
    height: 100%;
    width: 100%;
}

</style>
