<template>
  <div class="uif-tabs">
    <div class="uif-tabs-header clearfix">
      <template v-for="(tab, index) in tabs">
        <div class="uif-tabs-slot" v-if="tab.slot" :key="index" @click="setActive(index)">
          <u-base-slot :slot-function="tab.slot" :params="{index, active: tab.active}"></u-base-slot>
        </div>
        <u-button v-else :key="tab.label" class="uif-tabs-button" size="large" :active="tab.active" @click="setActive(index)">{{tab.label}}</u-button>
      </template>
      <div class="fr" v-if="$slots.header"><slot name="header"></slot></div>
    </div>
    <slot></slot>
  </div>
</template>

<script>
import UButton from '@uif/hq/src/components/button'
import UBaseSlot from '@uif/hq/src/components/base-slot'
import {findChildComponents} from '@uif/hq/src/utils/findComponents'
import {map, findIndex} from '@uif/hq/src/utils/array'
import {isFunction} from '@uif/hq/src/utils/assist'
export default {
  name: 'u-tabs',
  components: {
    UButton,
    UBaseSlot
  },
  props: {
    value: {
      type: Number,
      default: 0
    },
    menus: {
      type: Array,
      default: null
    }
  },
  data () {
    return {
      index: -1,
      tabs: this.menus || []
    }
  },
  watch: {
    value () {
      if (this.value !== this.index) {
        this.setActive(this.value)
      }
    }
  },
  mounted () {
    if (this.tabs.length <= 0) {
      this.getTabs()
    }
    const index = findIndex(this.tabs, tab => tab.active)
    this.setActive(Math.max(this.value, index))
  },
  methods: {
    getTabs () {
      this.tabs = map(findChildComponents(this, 'u-tab-panel'), ref => {
        return {
          slot: ref.$scopedSlots.label,
          label: ref.label,
          active: ref.active,
          getRef: () => ref
        }
      })
    },
    setActive (index) {
      if (this.index !== index) {
        this.index = index
        this.$emit('input', this.index)
        this.$emit('change', this.index)
        this.tabs.forEach((tab, idx) => {
          const active = index === idx
          this.$set(tab, 'active', active)
          if (isFunction(tab.getRef)) {
            tab.getRef().isActive = active
          }
        })
      }
    }
  }
}
</script>
