<template>
  <div class="zui-tab-bar">
    <div class="zui-tab-bar-inner">
      <div class="zui-tab-bar-list">
        <div class="zui-tab-bar-item" :class="itemClassRender(item)" v-for="(item, index) in items" :key="item.name" @click="$_onClick(item, index)">
          <slot name="item" :item="item" :items="items" :index="index" :currentName="currentName">{{ item.label }}</slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TabBar',
  props: {
    value: {
      type: [String, Number],
      default: '',
    },
    items: {
      type: Array,
      default: function () {
        return [];
      },
    },
  },
  data: function () {
    return {
      currentName: '',
    };
  },
  computed: {
    currentIndex: function () {
      for (var i = 0, len = this.items.length; i < len; i++) {
        if (this.items[i].name == this.currentName) {
          return i;
        }
      }
      return 0;
    },
    currentTab: function () {
      if (this.currentIndex) {
        return this.items[this.currentIndex];
      }
      return {};
    },
  },
  watch: {
    value: {
      immediate: true,
      handler: function (val) {
        if (val != this.currentName) {
          this.currentName = val;
        }
      },
    },
  },
  created: function () {
    if (this.currentName == '' && this.items.length) {
      this.currentName = this.items[0].name;
      this.$emit('change', this.items[0].name, this.items[0], 0, 0);
    }
  },
  methods: {
    $_onClick: function (item, index) {
      if (item.disabled) {
        return;
      }
      this.$emit('change', item.name, item, index, this.currentIndex);
      this.currentName = item.name;
      this.$emit('input', item.name);
    },
    itemClassRender: function (item) {
      return {
        'is-active': this.currentName == item.name,
        'is-disabled': !!item.disabled,
      };
    },
  },
};
</script>

<style>
@import './index.css';
</style>
