<template>
  <transition name="n-opacity">
    <div v-show="visible" class="n-loading-bar">
      <n-progress :height="height" :background="background" :color="color" :value="value"></n-progress>
    </div>
  </transition>
</template>
<script>
import NProgress from '@uif/next/lib/components/progress'
import { prop, Timeout } from '@uif/next/lib/utils/tools'
export default {
  name: 'n-loading-bar',
  components: { NProgress },
  props: {
    // 加载中
    loading: prop.boolean(),
    // 高度
    height: prop.stringNumber(4),
    // 背景色
    background: prop.string(),
    // 填充颜色，可使用数组做渐变
    color: {
      type: [String, Array]
    }
  },
  data () {
    return {
      time: new Timeout(),
      visible: false,
      value: 0
    }
  },
  watch: {
    loading: {
      immediate: true,
      handler () {
        this.onChange()
      }
    }
  },
  beforeDestroy () {
    this.time.clear()
  },
  methods: {
    onChange () {
      if (this.loading) {
        this.start()
      } else if (this.visible) {
        this.finish()
      }
    },
    start () {
      this.visible = true
      this.value = 0
      this.startUpdate()
    },
    finish () {
      this.time.clear()
      this.value = 1
      this.time.out(() => {
        this.visible = false
        this.time.out(() => (this.value = 0), 200)
      }, 800)
    },
    startUpdate () {
      this.time.out(() => {
        this.value += Math.floor(Math.random() * 3 + 1) / 100
        if (this.value < 0.95) this.startUpdate()
      }, 200)
    }
  }
}
</script>
