//置顶
<template>
  <div class="all" v-show="showIcon">
    <i class="icon-huidaodingbu" @click="backTop"></i>
  </div>
</template>

<script>
  // import smoothscroll from 'smoothscroll-polyfill'
  export default {
    name: 'PlacedTop',
    props: {
      containerId: {
        type: String,
        default: '',
      },
      nodeId: {
        type: String,
        default: '',
      },
      classNodeId: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        showIcon: false,
        scrollTop: null,
      }
    },
    mounted() {
      // 解决移动端 scrollTo 的 behavior: "smooth" 无效的问题
      // smoothscroll.polyfill()
      window.addEventListener('scroll', this.scrollBackTop, true) //监听滚动条
    },

    methods: {
      backTop() {
        setTimeout(() => {
          if (this.containerId) {
            document.getElementById('workerContent').scrollTo({
              top: 0,
              behavior: 'smooth',
            })
          } else if (this.nodeId) {
            document.getElementById(this.nodeId).scrollTo({
              top: 0,
              behavior: 'smooth',
            })
          } else if (this.classNodeId) {
            document.getElementsByClassName(this.classNodeId)[0].scrollTo({
              top: 0,
              behavior: 'smooth',
            })
          } else {
            this.$parent.$el.scrollTo({
              top: 0,
              behavior: 'smooth',
            })
          }
        }, 0)
        this.showIcon = false
      },

      // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
      scrollBackTop() {
        const that = this
        let scrollTop = this.$parent.$el.scrollTop
        //

        if (this.containerId) {
          scrollTop = document.getElementById('workerContent').scrollTop
        }
        // id
        if (this.nodeId) {
          scrollTop = document.getElementById(this.nodeId)
            ? document.getElementById(this.nodeId).scrollTop
            : 0
        }
        // class
        if (this.classNodeId) {
          scrollTop = document.getElementsByClassName(this.classNodeId)[0]
            ? document.getElementsByClassName(this.classNodeId)[0].scrollTop
            : 0
        }

        that.scrollTop = scrollTop

        if (that.scrollTop > 400) {
          that.showIcon = true
        } else {
          that.showIcon = false
        }
      },
    },
    //移除滚动条监听
    beforeDestroy() {
      window.removeEventListener('scroll', this.scrollBackTop, true)
    },
  }
</script>

<style lang="scss" scoped>
  .all {
    position: fixed;
    bottom: 15vh;
    right: 8px;
    z-index: 99;
    width: 36px;
    height: 36px;
    background: #ffffff;
    box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.16);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      font-size: 24px;
      color: #409eff;
    }
  }
</style>
