<template>
  <div class="elrow-top" :class="elrowtop">
    <el-row justify="center">
      <el-col :span="6" v-if="windowwidth">
        <div class="grid-content ep-bg-purple-dark">
          <div class="logo-text">清疯不颠</div>
        </div>
      </el-col>
      <el-col :span="14" justify="center">
        <div class="grid-content ep-bg-purple-dark">
          <el-menu :default-active="activeIndex" class="el-menu-demo" :collapse="false" @select="handleSelect">
            <el-menu-item index="home">
              首页
            </el-menu-item>
            <el-menu-item index="article-list">
              目录
            </el-menu-item>
            <el-menu-item index="nonsense">
              疯言疯语
            </el-menu-item>
            <el-menu-item index="about">
              关于
            </el-menu-item>
            <el-menu-item index="message">
              留言板
            </el-menu-item>
          </el-menu>
        </div>
      </el-col>
      <el-col :span="2" class="search-container" v-if="windowwidth">
        <!-- 搜索功能 -->
        <div class="search-wrapper">
          <button class="search-icon-btn" @click="toggleSearchBox" :class="{ 'active': isSearchBoxOpen }">
            <svg t="1761567058506" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5586" width="32" height="32"><path d="M512 858.3168c-194.816 0-352-166.2464-352-370.4832S317.184 117.3504 512 117.3504s352 166.2464 352 370.4832-157.184 370.4832-352 370.4832z m0-64c158.6688 0 288-136.8576 288-306.4832 0-169.6768-129.3312-306.4832-288-306.4832S224 318.1568 224 487.8336c0 169.6256 129.3312 306.4832 288 306.4832zM717.312 799.9488a32 32 0 0 1 46.4896-43.9808l91.4432 96.7168a32 32 0 0 1-46.4896 43.9808l-91.4432-96.768z" fill="#5A5A68" p-id="5587"></path></svg>
          </button>
          <div class="search-box-container" :class="{ 'open': isSearchBoxOpen }">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索文章..." 
              class="search-input"
              @keyup.enter="performSearch"
              @blur="closeSearchBoxWithDelay"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  
  <!-- Hero 区域 -->
  <div class="hero" :class="{ 'newhero': classhero }" v-if="windowwidth">
    <h1 class="typewriter">{{ heroText }}</h1>
  </div>

  <!-- 提示区域 -->
  <div id="content-section" :class="{ 'visible': isconts }">
    <div class="nonsensetitle" v-if="classnonsenset">
      <div class="nonsensetitleconst">
        <h1>{{Cardtitle}}</h1>
      </div>
    </div>
    
    <!-- 左侧模块 -->
     <div class="leftmodluecontainer" v-if="isleftmodluecontainer">
       <LeftModule class="leftmodluepage" :class="{ 'nonsensetmargintop': classnonsenset }" v-if="windowwidth"  />
     </div>
    
    <!-- 内容模块 -->
    <RouterView class="RouterViewpage" :class="{'forbidwidth': !isleftmodluecontainer, 'nonsensetmargintop': classnonsenset }" />
  </div>
  
  <!-- 分页区域 -->
  <div class="Pagination">
    <!-- 分页组件可以在这里添加 -->
  </div>
    <Establish class="establish-container" v-if="Login" />
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import LeftModule from '@/components/LeftModule.vue';
import Establish from '@/layouts/establish.vue'
// 路由相关
const router = useRouter();
const route = useRoute();
// 全局状态管理
import { useGlobalStore  } from '@/store/globalStore'
import { Card } from 'ant-design-vue';
const globalStore = useGlobalStore()
const Login = computed(() => globalStore.Login)

// 响应式状态
const Cardtitle = ref('');
const isleftmodluecontainer = ref(true);
const classhero = ref(false);
const isconts = ref(false);
const isScrollingleftmodlue = ref(false);
const elrowtop = ref('transparent');
const classnonsenset = ref(false);
const windowwidth = ref(true);
const activeIndex = ref('home');
const localhome= 'home';

let rpsliturl = route.path.split('/');

// 搜索相关状态
const isSearchBoxOpen = ref(false);
const searchKeyword = ref('');
let searchCloseTimer: number | undefined;

// 打字机效果相关
let fullHeroText = '清疯不颠';
const heroText = ref('');
let heroIndex = 0;
let heroTimer: number | undefined;

/**
 * 打字机效果函数
 */
const startTypewriter = () => {
  heroText.value = '';
  heroIndex = 0;
  if (heroTimer) clearInterval(heroTimer);
  heroTimer = window.setInterval(() => {
    if (heroIndex < fullHeroText.length) {
      heroText.value += fullHeroText[heroIndex];
      heroIndex++;
    } else {
      clearInterval(heroTimer);
    }
  }, 100);
};

/**
 * 菜单选择跳转
 */
const handleSelect = (key: string) => {
  // globalStore.clearAll()
  router.push({ path: '/' + key });
};

/**
 * 切换搜索框显示/隐藏
 */
const toggleSearchBox = () => {
  isSearchBoxOpen.value = !isSearchBoxOpen.value;
  
  // 如果打开搜索框，清除之前的延时关闭定时器
  if (isSearchBoxOpen.value && searchCloseTimer) {
    clearTimeout(searchCloseTimer);
  }
};

/**
 * 关闭搜索框
 */
const closeSearchBox = () => {
  isSearchBoxOpen.value = false;
};

/**
 * 带延迟关闭搜索框（处理点击搜索按钮后的情况）
 */
const closeSearchBoxWithDelay = () => {
  if (searchCloseTimer) {
    clearTimeout(searchCloseTimer);
  }
  
  searchCloseTimer = window.setTimeout(() => {
    isSearchBoxOpen.value = false;
  }, 300);
};

/**
 * 执行搜索操作
 */
const performSearch = () => {
  if (searchKeyword.value.trim()) {
  // 这里可以根据实际需求实现搜索逻辑
  // 存储文章信息到全局状态
  globalStore.setValue('articleserarch', {
    name: searchKeyword.value 
  })
    router.push({ path: `/home/aericletitle`});
  }
  
  // 搜索后保持搜索框打开状态
  if (searchCloseTimer) {
    clearTimeout(searchCloseTimer);
  }
};

/**
 * 根据路由路径设置页面状态
 */
const updatePageState = (url: string) => {
  classhero.value = url !== localhome;
  classnonsenset.value = url === 'nonsense';
};

/**
 * 设置当前激活的菜单项
 */
const setActiveIndex = (path: string) => { 
  // 存储文章信息到全局状态
  globalStore.setValue('localpath', {
    name: path
  })
  // console.log('设置激活索引:', path);
  if (path === 'message') {
    globalStore.removeValue('articleInfo')
  }
    activeIndex.value =path;
};



/**
 * 处理窗口大小变化
 */
const handleResize = () => {
  windowwidth.value = window.innerWidth > 768;
  
  // 根据屏幕大小调整内容区可见性
  if (rpsliturl[1] === localhome) {
    isconts.value = window.innerWidth <= 768 ? true : false;
  }
};

/**
 * 处理滚动事件
 */
const handleScroll = () => {
  // 屏幕小于768时只切换导航栏样式，不做内容动画
  if (window.innerWidth < 768) {
    elrowtop.value = window.scrollY > 100 ? 'solid' : 'transparent';
    return;
  }
  
  // 导航栏样式切换
  if (window.scrollY > 1200) {
    elrowtop.value = 'hide';
  } else {
    elrowtop.value = window.scrollY > 100 ? 'solid' : 'transparent';
  }
  
  // 首页内容区滚动动画
  if (rpsliturl[1] === localhome) {
    isconts.value = window.scrollY > 200;
    isScrollingleftmodlue.value = window.scrollY > 600;
  }
};

/**
 * 监听路由变化
 */
watch(() => route.path, () => {
  rpsliturl = route.path.split('/');
  updatePageState(rpsliturl[1]);
  setActiveIndex(rpsliturl[1]);
  
  console.log(rpsliturl[1])
  let articledata; 
    // 优先使用attributeId参数（新接口）
    if (rpsliturl[2]==='aericletype') {
      articledata = globalStore.getValue('attribute')
    }
    // 搜索标题
    if (rpsliturl[2]==='aericletitle') {
      articledata = globalStore.getValue('title')
    }
    if (rpsliturl[1]==='nonsense') {
      articledata = "疯言疯语"
    }
    // hero 标题
    if (articledata) {
      Cardtitle.value = articledata.name
      classhero.value = true;
    }
  // 跳转后回到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
  // 首页内容区滚动动画仅大屏下生效
  if (rpsliturl[1] === localhome && rpsliturl[2] == '') {
    // isconts.value = window.innerWidth <= 768 ? true : false;
    // 首页时启动打字机效果
    startTypewriter();
  } else {
    isconts.value = true;
    heroText.value =fullHeroText;
    if (heroTimer) clearInterval(heroTimer);
  }
  // 非首页时关闭左侧状态栏
  if (rpsliturl[1] == "articlesave") {
    isleftmodluecontainer.value = false;
  } else {
    isleftmodluecontainer.value = true;
  }
}, { immediate: true });

/**
 * 生命周期钩子
 */
onMounted(() => {
  // 初始化窗口大小


  handleResize();
  // 添加事件监听器
  window.addEventListener('resize', handleResize);
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize);
  window.removeEventListener('scroll', handleScroll);
  
  // 清理定时器
  if (heroTimer) clearInterval(heroTimer);
});
</script>

<style scoped>
/* 搜索框样式 */
.search-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  height: 100%;
}

.search-icon-btn {
  background: none;
  border: none;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
  /* padding: 8px; */
  border-radius: 4px;
  transition: all 0.3s ease;
}

.search-icon-btn:hover,
.search-icon-btn.active {
  background-color: rgba(255, 255, 255, 0.1);
}

.search-box-container {
  position: absolute;
  right: 100%;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 4px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
  overflow: hidden;
  width: 0;
  opacity: 0;
  transition: all 0.3s ease;
  z-index: 1000;
}

.search-box-container.open {
  width: 100%;
  opacity: 1;
}

.search-input {
  border: none;
  outline: none;
  width: 100%;
  height: 36px;
  /* padding: 0 8px; */
  border: none;
}

.search-btn,
.close-btn {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #606266;
  transition: color 0.3s ease;
}

.search-btn:hover,
.close-btn:hover {
  color: #409eff;
}

/* 防止搜索框在小屏幕上重叠 */
@media screen and (max-width: 1200px) {
  .search-box-container.open {
    width: 250px;
  }
}
</style>