<template>
  <div class="upanapp-sticky-box">
    <slot></slot>
  </div>
</template>

<script>
import sticky from './sticky'

export default {
  name: 'ua-sticky',
  data () {
    return {
      initTimes: 0
    }
  },
  created () {
    this.$upanapp && this.$upanapp.bus && this.$upanapp.bus.$on('upanapp:after-view-enter', this.bindSticky)
  },
  activated () {
    if (this.initTimes > 0) {
      this.bindSticky()
    }
    this.initTimes++
  },
  mounted () {
    this.$nextTick(() => {
      this.bindSticky()
    })
  },
  beforeDestroy () {
    this.$upanapp && this.$upanapp.bus && this.$upanapp.bus.$off('upanapp:after-view-enter', this.bindSticky)
  },
  methods: {
    bindSticky () {
      if (this.disabled) {
        return
      }
      this.$nextTick(() => {
        sticky(this.$el, {
          scrollBox: this.scrollBox,
          offset: this.offset,
          checkStickySupport: typeof this.checkStickySupport === 'undefined' ? true : this.checkStickySupport
        })
      })
    }
  },
  props: ['scrollBox', 'offset', 'checkStickySupport', 'disabled']
}
</script>

<style lang="less">
@import '../../styles/variable.less';

.upanapp-sticky-box {
  z-index: @sticky-zindex;
}
.upanapp-sticky {
  width: 100%;
  position: sticky;
  top: 0;
}
.upanapp-fixed {
  width: 100%;
  position: fixed;
  top: 0;
  transform: translate3d(0, 0, 0);
}
.upanapp-sticky-fill {
  display: none;
}
.upanapp-fixed + .upanapp-sticky-fill {
  display: block;
}
</style>
