<template>
  <section :class="[c(),cusClass,overFlow]" >
    <section :style="transform" :class="[tabCss]" class="tab-content">
      <slot/>
    </section>
  </section>
</template>
<script>
import { base } from '../../common/mixins'
import stabItem from './tab-item'

export default {
  name: 'SwitchTab',
  mixins: [base],
  component: { stabItem },
  props: {
    position: {
      type: String,
      default: 'top',
    },
    cusClass: {
      type: String,
      default: '',
    },
    defaultActive: {
      type: Number,
      default: 0,
    },
    showDivider: {
      type: Boolean,
      default: false,
    },
    overflowX: {
      type: Boolean,
      default: true,
    },
  },
  data () {
    return {
      items: [],
      length: '',
      activedIndex: '',
      translate: 0,
    }
  },
  computed: {
    overFlow () {
      return this.overflowX ? 'auto-overflow-x' : ''
    },
    tabCss () {
      return this.position === 'top' ? this.c('top') : this.c('bottom')
    },
    count () {
      this.length = this.items.length
      return this.items.length
    },
    current () {
      let vm = this
      let length = (vm.items.length) - 1
      if (vm.defaultActive > length) {
        vm.index = length
      } else {
        vm.index = vm.defaultActive
      }
      return vm.index
    },

    transform () {
      return {
        transform: 'translateX(' + this.translate + 'px' + ')',
       // transition: 'right 0.3s cubic-bezier(0.35, 0, 0.25, 1), left 0.3s cubic-bezier(0.35, 0, 0.25, 1) 0.09s;',
      }
    },
  },
  mounted () {
    let vm = this
    this.items[vm.current].$el.classList.add('activated')
    this.scrollToActiveTab(vm.current, this.items[vm.current].$el.clientWidth)
  },
  methods: {
    actived (index, clientWidth) {
      this.activedIndex = index
      this.$emit('tabClick', index)
      this.$emit('input', index)

      this.scrollToActiveTab(index, clientWidth)
    },

    scrollToActiveTab (index, width) {
      let clientWidth = this.$el.clientWidth
      index += 1
      let vm = this
      let count = Math.floor(clientWidth / width)
      let overFlowWidth = clientWidth - count * width
      let num
      if (index > count) {
        num = index - count
        if ((vm.count - index) >= 1) {
          num += 1
        }
      } else {
        num = 0
      }
      if (num === 0) {
        vm.translate = 0
      } else {
        vm.translate = -num * width + overFlowWidth
      }
    },
  },
}
</script>

<style lang="less">
  @import "../../common/styles/vue-1px";
  .auto-overflow-x {
    overflow-x: auto;
  }

  .hls-switch-tab {
    width: 100%;
   // position: absolute;
    z-index: 1;
    display: flex;
    // justify-content: space-around;
    height: 40px;
    background-color: #fff;

    &-top {
     // top: 0;

      &:after {
        .setBottomLine();
      }
    }

    &-bottom {
     // bottom: 0;

      &:before {
        .setTopLine();
      }
    }
  }

</style>
