<template>
  <div id="tags-view-container" class="tags-view-container">
    <el-tabs type="border-card" class="demo-tabs" v-model="tabsName">
      <el-tab-pane v-for="tag in visitedViews" :key="tag.path" :name="tag.name">
        <template #label>
          <router-link
            v-show="!tag.hidden"
            :data-path="tag.path"
            :to="{ path: tag.path, query: tag.query, fullPath: tag.fullPath }"
            @click.middle="
              !isAffix(tag) ? closeSelectedTag(tag) : ''
            "
            @contextmenu.prevent="openMenu(tag, $event)"
          >
            <svg-icon icon-class="staging" v-if="tag.path === '/index'" />
            {{ 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>
        </template>
      </el-tab-pane>
    </el-tabs>
    <el-tooltip
      class="box-item"
      effect="dark"
      content="关闭当前所有打开页面！"
      placement="bottom"
    >
      <span class="closeSwitichBig" @click="closeAllTags(selectedTag)">
        <span class="closeSwitichSmall">
          <close class="el-icon-close" style="width: 1em; height: 1em;vertical-align: middle;" />
        </span>
      </span>
    </el-tooltip>
    <!-- <scroll-pane ref="scrollPaneRef" class="tags-view-wrapper" @scroll="handleScroll">
      <router-link
        v-for="tag in visitedViews"
        v-show="!tag.hidden"
        :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)"
      >
        <svg-icon icon-class="staging" v-if="tag.path === '/index'" />
        {{ 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-tooltip
        class="box-item"
        effect="dark"
        content="关闭当前所有打开页面！"
        placement="bottom"
       >
        <span class="closeSwitichBig" @click="closeAllTags(selectedTag)">
        <span class="closeSwitichSmall">
        <close class="el-icon-close" style="width: 1em; height: 1em;vertical-align: middle;" />
        </span>
      </span>
    </el-tooltip>
    </scroll-pane> -->
    <!-- <ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li @click="refreshSelectedTag(selectedTag)">
        <refresh-right style="width: 1em; height: 1em;" /> 刷新页面
      </li>
      <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>
      <li v-if="!isFirstView()" @click="closeLeftTags">
        <back style="width: 1em; height: 1em;" /> 关闭左侧
      </li>
      <li v-if="!isLastView()" @click="closeRightTags">
        <right style="width: 1em; height: 1em;" /> 关闭右侧
      </li>
      <li @click="closeAllTags(selectedTag)">
        <circle-close style="width: 1em; height: 1em;" /> 全部关闭
      </li>
    </ul> -->
  </div>
</template>

<script setup>
import ScrollPane from './ScrollPane'
import { getNormalPath } from '@/utils/cfhi'
import useTagsViewStore from '@/store/modules/tagsView'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'

const visible = ref(false);
const top = ref(0);
const left = ref(0);
const selectedTag = ref({});
const affixTags = ref([]);
const scrollPaneRef = ref(null);

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const tabsName = ref(null)

const visitedViews = computed(() => useTagsViewStore().visitedViews);
const routes = computed(() => usePermissionStore().routes);
const theme = computed(() => useSettingsStore().theme);

watch(route, () => {
  addTags()
  // moveToCurrentTag()
})
watch(visible, (value) => {
  if (value) {
    document.body.addEventListener('click', closeMenu)
  } else {
    document.body.removeEventListener('click', closeMenu)
  }
})
onMounted(() => {
  initTags()
  addTags()
})

function isActive(r) {
  return r.path === route.path
}
function activeStyle(tag) {
  if (!isActive(tag)) return {};
  return {
    "background-color": '#fff',
    // "border-bottom": '2px solid ' + theme.value,
    // "border-color": theme.value,
    "color": theme.value,
  };
}
function isAffix(tag) {
  return tag.meta && tag.meta.affix
}
function isFirstView() {
  try {
    return selectedTag.value.fullPath === '/index' || selectedTag.value.fullPath === visitedViews.value[1].fullPath
  } catch (err) {
    return false
  }
}
function isLastView() {
  try {
    return selectedTag.value.fullPath === visitedViews.value[visitedViews.value.length - 1].fullPath
  } catch (err) {
    return false
  }
}
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,
        hidden: route.hidden,
        meta: { ...route.meta }
      })
    }
    if (route.children) {
      const tempTags = filterAffixTags(route.children, route.path)
      if (tempTags.length >= 1) {
        tags = [...tags, ...tempTags]
      }
    }
  })
  return tags
}
function initTags() {
  const res = filterAffixTags(routes.value);
  affixTags.value = res;
  for (const tag of res) {
    // Must have tag name
    if (tag.name) {
       useTagsViewStore().addVisitedView(tag)
    }
  }
}
function addTags() {
  const { name } = route
  tabsName.value = name
  // 详情页不展示
  // let list = []
  // getAddRouteTags(routes.value, list)
  if (name) {
    // useTagsViewStore().addView(list[0])
    useTagsViewStore().addView(route)
    if (route.meta.link) {
      useTagsViewStore().addIframeView(route);
    }
  }
  return false
}
function getAddRouteTags (list, arr) {
  let data = null
  list.forEach(item => {
    if (item.children && item.children.length > 0) {
      if (item.name === route.name) {
        data = {
          ...route,
          hidden: item.hidden
        }
      } else {
        getAddRouteTags(item.children, arr)
      }
    } else {
      if (item.name === route.name) {
        data = {
          ...route,
          hidden: item.hidden
        }
      } 
    }
  })
  if (data) {
    arr.push(data)
  }
  return arr
}
function moveToCurrentTag() {
  nextTick(() => {
    for (const r of visitedViews.value) {
      if (r.path === route.path) {
        scrollPaneRef.value.moveToTarget(r);
        // when query is different then update
        if (r.fullPath !== route.fullPath) {
          useTagsViewStore().updateVisitedView(route)
        }
      }
    }
  })
}
function refreshSelectedTag(view) {
  proxy.$tab.refreshPage(view);
  if (route.meta.link) {
    useTagsViewStore().delIframeView(route);
  }
}
function closeSelectedTag(view) {
  proxy.$tab.closePage(view).then(({ visitedViews }) => {
    if (isActive(view)) {
      toLastView(visitedViews, view)
    }
  })
}
function closeRightTags() {
  proxy.$tab.closeRightPage(selectedTag.value).then(visitedViews => {
    if (!visitedViews.find(i => i.fullPath === route.fullPath)) {
      toLastView(visitedViews)
    }
  })
}
function closeLeftTags() {
  proxy.$tab.closeLeftPage(selectedTag.value).then(visitedViews => {
    if (!visitedViews.find(i => i.fullPath === route.fullPath)) {
      toLastView(visitedViews)
    }
  })
}
function closeOthersTags() {
  router.push(selectedTag.value).catch(() => { });
  proxy.$tab.closeOtherPage(selectedTag.value).then(() => {
    moveToCurrentTag()
  })
}
function closeAllTags(view) {
  proxy.$tab.closeAllPage().then(({ visitedViews }) => {
    if (affixTags.value.some(tag => tag.path === route.path)) {
      return
    }
    toLastView(visitedViews, view)
  })
}
function toLastView(visitedViews, view) {
  const latestView = visitedViews.slice(-1)[0]
  if (latestView) {
    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
      router.replace({ path: '/redirect' + view.fullPath })
    } else {
      router.push('/')
    }
  }
}
function openMenu(tag, e) {
  const menuMinWidth = 105
  const offsetLeft = proxy.$el.getBoundingClientRect().left // container margin 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 = e.clientY
  visible.value = true
  selectedTag.value = tag
}
function closeMenu() {
  visible.value = false
}
function handleScroll() {
  closeMenu()
}
</script>

<style lang="scss">
.tags-view-container{
  height: 48px;
  width: 100%;
  position: relative;
  overflow: hidden;
  .demo-tabs{
    height: 48px;
    width: calc(100% - 48px);
    border: none;
    .el-tabs__header{
      height: 48px;
      .el-tabs__item{
        height: 49px;
        line-height: 48px;
        padding: 0 !important;
        a{
          display: block;
          height: 100%;
          width: 100%;
          padding: 0 20px;
        }
      }
    }
    .el-tabs__content{
      padding: 0;
    }
    .el-tabs__nav-prev{
      border-right: 1px solid #DFE1E4;
    }
    .el-tabs__nav-next{
      border-left: 1px solid #DFE1E4;
    }
    .el-tabs__nav-next,.el-tabs__nav-prev{
      line-height: 50px;
    }
  }
  .closeSwitichBig{
    cursor:pointer;
    display: inline-block;
    font-size: 18px;
    font-weight: 400;
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    width: 48px;
    line-height: 48px;
    text-align: center;
    border-left: 1px solid #DFE1E4;
    border-bottom: 1px solid #DFE1E4;
    color: #aeb0b4;
    background-color: #f5f7fa;
    z-index: 999;
    .closeSwitichSmall{
      display: inline-block;
      height: 100%;
      width: 48px;
      line-height: 48px;
    }
  }
  .closeSwitichBig:hover{
    color: #8e8e91;
    background:#f6f6f9;
  }
}
.el-icon-close {
  width: 16px !important;
  height: 16px !important;
  vertical-align: -4px !important;
  border-radius: 50%;
  text-align: center;
  font-size: 16px;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  transform-origin: 100% 50%;
  color: rgba(179, 183, 190, 1);
  &:hover {
    color: var(--el-color-primary);
  }
}
</style>
