<template>
  <div id="tags-view-container" class="navbar-tag">
    <div @click="$baseEventBus.$emit('triggerMenu')" class="telescopMenuIcon"><i class="iconfont" :class="isMenu?'icon-shouqi':'icon-shouqi-copy'"></i></div>
    <scroll-pane ref="scrollPane" class="tags-view-wrapper" @scroll="handleScroll">
      <router-link
        v-for="tag in visitedViews"
        ref="tag"
        :key="tag.path"
        :class="isActive(tag)?'active':''"
        :to="{ path: tag.path, query: tag.query, fullPath: tag.fullPath }"
        tag="span"
        class="tags-view-item"
        @click.middle.native="!isAffix(tag)?closeSelectedTag(tag):''"
        @contextmenu.prevent.native="openMenu(tag,$event)"
      >
        <i class="el-icon-s-home" v-if="tag.name =='home'"></i>
        {{ getMenuName(tag) }}

        <span v-if="!!tag.meta.user_affix" class="el-icon-close is-disabled"/>
        <span v-else-if="!isAffix(tag)" class="el-icon-close" @click.prevent.stop="closeSelectedTag(tag)"/>
      </router-link>
    </scroll-pane>
    <div class="tags-operBox">
      <el-tooltip :enterable="false" class="item" effect="dark" :content="$t1('左移')" placement="bottom">
        <i class="el-icon-arrow-left" layadmin-event="leftPage"
           one-link-mark="yes" @click="$refs.scrollPane.handleScrollLeft()"/>
      </el-tooltip>
      <el-tooltip :enterable="false" class="item" effect="dark" :content="$t1('右移')" placement="bottom" l>
        <i class="el-icon-arrow-right" ayadmin-event="rightPage"
           one-link-mark="yes" @click="$refs.scrollPane.handleScrollRight()"/>
      </el-tooltip>
      <el-dropdown >
        <span class="el-dropdown-link" style="padding-right:10px;padding-left:4px;">
          <i class="el-icon-more el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="refreshSelectedTag($route)" :disabled="getIsLock()">
            <i class="el-icon-refresh"/><span>{{ $t1('刷新') }}</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="closeAllTags(selectedTag)">
            <i class="el-icon-close"/><span>{{ $t1('全部关闭') }}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- <el-tooltip :enterable="false" class="item" effect="dark" :content="$t1('刷新')" placement="bottom">
        <i class="el-icon-refresh" @click="refreshSelectedTag($route)"/>
      </el-tooltip>
      <el-tooltip :enterable="false" class="item" effect="dark" :content="$t1('全部关闭')" placement="bottom">
        <i class="el-icon-close" @click="closeAllTags(selectedTag)"/>
      </el-tooltip> -->
    </div>
    <!-- <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
      <li @click="refreshSelectedTag(selectedTag)">Refresh</li>
      <li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">Close</li>
      <li @click="closeOthersTags">Close Others</li>
      <li @click="closeAllTags(selectedTag)">Close All</li>
    </ul> -->
  </div>
</template>

<script>
import ScrollPane from './ScrollPane'
import path from 'path'

export default {
  components: {ScrollPane},
  props: {
    isMenu: {
      type: Boolean
    }
  },
  data() {
    return {
      visible: false,
      top: 0,
      left: 0,
      selectedTag: {},
      affixTags: []
    }
  },
  computed: {
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    },
    routes() {
      return this.$store.state.permission.routes
    }
  },
  watch: {
    $route() {
      this.addTags()
      this.moveToCurrentTag()
    },
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  mounted() {
    this.initTags()
    this.addTags()
  },
  methods: {
    getMenuName(item) {
      let locale = this.$i18n?.locale;
      let zhTitle = item.meta?.title || "";
      let enTitle = item.meta?.enTitle || '';
      let title;
      if (locale == "en") {
        title = enTitle || zhTitle;
      } else {
        title = zhTitle
      }
      if (!enTitle || locale !== "en") {
        title = zhTitle
      }
      if (this.$t1) {
        title = this.$t1(title)
      }
      return title;
    },
    isActive(route) {
      return route.path === this.$route.path
    },
    isAffix(tag) {
      return tag.meta && tag.meta.affix
    },
    filterAffixTags(routes, basePath = '/') {
      let tags = []
      routes.forEach(route => {
        if (route.meta && route.meta.affix) {
          const tagPath = path.resolve(basePath, route.path)
          tags.push({
            fullPath: tagPath,
            path: tagPath,
            name: route.name,
            meta: {...route.meta}
          })
        }
        if (route.children) {
          const tempTags = this.filterAffixTags(route.children, route.path)
          if (tempTags.length >= 1) {
            tags = [...tags, ...tempTags]
          }
        }
      })
      return tags
    },
    initTags() {
      const affixTags = this.affixTags = this.filterAffixTags(this.routes)
      for (const tag of affixTags) {
        // Must have tag name
        if (tag.name) {
          this.$store.dispatch('tagsView/addVisitedView', tag)
        }
      }
    },
    addTags() {
      const {name} = this.$route
      if (name) {
        this.$store.dispatch('tagsView/addView', this.$route)
      }
      return false
    },
    moveToCurrentTag() {
      const tags = this.$refs.tag
      this.$nextTick(() => {
        for (const tag of tags) {
          if (tag.to.path === this.$route.path) {
            this.$refs.scrollPane.moveToTarget(tag)
            // when query is different then update
            if (tag.to.fullPath !== this.$route.fullPath) {
              this.$store.dispatch('tagsView/updateVisitedView', this.$route)
            }
            break
          }
        }
      })
    },
    refreshSelectedTag(view) {
      this.$baseEventBus.$emit("reflushRouteView", view);
      /* if(this.$route.name=="outLink"){
        let a = this.$baseEventBus.$emit("getAppMain");
        let t = this.$parent.$refs["appMain"].$refs["ref_"+this.$route.path][0];
        t.$baseReload();
      }else{
        this.$store.dispatch('tagsView/delCachedView', view).then(() => {
          const { fullPath } = view
          this.$nextTick(() => {
            this.$router.replace({
              path: '/redirect' + fullPath
            })
          })
        })
      } */
    },
    closeSelectedTag(view) {
      if(view.meta.user_affix)return
      this.$store.dispatch('tagsView/delView', view).then(({visitedViews}) => {
        if (this.isActive(view)) {
          this.toLastView(visitedViews, view)
        }
      })
    },
    closeOthersTags() {
      this.$router.push(this.selectedTag)
      this.$store.dispatch('tagsView/delOthersViews', this.selectedTag).then(() => {
        this.moveToCurrentTag()
      })
    },
    closeAllTags(view) {
      this.$baseConfirm(this.$t1('您确定要全部关闭吗？')).then(() => {
        this.$store.dispatch('tagsView/delAllViews').then(({visitedViews}) => {
          if (this.affixTags.some(tag => tag.path === view.path)) {
            return
          }
          this.toLastView(visitedViews, view)
        })
      })
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        this.$router.push(latestView.fullPath)
      } else {
        // now the default is to redirect to the home page if there is no tags-view,
        // you can adjust it according to your needs.
        if (view.name === 'Dashboard') {
          // to reload home page
          this.$router.replace({path: '/redirect' + view.fullPath})
        } else {
          this.$router.push('/')
        }
      }
    },
    openMenu(tag, e) {
      const menuMinWidth = 105
      const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
      const offsetWidth = this.$el.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft + 15 // 15: margin right

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }

      this.top = e.clientY
      this.visible = true
      this.selectedTag = tag
    },
    closeMenu() {
      this.visible = false
    },
    handleScroll() {
      this.closeMenu()
    },
    getIsLock() {
      let path = this.$route.path;
      let visitedViews = this.$store.state.tagsView.visitedViews
      let currentItem = visitedViews.find(item => item.path == path)
      return !!currentItem?.meta?.user_affix;
    },
  }
}
</script>

<style scoped lang="scss">
@import '~@/styles/variables.scss';

.navbar-tag .tags-view-item.active {
  background: $baseColor !important;
}
</style>
<style lang="scss">
//reset element css of el-icon-close
span.el-icon-close.is-disabled{
  cursor: not-allowed;
}
.tags-view-wrapper {
  .tags-view-item {
    .el-icon-close {
      width: 14px;
      height: 14px;
      vertical-align: text-bottom;
      line-height: 12px;
      border-radius: 50%;
      text-align: center;
      transition: all .3s cubic-bezier(.645, .045, .355, 1);
      transform-origin: 100% 50%;
      display: none;
      position: absolute;
      right: 12px;
      top: 8px;

      &:before {
        transform: scale(.84);
        display: inline-block;
        vertical-align: -1.8px;
      }
    }

    &:hover .el-icon-close {
      display: block;
    }
  }
}
</style>
