import Vue                from 'vue';
import { getGraghByName } from './stSvgStruct';

Vue.component('st-svg', {
    render:  function (createElement) {
        let gragh = getGraghByName(this.name, this.svgColor,this.viewBox);
        let root = createElement(
            'svg',
            {
                attrs: {
                    width:   this.width ? this.width : '22px',
                    height:  this.height ? this.height : '22px',
                    //画布大小，默认不传，当下载的图片不是22*22时传入
                    viewBox: this.viewBox ? this.viewBox : '0 0 22 22',
                    version: '1.1',
                    xmlns:   'http://www.w3.org/2000/svg',
                },
            },
        );
        root.children = [];

        function renderChildren(lVNode, gragh) {
            if (gragh.children) {
                lVNode.children = [];
                for (const nextGragh of gragh.children) {
                    if (!nextGragh.label) {
                        console.error('secondGragh label没有指定');
                    }
                    let nextLVNode = createElement(
                        nextGragh.label,
                        {
                            attrs: this.getAttrsObjByStr(nextGragh.attrs),
                        },
                    );
                    if (nextGragh.children) {
                        renderChildren.call(this, nextLVNode, nextGragh);
                    }
                    lVNode.children.push(nextLVNode);
                }
            }
        }

        for (const secondGragh of gragh) {
            if (!secondGragh.label) {
                console.error('secondGragh label没有指定');
            }
            let secondLVNode = createElement(
                secondGragh.label,
                {
                    attrs: this.getAttrsObjByStr(secondGragh.attrs),
                },
            );
            renderChildren.call(this, secondLVNode, secondGragh);
            root.children.push(secondLVNode);
        }
        return root;
    },
    data() {
        return {
            svgColor: this.color ? this.color: "#000000",
        };
    },
    props:   {
        width:   {
            type: String,
        },
        height:  {
            type: String,
        },
        viewBox: {
            type: String,
        },
        name:    {
            type:     String,
            required: true,
        },
        color:   {
            type: String,
        },
    },
    methods: {
        getAttrsObjByStr(str) {
            let obj = {};
            let arr = str.match(/([\w-]+)\=\"(.*?)\"/g);
            for (const kv of arr) {
                var arrKv = kv.split('=');
                obj[arrKv[0]] = arrKv[1].split('"').join('');
            }
            return obj;
        },
    },
    watch: {
        color(val) {
            this.svgColor = val;
        }
    }
});
