<template>
  <div class="aos-tabs">
    <div class="aos-tabs__container">
      <div v-for="(tab, key) in tabs" v-auth="tab.auth" :key="tab.name" :style="{'margin-right': realMarginLeft}" class="aos-tabs__item" :class="{ 'aos-tabs__item--active': key === currentIndex }" @click="handleClick(key, tab)">
        <i class="aos-tabs__item-icon iconfont" v-if="tab.icon && tab.iconType === 'iconfont'" :class="'icon-' + tab.icon"></i>
        <i class="aos-tabs__item-icon" v-else-if="tab.icon" :class="'el-icon-' + tab.icon"></i>
        <span>{{ tab.title }}</span>
      </div>
    </div>
    <div class="operate">
      <slot></slot>
    </div>
  </div>
</template>
<script>
import isEqual from 'lodash/isEqual'
export default {
  name: 'AosTabs',
  props: {
    tabs: {
      type: Array,
      required: true,
      default: function () {
        return []
      }
    },
    value: {
      type: String
    },
    // 是否显示下划线
    border: {
      type: Boolean,
      default: true
    },
    marginLeft: {
      type: [Number,String]
    }
  },
  computed: {
    realMarginLeft() {
      const type = typeof this.marginLeft
      const PX_REG = /[0-9]+px/g
      if (type === 'number') {
        return this.marginLeft + 'px'
      } else if (type === 'string' && PX_REG.test(this.marginLeft)) {
        return this.marginLeft
      } else {
        return '16px'
      }
    }
  },
  watch: {
    tabs: {
      handler: function (val, oldVal) {
        if (!isEqual(val, oldVal)) {
          if (this.value) {
            this.getCurrentIndex(this.value)
          } else {
            this.currentIndex = 0
          }
        }
      },
      deep: true
    },
    value (val,oldVal) {
      if (val && val !== oldVal) {
        this.getCurrentIndex(val)
      }
    }
  },
  data() {
    return {
      currentIndex: 0
    };
  },
  created () {
    if (this.value) {
      this.getCurrentIndex(this.value)
    }
  },
  methods: {
    getCurrentIndex (tabName) {
      if (tabName) {
        for (let index = 0; index < this.tabs.length; index++) {
          const element = this.tabs[index];
          if (element.name === tabName) {
            this.currentIndex = index
            break
          }
        }
      }
    },
    handleClick (key, tab) {
      this.currentIndex = key
      this.$emit('tab-click', tab.name)
      this.$emit('input', tab.name)
    }
  }
};
</script>
