<template>
  <div class="fbg-tabs">
    <ul class="fbg-tabs-box" ref="mainRef">
      <li v-if="refresh" style="position: absolute;width: 30px;left: 0;text-align: center;cursor:pointer">
        <span class="fbg-tabs-item-refresh" @click="handleRefresh">
          <i class="el-icon-refresh" style="font-size: 16px" />
        </span>
      </li>
      <li v-for="(item, index) in viewList" :key="item.path" :style="{'padding-right': hideClose?'5px':'25px',width:itemWidth}" :class="{'fbg-tabs-item': true, 'active': item.path === $route.path }" @click="handleClick(item)">
        <i :class="item.icon ? item.icon : 'el-icon-copy-document'" />
        <span>{{item.title}}</span>
        <span v-if="!item.hideClose && viewList.length !== 1" v-show="item.path === $route.path?true:(hideClose?false:true)"  class="fbg-tabs-item-close" @click.stop="handleClose(item.path)">
        <i class="fbgiconfont icon-guanbishanchu" />
        </span>
      </li>
    </ul>
  </div>
</template>
<script>
import util from '../../utils';
import Vue from 'vue';
export default {
  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    refresh: {
      type: Boolean,
      default(){
        return false
      }
    }
  },
  data() {
    return {
      viewList: [],
      pathList: [],
      itemWidth: '150px',
      hideClose: false,
      showClose: true,
      $page: {}
    };
  },
  beforeCreate() {
    Vue.prototype.$tabpage = this;
  },
  created() {
    this.init(this.data);
    this.initRoute(this.$route);
  },
  mounted() {
    this.itemWidth =  this.getItemWidth();
    window.addEventListener('resize', () => {
      this.itemWidth =  this.getItemWidth();
    }, false)
  },
  watch: {
    viewList: {
      immediate: true,
      handler(data) {
        this.itemWidth =  this.getItemWidth();
      }
    },
    data: {
      immediate: true,
      handler(data) {
        this.init(data);
      }
    },
    '$route': {
      immediate: true,
      deep: true,
      handler(route, old) {
        this.initRoute(route);
        if(old && old.meta && old.meta.isAutoDelete){
          this.handleClose(old.path);
        }
      }
    }
  },
  methods: {
    handleRefresh(item,index){
      this.viewList.forEach((item, index) => {
        if (item.path === this.$route.path) {
          // 临时关闭当前页面, 但是不关闭标签页
          this.temporaryClose(item,index);
          this.$emit('refresh', item.path);
          this.$nextTick(() => {
            this.$router.replace({
              path: '/refresh',
              query: { path: item.fullPath, query: this.$route.query },
              replace: true
            });
          })
        }
      })
    },
    temporaryClose(item,index) {
  	  this.pathList.splice(index, 1);
	  const viewList = this.viewList.filter(item => this.pathList.includes(item.path));
  	  this.$emit('change', item.path, viewList);
  	  this.$emit('close', item.path, viewList);
    },
    init(data) {
      this.viewList = data||[];
      this.pathList = this.data.map(item => item.path);
    },
    initPathList() {
	  this.pathList = this.viewList.map(item => item.path);
    },
    initRoute(route) {
      if (route && route.meta && route.meta.title) {
      	this.initPathList();
        const index = this.pathList.indexOf(route.path);
        const $page = {
          ...route,
          title: route.query.MenuName || route.meta.title,
          icon: route.meta.icon
        }
        if ( index === -1) {
          this.pushItem($page);
        } else {
          Object.assign(this.viewList[index], $page);
        }
      } else if(route && route.path !== '/')  {
        throw new Error('请设置当前路由的meta.title属性！');
      }
    },
    getItemWidth() {
      if (this.$refs.mainRef) {
        let width = parseInt(util.getStyle(this.$refs.mainRef, 'width'));
        width = width/this.viewList.length;
        if (width < 100) {
          this.hideClose = true;
        } else {
          this.hideClose = false;
        }
        return width > 150 ? 150+'px':(width-2)+'px';
      } else {
        return "150px";
      }
    },
    handleClick(item) {
      if (item.path === this.$route.path) {
        return false;
      }
      let flag = true;
      this.$emit('change', item.path, this.viewList, (res) => {
        flag = false;
      });
      if (flag !== false) {
        this.$router.push({
          ...item,
          replace: true
        });
      }
    },
    handleClose(path) {
      this.closePage(path);
    },
    closePage(path, newUrl) {
      this.removeItem(path, newUrl);
      this.$emit('change', path, this.viewList);
      this.$emit('close', path, this.viewList);
    },
    pushItem(item) {
      this.viewList.push(item);
      this.pathList.push(item.path);
      this.$emit('change', item.path, this.viewList);
    },
	  virtualRemoveItem(path) {
      let index = this.pathList.indexOf(path);
      if (index > -1) {
    	  this.pathList.splice(index, 1);
    	  this.viewList.splice(index, 1);
      }
      const len = this.pathList.length;
      if (this.$route.path === path) {
    	  if (index >= len) {
    		  index --;
    	  } else if(len === 0) {
    		  return false;
    	  }
    	  let timer = setTimeout(() => {
    		  this.$router.push({
    			  ...this.viewList[index]
    		  });
    		  clearTimeout(timer);
    		  timer = null;
    	  }, 0)
      }
    },
    removeItem(path, newUrl) {
      let index = this.pathList.indexOf(path);
      if (index > -1) {
        this.pathList.splice(index, 1);
        this.viewList.splice(index, 1);
      }
      const len = this.pathList.length;
      if (this.$route.path === path) {
        if (index >= len) {
          index --;
        } else if(len === 0) {
          return false;
        }
        let timer = setTimeout(() => {
          if(newUrl){
            this.$router.push(newUrl);
          }else{
            this.$router.push({
              ...this.viewList[index]
            });
          }
          clearTimeout(timer);
          timer = null;
        }, 0)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.fbg {
  &-tabs {
    padding: 0px 30px;
    height: 32px;
    line-height: 32px;
    -moz-user-select:none; /*火狐*/
    -webkit-user-select:none; /*webkit浏览器*/
    -ms-user-select:none; /*IE10*/
    -khtml-user-select:none; /*早期浏览器*/
    user-select:none;

    .active {
      background-color: $themeDimColor;
      color: $themeColor;
      .fbg-tabs-item-close,.fbg-tabs-item-refresh{
        display: inline-block;
        font-size: 12px;
        border-radius: 4px;
        color: #606266;
        background-color: transparent;
        height: 16px;
        line-height: 15px;
        width: 16px;
        border-radius: 4px;
        position: absolute;
        top: 8px;
        text-align: center;
      }
      .fbg-tabs-item-refresh{
        right: 25px;
        top: 7px;
        .el-icon-refresh{
          &::before{
            font-size: 14px;
          }
        }
        &:hover{
          color: #fefefe !important;
          background-color: #5a76e4 !important;
          display: inline-block !important;
        }
      }
    }
    &-item {
	  transition: background-color 0.5s;
      cursor: pointer;
      &:first-child {
        border-left: 1px solid rgba(0,0,0, 0.1);
      }
      .fbgicon-icon{
        position: relative;
        top: -1px;
        font-size:12px;
      }
	  background-color: #ffffff;
      display: inline-block;
      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;
      overflow: hidden;
      &:hover {
        background-color: $themeDimColor;
        color: $themeColor;
      }
      &-close{
        position: absolute;
        right: 6px;
	    display: inline-block;
	    font-size: 12px;
	    border-radius: 4px;
	    color: #606266;
	    background-color: transparent;
	    height: 16px;
	    line-height: 15px;
	    width: 16px;
	    top: 8px;
	    text-align: center;

        i {
          font-size: 12px;
        }

		  &:hover{
			  color: #fefefe !important;
			  background-color: $themeColor !important;
			  display: inline-block !important;
		  }
      }
      i {
        vertical-align: middle;
        font-size: 15px;
        margin-top: -3px;
      }
      span {
        margin-left: 5px;
        font-size: 12px;
      }
    }
    box-shadow: 1px 0px 5px $themeShadowColor;
  }
}
</style>
