<template>
    <quick-item
        :class="bem()"
        @click.native="scrollToTop"
        v-show="isShowBackTopBtn">
        <icon name="arrow-top" />
        <span :class="bem('tip')">回到<br>顶部</span>
    </quick-item>
</template>

<script>
import { componentMixin, createComponentName } from '../_utils/component';
import quickItem from './QuickItem';
import icon from '../Icon';

export default {
    name: createComponentName('quick-link-back-top'),

    components: {
        icon,
        quickItem,
    },
    mixins: [componentMixin],

    data() {
        return {
            isShowBackTopBtn: false,
        };
    },

    mounted() {
        window.addEventListener('scroll', this.handleScroll, false);
    },

    beforeDestroy() {
        window.removeEventListener('scroll', this.handleScroll, false);
    },

    methods: {
        scrollToTop() {
            this.lastTop = undefined;
            this.beginScrollToTop();
        },
        beginScrollToTop() {
            const c = document.documentElement.scrollTop || document.body.scrollTop;
            if (this.lastTop < c) return;

            this.lastTop = c;
            if (c > 20) {
                window.requestAnimationFrame(this.beginScrollToTop);
                window.scrollTo(0, c - c / 8);
            }
            else {
                window.scrollTo(0, 0);
            }
        },

        handleScroll() {
            this.isShowBackTopBtn = window.pageYOffset >= 100;
        },
    },
};
</script>

<style lang="less">
@import '../_styles/base.less';

@b: ~'@{prefix}-quick-link-back-top';

.@{b} {
    & &__tip {
        display: none;
    }

    & svg {
        font-size: 24px;
        color: #333;
    }

    &:hover {
        .@{b}__tip {
            display: block;
        }

        svg {
            display: none;
        }
    }

}
</style>
