<template>
  <transition name="uif-opacity">
    <u-progress v-show="visible" class="uif-loading-bar" :percent="percent" :height="2" transparent></u-progress>
  </transition>
</template>
<script>
import UProgress from '@uif/core/lib/components/progress'
export default {
  name: 'u-loading-bar',
  components: { UProgress },
  props: {
    loading: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      visible: false,
      percent: 0,
      timer: 0
    }
  },
  watch: {
    loading: {
      immediate: true,
      handler () {
        this.handleLoading()
      }
    }
  },
  methods: {
    handleLoading () {
      if (this.loading) {
        this.start()
      } else if (this.visible) {
        this.finish()
      }
    },
    start (percent = 0) {
      this.visible = true
      this.percent = percent
      this.startUpdate()
    },
    finish () {
      this.clearTimer()
      this.percent = 100
      setTimeout(() => {
        this.visible = false
        setTimeout(() => {
          this.percent = 0
        }, 200)
      }, 800)
    },
    startUpdate () {
      this.timer = setInterval(() => {
        this.percent += Math.floor(Math.random() * 3 + 1)
        if (this.percent > 95) this.clearTimer()
      }, 200)
    },
    clearTimer () {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = 0
      }
    }
  }
}
</script>
