<template>
  <div class="app-layout">
    <Header @toggle-sidebar="toggleSidebar" />
    <div class="main">
      <div class="sidebar" :class="{ collapse: collapsed }" v-if="routeStore.sideRoutes.length > 0">
        <div class="collapse-btn corlor-place w-ra-100 flex gap-6 start h-44 fs-12 pl-25">
          <el-icon @click="toggleSidebar" :size="14">
            <component :is="collapsed ? Expand : Fold" />
          </el-icon>
          <span class="txt" :class="{ transparent: collapsed }">收起导航</span>
        </div>

        <NavBar ref="sideBarRef" class="side-menu w-ra-100" :routes="routeStore.sideRoutes"
          :activeMenu="routeStore.activeSideRoute?.path" :isIcon="false" />
      </div>

      <div class="content px-16 pb-16">
        <div class="content-header my-16">
          <el-icon class="tabs-arrow left" :class="{ disabled: !canScrollLeft }" @click="scrollTabs('left')">
            <ArrowLeft />
          </el-icon>

          <div ref="tabsWrapRef" class="route-tabs" @scroll="syncScrollState">
            <div v-for="tab in routeTabs" :key="tab.path" class="route-tab"
              :class="{ active: tab.path === activeTabPath }" @click="goTab(tab.path)">
              <span class="tab-title">{{ tab.title }}</span>
              <el-icon v-if="tab.closable && routeTabs.length > 1" class="tab-close" @click.stop="closeTab(tab)">
                <Close />
              </el-icon>
            </div>
          </div>

          <el-icon class="tabs-arrow right" :class="{ disabled: !canScrollRight }" @click="scrollTabs('right')">
            <ArrowRight />
          </el-icon>
        </div>
        <!-- 主显示区域 -->
        <slot />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import Header from './header.vue'
import NavBar from '@/components/navBar/NavBar.vue'
import { Fold, Expand, Close, ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { useRouteSync } from '@/composables/useRouteSync'
const route = useRoute()
const router = useRouter()
const routeStore = useRouteSync()

const routeTabs = ref([])
const tabsWrapRef = ref(null)
const canScrollLeft = ref(false)
const canScrollRight = ref(false)

const activeTabPath = computed({
  get() {
    const path = route.fullPath || route.path;
    if(path === '/shop/home') {
      return '/shop/index'
    }
    return path;
  }
})

const currentRouteInfo = computed(() => {
  const matched = [...route.matched].reverse().find((r) => r.meta?.title) || route.matched[route.matched.length - 1]
  let title = matched?.meta?.title || route.meta?.title || ''
  const hidden = matched?.meta?.hidden ?? false
  let path = route.fullPath || route.path
  if(hidden) {
    if(path === '/shop/home') {
      path = '/shop/index',
      title = '页面管理'
    } 
  }
  
  if (!title) return null

  return {
    title,
    path,
    closable: (matched?.meta?.closable ?? true), //&& route.path !== '/home'
  }
})

watch(
  currentRouteInfo,
  (tab) => {
    console.log('咋不对呢',tab);
    
    if (!tab) return

    const exists = routeTabs.value.some((item) => item.path === tab.path)
    if (!exists) {
      routeTabs.value.push(tab)
    }
    nextTick(() => {
      scrollActiveTabIntoView()
      syncScrollState()
    })
  },
  { immediate: true },
)
const syncScrollState = () => {
  const el = tabsWrapRef.value
  if (!el) return

  canScrollLeft.value = el.scrollLeft > 0
  canScrollRight.value = el.scrollLeft + el.clientWidth < el.scrollWidth - 1
}

const scrollTabs = (direction) => {
  const el = tabsWrapRef.value
  if (!el) return

  const distance = 220
  el.scrollBy({
    left: direction === 'left' ? -distance : distance,
    behavior: 'smooth',
  })
}

const scrollActiveTabIntoView = () => {
  const el = tabsWrapRef.value
  if (!el) return

  const activeTab = el.querySelector('.route-tab.active')
  activeTab?.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' })
}

let resizeObserver = null

onMounted(() => {
  nextTick(() => {
    syncScrollState()
    scrollActiveTabIntoView()
  })

  if (window.ResizeObserver && tabsWrapRef.value) {
    resizeObserver = new ResizeObserver(() => {
      syncScrollState()
    })
    resizeObserver.observe(tabsWrapRef.value)
  }
})

onBeforeUnmount(() => {
  resizeObserver?.disconnect()
})

const goTab = (path) => {
  if (path && path !== route.fullPath) {
    router.push(path)
  }
}

const closeTab = (tab) => {
  if (routeTabs.value.length <= 1) return

  const tabs = routeTabs.value
  const index = tabs.findIndex((item) => item.path === tab.path)
  if (index < 0) return

  tabs.splice(index, 1)

  if (tab.path === route.fullPath) {
    const nextTab = tabs[index] || tabs[index - 1] || tabs[0]
    if (nextTab) {
      router.push(nextTab.path)
    } else {
      router.push('/home')
    }
  }
}

const sideBarRef = ref(null)
const collapsed = ref(false)

const toggleSidebar = () => {
  collapsed.value = !collapsed.value
}

</script>

<style scoped lang="scss">
:deep(.el-icon) {
  cursor: pointer;
}

.app-layout {
  width: 100vw;
  height: 100vh;


  .main {
    display: flex;
    overflow: hidden;
    background: var(--bg-color-page);
    height: calc(100vh - 60px);
    overflow: hidden;

    .sidebar {
      width: 160px;
      height: calc(100vh - 60px);
      background-color: var(--bg-color-container);

      transition: 0.2s all linear;

      &.collapse {
        width: 64px;

        :deep(.el-menu-item) {
          padding-left: 10px !important;

          &:hover span {
            overflow: visible;
            text-overflow: clip;
            max-width: none;
            position: absolute;
            top: 50%;
            left: 36px;
            transform: translateY(-50%);
            padding: 0 10px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
            z-index: 20;
          }
        }
      }

      .collapse-btn {
        border-bottom: 1px solid var(--component-stroke);

        .txt {
          transition: 0.2s all linear;
          white-space: nowrap;
          display: inline-block;
          opacity: 1;

          &.transparent {
            opacity: 0;
          }
        }
      }

      .side-menu {
        transition: width 0.3s;
        padding: 16px 8px;
        border-right: none;
        background: transparent;

        :deep(.el-menu-item),
        :deep(.el-sub-menu__title) {
          width: 100%;
          position: relative;
          overflow: visible;

          span {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            vertical-align: middle;
          }

        }

        :deep(.el-menu-item) {
          transition: 0.2s all linear;
          padding-left: 20px;
          border-radius: 3px;
          color: var(--text-color-secondary);

          &:hover {
            background-color: var(--brand-color-light);
          }

          &.is-active {
            background-color: var(--brand-color);
            color: var(--text-color-primary);
          }
        }
      }


      &.collapse {
        width: 64px;
      }
    }

    .content {
      height: 100%;
      overflow: auto;
      flex: 1;

      .content-header {
        display: flex;
        align-items: center;
        gap: 10px;
        background-color: var(--bg-color-container);
        height: 44px;
        overflow: hidden;
        border-radius: 6px;

        .tabs-arrow {
          flex: 0 0 auto;
          width: 44px;
          height: 100%;
          border-radius: 0;
          background: var(--bg-color-container);
          color: #666;
          border: none;
          z-index: 1;

          :deep(svg) {
            width: 14px;
            height: 14px;
          }

          &.disabled {
            color: #c9cdd4;
            cursor: not-allowed;
            pointer-events: none;
            opacity: 0.7;
          }

          &.left {
            box-shadow: 6px 0 14px rgba(0, 0, 0, 0.08);
          }

          &.right {
            box-shadow: -6px 0 14px rgba(0, 0, 0, 0.08);
          }
        }

        .route-tabs {
          display: flex;
          align-items: center;
          // gap: 12px;
          flex: 1;
          min-width: 0;
          overflow-x: auto;
          padding-bottom: 0;
          scrollbar-width: none;
          height: 100%;

          &::-webkit-scrollbar {
            display: none;
          }

          .route-tab {
            flex: 0 0 auto;
            display: inline-flex;
            align-items: center;
            height: 100%;
            padding: 0 6px;
            border-bottom: 2px solid transparent;
            border-radius: 0;
            background: transparent;
            color: var(--text-color-secondary);
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
              color: var(--brand-color-hover);
              border-bottom-color: var(--brand-color-hover);
            }

            &.active {
              color: var(--brand-color);
              border-bottom-color: var(--brand-color);
              font-weight: 600;
            }
          }
        }

        .tab-title {
          line-height: 1;
          display: inline-flex;
          align-items: center;
          height: 100%;
        }

        .tab-close {
          margin-left: 8px;
          font-size: 12px;
          color: #999;

          &:hover {
            color: var(--brand-color);
          }
        }
      }
    }
  }
}
</style>
