<template>
    <svg
        :class="bem([size, iconName])"
        width="1em"
        color="currentColor"
        height="1em"
    ><use :xlink:href="'#gd-icons-' + iconName"/></svg>
</template>

<script>
import svgSprite from './icon-sprite';
import { createComponentName, componentMixin } from '../_utils/component';
import { on, off } from '../_utils/dom';
import { isSSR } from '../_utils/constant';

let loaded = false;
function loadSprite() {
    if (!loaded) {
        loaded = true;
        const div = document.createElement('div');
        div.id = '__GD_SVG_ICONS__';
        div.style.display = 'none';
        div.innerHTML = svgSprite;

        document.body.appendChild(div, document.body.firstChild);
    }
}

if (!isSSR()) {
    loadSprite();
}

export default {
    name: createComponentName('icon'),
    mixins: [componentMixin],
    props: {
        // 图标名
        name: {
            type: String,
            required: true,
        },
        hoverName: {
            type: String
        },
        size: {
            type: String,
        },
    },
    data() {
        return {
            hover: false
        };
    },
    computed: {
        iconName() {
            if (!this.hoverName) return this.name;

            return this.hover ? this.hoverName : this.name;
        }
    },
    mounted() {
        if (!this.isSSR()) {
            if (this.hoverName) {
                on(this.$el, 'mouseenter', this.mouseenter);
                on(this.$el, 'mouseleave', this.mouseleave);
            }
        }
    },
    beforeDestroy() {
        if (!this.isSSR() && this.hoverName) {
            off(this.$el, 'mouseenter', this.mouseenter);
            off(this.$el, 'mouseleave', this.mouseleave);
        }
    },
    methods: {
        mouseenter() {
            this.hover = true;
        },
        mouseleave() {
            this.hover = false;
        }
    }
};
</script>
<style lang="less">
@import '../_styles/base.less';

@b: ~'@{prefix}-icon';

.@{b} {
    display: inline-block;
    color: currentColor;

    &--small {
        font-size: 12px;
    }

    &--medium {
        font-size: 18px;
    }

    &--big {
        font-size: 22px;
    }

    &--large {
        font-size: 32px,
    }

    &--huge {
        font-size: 42px;
    }

    &--gigantic {
        font-size: 64px;
    }

    @keyframes icon-rotation {
        100% {
            transform: rotate(360deg);
        }
    }
}
</style>
