<template>
  <div class="uif-sticky-bar" :class="{ fixed }">
    <div class="uif-sticky-bar-content" :style="styles">
      <slot :fixed="fixed"></slot>
    </div>
  </div>
</template>

<script>
import { oneOf } from '@uif/hq/src/utils/assist'
import { debounce } from '@uif/hq/src/utils/pipe'
export default {
  name: 'u-sticky-bar',
  props: {
    position: {
      validator (value) {
        return oneOf(value, ['top', 'bottom'])
      },
      default: 'top'
    },
    value: {
      type: [Number, String],
      default: 0
    },
    debounce: {
      type: [Number, String],
      default: 200
    },
    transform: {
      type: Boolean,
      default: false
    },
    width: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      scrollHandler: debounce(this.onScroll, Number(200)),
      fixed: false,
      scrollLeft: 0,
      scrollWidth: 0
    }
  },
  computed: {
    styles () {
      const styles = {}
      if (this.fixed) {
        styles.position = 'fixed'
        styles[this.position] = this.value + 'px'
        if (this.transform) {
          styles.transform = 'translateX(-' + this.scrollLeft + 'px)'
        }
        if (this.width) {
          styles.width = this.scrollWidth + 'px'
        }
      }
      return styles
    }
  },
  mounted () {
    this.update()
    document.addEventListener('scroll', this.update)
    window.addEventListener('resize', this.update)
  },
  beforeDestroy () {
    document.removeEventListener('scroll', this.update)
    window.addEventListener('resize', this.update)
  },
  methods: {
    update () {
      const top = this.$el.getBoundingClientRect().top
      switch (this.position) {
        case 'top':
          this.setFixed(top < Number(this.value))
          break
        case 'bottom':
          this.setFixed(top > window.innerHeight - Number(this.value))
          break
      }
      this.scrollLeft = document.documentElement.scrollLeft
      this.scrollWidth = document.documentElement.scrollWidth
      this.scrollHandler()
    },
    setFixed (value) {
      if (this.fixed !== value) {
        this.fixed = value
        this.$emit('change', value)
      }
    },
    onScroll () {
      this.$emit('scroll', this)
    }
  }
}
</script>
