<template>
  <div class="uif-slide-navigation" :class="mode" v-if="blocks.length">
    <template v-for="(block, idx) in blocks">
      <div class="uif-slide-nav" :key="idx" :class="{active: index === idx}"
           @click="handleClick(block, idx)">{{idx + 1}}. {{block.title}}</div>
    </template>
  </div>
</template>

<script>
import {oneOf} from '@uif/core/lib/utils/assist'
import {findChildComponents} from '@uif/core/lib/utils/findComponents'
import {forEach, map} from '@uif/core/lib/utils/array'
import {waitScroll, scrollIntoView} from '@uif/core/lib/utils/dom'

export default {
  name: 'u-slide-navigation',
  props: {
    auto: {
      type: Boolean,
      default: true
    },
    mode: {
      validator (value) {
        return oneOf(value, ['normal', 'dark'])
      },
      default: 'normal'
    }
  },
  data () {
    return {
      index: 0,
      blocks: []
    }
  },
  mounted () {
    if (this.auto) {
      this.findBlocks()
    }
  },
  methods: {
    findBlocks (content = this.$parent) {
      this.index = 0
      this.blocks = map(findChildComponents(content, 'u-slide-block'), ref => ({title: ref.title, getRef: () => ref}))
    },
    handleClick (block, idx) {
      this.index = idx
      const el = block.getRef().$el
      return waitScroll(el, 'top', () => scrollIntoView(el))
    },
    // 全部设置显示模式
    setAllVisible (value) {
      forEach(this.blocks, block => block.getRef().setVisible(value))
    },
    // 全部取消等待模式
    setAllLoaded () {
      forEach(this.blocks, block => block.getRef().setLoaded())
    }
  }
}
</script>
