/**
 * Created by Zhang Haijun on 2018/6/8.
 */

import echarts from 'echarts';
import theme from './theme/walden';

export default {
    props: {
        data: {
            type: null,
        },
        setting: {
            type: Object,
            default: function () {
                return {
                    fixed: 0
                };
            },
        },
        unit: {
            type: String,
        },
        className: {
            type: String,
            default: 'chart',
        },
        dataZoom: {
            type: Boolean,
            default: false,
        },
        id: {
            type: String,
            default: 'chart',
        },
        width: {
            type: String,
            default: '200px',
        },
        height: {
            type: String,
            default: '300px',
        },
    },
    data() {
        return {
            chart: null,
        };
    },
    computed: {
        themeColor () {
            if (this.$store.state.app.theme.name === 'theme-night') {
                return {
                    legendColor: '#fff',
                    axisColor: '#ccc'
                };
            }
            return {};
        }
    },
    mounted() {
        this.initChart();
        window.addEventListener('resize', this.resize);
    },
    watch: {
        themeColor (newVal, oldVal) {
            if (newVal.legendColor === oldVal.legendColor) return;
            this.updateChart();
        },
        data: function () {
            this.updateChart();
        },
    },
    beforeDestroy() {
        if (!this.chart) {
            return;
        }
        this.chart.dispose();
        this.chart = null;
        window.removeEventListener('resize', this.resize);
    },
    methods: {
        initChart() {
            echarts.registerTheme('theme', theme);
            const target = document.getElementById(this.id);
            this.chart = echarts.init(target, 'theme');
            this.updateChart();
        },
        resize() {
            if (this.chart) this.chart.resize();
        },
    },
};
