<template>
    <h-drop-area :isShow="isShow">
        <span :class="classes({show: isShow})" @click="handleClick">{{text}}</span>
    </h-drop-area>
</template>
<script>
import { classesMixin } from '../../common/mixins/classname';
import hDropArea from '../drop-area/index.vue';
let classMixin = classesMixin('back-top');
export default {
    name: 'h-back-top',
    mixins: [classMixin],
    components: {
        hDropArea
    },
    props: {
        text: {
            type: String,
            default: '返回顶部'
        },
        targetId: String
    },
    data() {
        return {
            isShow: false,
            DOM: null,
            scrollTop: 0,
            timer: null
        }
    },
    mounted() {
        if ( this.targetId ) {
            this.$nextTick( () => {
                const DOM = document.getElementById(this.targetId);
                DOM.addEventListener( 'scroll', this.handleWindowScroll );
                this.DOM = DOM;
            } );
        } else {
            const DOM = window;
            DOM.addEventListener( 'scroll', this.handleDOMScroll );
            this.DOM = DOM;
        }
        
        window.onmousewheel = this.handleMouseScroll;
        window.ontouchstart = this.handleMouseScroll;
    },
    destroyed() {
        if ( this.targetId ) {
            this.DOM.removeEventListener('scroll', this.handleWindowScroll);
        } else {
            this.DOM.removeEventListener('scroll', this.handleDOMScroll);
        }
        
        window.onmousewheel = null;
        window.ontouchstart = null;
        this.DOM = null;
    },
    methods: {
        handleWindowScroll() {
            let scrollTop = this.DOM.scrollTop;
            this.scrollTop = scrollTop;
            if (scrollTop > 150) {
                this.isShow = true
            } else {
                this.isShow = false
            }
        },
        handleDOMScroll( e ) {
            let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
            this.scrollTop = scrollTop;
            if (scrollTop > 150) {
                this.isShow = true
            } else {
                this.isShow = false
            }
        },
        handleClick() {
            let that = this;
            this.timer = setInterval(() => {
                let ispeed = Math.floor(-that.scrollTop / 10);
                if ( this.targetId ) {
                    this.DOM.scrollTop = that.scrollTop + ispeed;
                } else {
                    document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed;
                }
                if (that.scrollTop === 0) {
                    clearInterval(this.timer)
                }
            }, 16);
        },
        handleMouseScroll() {
            clearInterval(this.timer)
        }
    }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
