<template>
  <div class="ipub-backtop"
       :class="isShow ? 'isShow' : ''">
    <div class="ipub-backtop-content">
      <slot></slot>
      <div class="tc"
           @click="scrollTop">
        <ipub-icon type="iconBackToTop" />
        <div class="ipub-p5">Back to top</div>
      </div>
    </div>
    <div class="ipub-backtop-switch">
      <ipub-icon type="iconArrow" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'IpubBacktop',
  data () {
    return {
      isShow: false
    }
  },
  mounted () {
    window.addEventListener(
      'scroll',
      () => {
        if (
          (document.documentElement.scrollTop || document.body.scrollTop) > 200
        ) {
          this.isShow = true
        } else {
          this.isShow = false
        }
      },
      true
    )
  },
  methods: {
    scrollTop () {
      const timer = setInterval(function () {
        //获取滚动条距离顶部的高度
        let osTop =
          document.documentElement.scrollTop || document.body.scrollTop
        let ispeed = Math.floor(-osTop / 5)
        document.documentElement.scrollTop = document.body.scrollTop =
          osTop + ispeed

        if (osTop == 0) {
          clearInterval(timer)
        }
      }, 10)
    }
  }
}
</script>

<style lang="scss" scoped>
.ipub-backtop {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: -1px -1px 10px 0px rgba(206, 232, 234, 0.5);
  width: 52px;
  // min-height: 80px;
  font-size: 24px;
  position: fixed;
  right: -32px;
  bottom: 110px;
  background: $body_color;
  border-radius: 4px 0 0 4px;
  opacity: 1;
  transition: 0.3s all;
  z-index: 999;
  cursor: pointer;
  padding: 12px 0;
  // @include mq($xl) {
  //   right: calc(50vw - #{$lg_screen/2});
  // }
  .ipub-p5 {
    font-size: 10px;
  }
  &.isShow {
    opacity: 1 !important;
  }
  &-content {
    transition: 0.3s all;
    opacity: 0;
  }
  &-switch {
    transition: 0.3s all;
    opacity: 1;
    position: absolute;
    left: 0;
    width: 20px;
    text-align: center;
    font-size: 14px;
    > i {
      display: inline-block;
      transform: rotate(90deg);
    }
  }
  &:hover {
    right: 0;
    .ipub-backtop-content {
      opacity: 1;
    }
    .ipub-backtop-switch {
      opacity: 0;
    }
  }
}
</style>
