<template>
  <div class="fbg-tabs">
    <ul class="fbg-tabs-box">
      <li v-for="(item) in viewList" :key="item.path"  :class="{'fbg-tabs-item': true, 'active': item.path === $route.path }" @click="handleClick(item)">
        <i class="fbgiconfont icon-touxiang" />
        <span>{{item.meta.title}}</span>
        <i class="fbgiconfont icon-guanbishanchu  fbg-tabs-item-close" @click.stop="handleClose(item.path)"/>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      viewList: [],
      pathList: []
    };
  },
  watch: {
    data: {
      immediate: true,
      handler() {
        this.viewList = this.data||[];
      }
    },
    '$route': {
      immediate: true,
      deep: true,
      handler(route) {
        if (route.meta && route.meta.title) {
          if (this.pathList.indexOf(route.path) === -1) {
            this.pushItem(route);
          }  
        }
      }
    }
  },
  methods: {
    handleClick(item) {
      if (item.path === this.$route.path) {
        return false;
      }
      this.$router.push({
        path: item.path,
        replace: true
      })
    },
    handleClose(path) {
      this.removeItem(path);
    },
    pushItem(item) {
      this.viewList.push(item);
      this.pathList.push(item.path);
    },
    removeItem(path) {
      let index = this.pathList.indexOf(path);
      if (index > -1) {
        this.pathList.splice(index, 1);
        this.viewList.splice(index, 1);
      }
      if (this.$route.path === path) {
        if (index >= this.pathList.length) {
          index --;
        }
        let timer = setTimeout(() => {
          this.$router.push({
            path: this.pathList[index]
          });
          clearTimeout(timer);
          timer = null;
        }, 0)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.fbg {
  &-tabs {
    padding: 0px 30px;
    height: 32px;
    line-height: 32px;
    .active {
      background-color: $themeDimColor;
      color: $themeColor;
    }
    &-item {
      cursor: pointer;
      &:first-child {
        border-left: 1px solid rgba(0,0,0, 0.1);
      }
      display: inline-block;
      width: 150px;
      height: 32px;
      line-height: 32px;
      border-right: 1px solid rgba(0,0,0, 0.1);
      color: #666;
      padding: 0px 10px;
      box-sizing: border-box;
      position: relative;
      &:hover {
        background-color: $themeDimColor;
      }
      &-close{
        position: absolute;
        right: 10px;
        top: 0px;
        color: #666;
        font-size: 12px;
      }
      i {
        vertical-align: middle;
      }
      span {
        margin-left: 5px;
        font-size: 12px;
      }
    }
    box-shadow: 1px 0px 5px $themeShadowColor;
  }
}
</style>
