<template>
  <div class="multiple_tag">
    <el-tabs
      v-model="currentTag"
      class="tag-tabs"
      type="card"
      @tab-click="tabClick"
      @tab-remove="tabRemove"
    >
      <el-tab-pane
        v-for="item in permStore.multipleTag"
        :closable="item.path !== '/home'"
        :key="item.id || item.path"
        :label="item.meta?.name || ''"
        :name="item.path"
      />
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
import { useUserStore } from '@/stores/user'
import { routeWithParams } from '@/utils/tag'

const route = useRoute()
const router = useRouter()
const permStore = usePermissionStore()
const userStore = useUserStore()

const currentTag = computed({
  get: () => permStore.curTag,
  set: () => {}
})

const curTheme = computed(() => userStore.curTheme)

function tabClick(tab: any) {
  const path = tab.props.name
  permStore.SET_CUR_TAG(path)
  if (routeWithParams.includes(path)) {
    const id = route.query.id
    if (id) localStorage.setItem(path, String(id))
    router.push({ path, query: { id: localStorage.getItem(path) || undefined } })
  } else {
    router.push(path)
  }
}

function tabRemove(name: string) {
  const tags = [...permStore.multipleTag]
  const index = tags.findIndex((item: any) => item.path === name)
  const toRouter = tags[index - 1]
  tags.splice(index, 1)
  permStore.SET_MULTIPLE_TAG(tags)
  if (name === route.path) {
    permStore.SET_CUR_TAG(toRouter.path)
    router.push(toRouter.path)
  }
}
</script>

<style scoped lang="less">
.multiple_tag {
  position: relative;
  z-index: 1;

  :deep(.tag-tabs) {
    &.el-tabs {
      .el-tabs__header {
        margin: 0;
        border: none;

        .el-tabs__nav-wrap {
          &.is-scrollable {
            padding: 0 50px;
          }

          .el-tabs__nav {
            border: none;

            .el-tabs__item {
              border: none;
              margin-bottom: -1px;
              position: relative;
              z-index: 1;
              color: #fff;
              opacity: 0.7;
              font-weight: normal;

              &.is-active {
                opacity: 1;
                border-radius: 6px 6px 0 0;
                font-weight: bold;

                &::after {
                  content: '';
                  display: block;
                  position: absolute;
                  bottom: 2px;
                  height: 3px;
                  width: calc(100% - 60px);
                  left: 30px;
                  border-radius: 8px;
                  background: #fff;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
