
<template>
    <div class="tjm_tabsbar_container">
        <el-scrollbar
            ref="scrollContainer"
            :vertical="false"
            class="tjm_tabs-content"
            @wheel.prevent="handleScroll"
        >
            <router-link
                v-for="tag in visitedViews"
                :key="tag.path"
                :data-path="tag.path"
                :class="isActive(tag) ? 'active' : ''"
                :to="{ path: tag.path, query: tag.query, fullPath: tag.fullPath }"
                class="tags-view-item"
                :style="activeStyle(tag)"
                @click.middle="!isAffix(tag) ? closeSelectedTag(tag) : ''"
                @contextmenu.prevent="openMenu(tag, $event)"
            >
                {{ tag.title }}
                <span v-if="!isAffix(tag)" @click.prevent.stop="closeSelectedTag(tag)">
                <close
                    class="el-icon-close"
                    style="width: 1em; height: 1em; vertical-align: middle"
                />
                </span>
            </router-link>
        </el-scrollbar>
        <ul
            v-show="visible"
            :style="{ left: left + 'px', top: top + 'px' }"
            class="contextmenu"
        >
            <li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">
                <close style="width: 1em; height: 1em;" /> 关闭当前
            </li>
            <li @click="closeOthersTags">
                <circle-close style="width: 1em; height: 1em;" /> 关闭其他
            </li>
        </ul>
    </div>
</template>

<script setup>
import { useTabsBarStore } from '@/store/tabsbar.js'
import { usePermissionStore } from '@/store/permission.js'
import { useSettingStore } from '@/store/settings.js'
const routes = computed(() => usePermissionStore().routes)
const route = useRoute()
const router = useRouter()

//==================================================
const visitedViews = computed(() => useTabsBarStore().visitedViews)
const affixTags = ref([])
const visible = ref(false)
const theme = computed(() => useSettingStore().theme)
const top = ref(0)
const left = ref(0)
const selectedTag = ref({})

const { proxy } = getCurrentInstance()
watch(route, () => {
    addTags()
    // moveToCurrentTag()
})
onMounted(() => {
    initTags()
    addTags()
})


function addTags() {
    const { name } = route
    if (name) {
        useTabsBarStore().addView(route)
    }
    return false
}

function initTags() {
    const res = filterAffixTags(routes.value)
    affixTags.value = res
    for (const tag of res) {
        if (tag.name) {
            useTabsBarStore().addVisitedView(tag)
        }
    }
}

function moveToCurrentTag() {
    nextTick(() => {
        for (const r of visitedViews.value) {
            if (r.path === route.path) {
                scrollPaneRef.value.moveToTarget(r)
                if (r.fullPath !== route.fullPath) {
                    useTagsViewStore().updateVisitedView(route)
                }
            }
        }
    })
}

function filterAffixTags(routes, basePath = '') {
    let tags = []
    routes.forEach(route => {
        if (route.meta && route.meta.affix) {
            const tagPath = getNormalPath(basePath + '/' + route.path)
            tags.push({
                fullPath: tagPath,
                path: tagPath,
                name: route.name,
                meta: { ...route.meta }
            })
        }
        if (route.children) {
            const tempTags = filterAffixTags(route.children, route.path)
            if (tempTags.length >= 1) {
                tags = [...tags, ...tempTags]
            }
        }
    })
    return tags
}


function getNormalPath(p) {
    if (p.length === 0 || !p || p == 'undefined') {
        return p
    }
    let res = p.replace('//', '/')
    if (res[res.length - 1] === '/') {
        return res.slice(0, res.length - 1)
    }
    return res
}



function closeMenu() {
    visible.value = false
}

function handleScroll() {
    closeMenu()
}
watch(visible, (value) => {
    if (value) {
        document.body.addEventListener('click', closeMenu)
    } else {
        document.body.removeEventListener('click', closeMenu)
    }
})

function openMenu(tag, e) {
    const menuMinWidth = 105
    const offsetLeft = proxy.$el.getBoundingClientRect().left
    const offsetWidth = proxy.$el.offsetWidth // container width
    const maxLeft = offsetWidth - menuMinWidth // left boundary
    const l = e.clientX - offsetLeft + 15 // 15: margin right

    if (l > maxLeft) {
        left.value = maxLeft
    } else {
        left.value = l
    }

    top.value = 15
    visible.value = true
    selectedTag.value = tag

}


function isActive(r) {
    return r.path === decodeURIComponent(route.path)
}



function activeStyle(tag) {
    if (!isActive(tag)) return {}
    return {
        'background-color': theme.value,
        'border-color': theme.value
    }
}

function isAffix(tag) {
    // if(tag.name=="Index") return true
    return tag.meta && tag.meta.affix
}

function closeSelectedTag(view) {
    useTabsBarStore()
        .delView(view)
        .then(({ visitedViews }) => {
            if (isActive(view)) {
                toLastView(visitedViews, view)
            }
        })
}
function closeOthersTags() {
    useTabsBarStore().delOthersViews(selectedTag.value).then(({ visitedViews }) => {
        toLastView(visitedViews, selectedTag.value)
    })
}
function toLastView(visitedViews, view) {
    const latestView = visitedViews.slice(-1)[0]
    if (latestView) {
        router.push(latestView.fullPath)
    } else {
        if (view.name === 'Index') {
            router.replace({ path: '/redirect' + view.fullPath })
        } else {
            router.push('/')
        }
    }
}
</script>
 
<style lang="scss" scoped>
.tjm_tabsbar_container {
  position: relative;
  height: $base-tabsbar-height;
  user-select: none;
  border-top: 1px solid #f6f6f6;
  display: flex;
  align-items: center;
  padding-right: $base-padding;
  padding-left: $base-padding;
  background: $base-color-white;
  white-space: nowrap;
  .tjm_tabs-content {
    height: 40px;
    width: 100%;
    // display: flex;
    // align-items: center;
    .tags-view-item {
      display: inline-block;
      position: relative;
      cursor: pointer;
      height: 26px;
      line-height: 26px;
      border: 1px solid #d8dce5;
      color: #495060;
      background: #fff;
      padding: 0 8px;
      font-size: 12px;
      margin-left: 5px;
      margin-top: 4px;
      text-decoration: none;
      &:hover {
        border: 1px solid #409eff;
      }
      &:first-of-type {
        margin-left: 15px;
      }
      &:last-of-type {
        margin-right: 15px;
      }
      &.active {
        background-color: #42b983;
        color: #fff;
        border-color: #42b983;

        &::before {
          content: '';
          background: #fff;
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          position: relative;
          margin-right: 5px;
        }
      }
    }
  }
  .contextmenu {
    margin: 0;
    background: #fff;
    position: absolute;
    z-index: 3000;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 400;
    color: #333;
    box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
    li {
      margin: 0;
      padding: 7px 16px;
      cursor: pointer;
      &:hover {
        background: #eee;
      }
    }
  }
}
</style>
<style lang="scss">
.tjm_tabs-content {
  a {
    text-decoration: none;
  }
  .router-link-active {
    text-decoration: none;
  }
  .el-icon-close {
    width: 16px;
    height: 16px;
    vertical-align: 2px;
    border-radius: 50%;
    text-align: center;
    transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
    transform-origin: 100% 50%;
    &:before {
      transform: scale(0.6);
      display: inline-block;
      vertical-align: -3px;
    }
    &:hover {
      background-color: #b4bccc;
      color: #fff;
      width: 12px !important;
      height: 12px !important;
    }
  }
}
</style>
