<template>
  <n-resize class="n-tab-switch" :class="'n-tab-switch-' + size" tag="span" @update="update" @mouseleave.native="transition(nValue)">
    <template v-for="(option, index) in options">
      <span :key="index" class="n-tab-switch-item" :class="{active: index === nValue}"
            @click="onClick($event, option, index)" @mouseenter="transition(index)">{{option.label}}</span>
    </template>
    <span class="n-tab-switch-line" :style="{left}"></span>
  </n-resize>
</template>
<script>
import NResize from '@uif/next/lib/components/resize'
import {prop} from '@uif/next/lib/utils/tools'
import vModel from '_common/vModel'

export default {
  name: 'n-tab-switch',
  mixins: [vModel],
  components: {
    NResize
  },
  props: {
    // 当前值
    value: prop.number(),
    // 切换选项
    options: prop.array(),
    // 大小
    size: prop.inArray(['small', 'large'], 'small')
  },
  data () {
    return {
      nValue: this.value,
      left: 0
    }
  },
  watch: {
    nValue () {
      this.update()
    }
  },
  mounted () {
    this.update()
  },
  methods: {
    update () {
      this.transition(this.nValue)
    },
    onClick (event, option, index) {
      if (this.nValue !== index) {
        this.nValue = index
        this.$emit('u-change', index, option)
        this.$emit('click', event, option, index)
      }
    },
    transition (index) {
      try {
        const el = this.$el.children[index]
        this.left = el.offsetWidth / 2 - 18 + el.offsetLeft + 'px'
      } catch (e) {}
    }
  }
}
</script>
