/**
 * 基于antv/g2抽象的基础vuejs组件
 * @author xiufu.wang
 * 2025-02-06添加registerShape
 */
import { Chart,registerShape } from '@antv/g2'
import propDataSource from "mars-pro/src/pro/mixins/propDataSource";

export default {
    name: 'ProDataChart',
    componentName: 'ProDataChart',
    mixins: [propDataSource],
    props: {
        createChartOptions: {},
        height: Number,
        width: Number
    },

    computed: {
        chartData() {
            return this.selectDatas || []
        }
    },
    watch: {
        /**
        * 数据更新是重新绘制
        */
        chartData() {
            this.doPaint()
        }
    },
    methods: {
        createChart() {
            const attrs = this.$attrs || {}
            const chart = this.chart = new Chart({
                container: this.$el,
                autoFit: true,
                ...attrs
            });
            return chart
        },
        upateChartOption() {
            let createChartOptions = this.createChartOptions || []
            createChartOptions = Array.isArray(createChartOptions) ? createChartOptions : [createChartOptions]
            // 处理antv g2 配置
            createChartOptions.forEach(cco => {
                cco({
                    chart: this.chart,
                    data: this.chartData,
                    attrs: this.$attrs,
                    registerShape: registerShape
                })
            })
        },
        doPaint() {
            this.upateChartOption()
            if (this.hadRender) {
                this.chart.changeData(this.chartData)
            } else {
                this.chart.data(this.chartData)
                this.chart.render()
            }
        }
    },

    render() {
        const _datas = {
            'class': {
                'pro-data-chart': true
            },
            style: {
                ...(this.width > 0 ? { width: `${this.width}px` } : {}),
                ...(this.height > 0 ? { height: `${this.height}px` } : {})
            },
            directives: [
                {
                    name: 'loading',
                    value: this.isLoading
                }
            ]
        }

        return (
            <div {..._datas}>
            </div>
        )
    },

    mounted() {
        // 创建
        const chart = this.createChart()
        // 渲染
        this.doPaint()
        this.hadRender = true
    },
    beforeDestroy() {
        if (this.chart && this.hadRender) {
            this.chart.destroy()
        }
    }
}