<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"> <a href="http://www.qf1121.top/">清疯不颠</a></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="articlelist">
              目录
            </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="{ 'small-hero': classsmallhero }" v-if="windowwidth"
    :style="{ marginBottom: heroMarginBottom, transform: heroTransform }">
    <h1 class="typewriter">{{ heroText }}</h1>
  </div>

  <!-- 内容区域 -->
  <div id="content-section" :class="{ 'visible': iscontentvisible }">
    <div class="nonsensetitle" v-if="classnonsenset">
      <div class="nonsensetitleconst">
        <h1>{{ Cardtitle }}</h1>
      </div>
    </div>

    <!-- 左侧模块 -->
    <div class="leftmodluecontainer" v-if="isleftmodluecontainer">
      <LeftModule class="leftmodluepage" @update-data="updateData" @CategoryModal="CategoryModal"
        @AttributeModal="AttributeModal" :class="{ 'nonsensetmargintop': classmoduleorrouter }" v-if="windowwidth" />
    </div>

    <!-- 内容模块 -->
    <div class="RouterViewpage">
      <RouterView :class="{ 'forbidwidth': !isleftmodluecontainer, 'nonsensetmargintop': classmoduleorrouter }" />
      <!-- 页脚 -->
      <Footer class="footer-container" v-if="windowwidth" />
    </div>
  </div>
  <!-- 分类蒙板组件 -->
  <Transition name="modal">
    <div v-if="showCategoryModal" class="category-modal" @click.self="closeCategoryModal">
      <div class="category-modal-content">
        <div class="category-modal-header">
          <h3>所有分类</h3>
          <button class="category-modal-close" @click="closeCategoryModal">×</button>
        </div>
        <div class="category-modal-body">
          <button v-for="category in Categoriestree" :key="category.typeid" class="category-button"
            @click="handleCategoryClick(category)">
            {{ category.name }} <span class="category-button-count">({{ category.children?.length || 0 }})</span>
          </button>
        </div>
      </div>
    </div>
  </Transition>

  <!-- 标签蒙板组件 -->
  <Transition name="modal">
    <div v-if="showAttributeModal" class="category-modal" @click.self="closeAttributeModal">
      <div class="category-modal-content">
        <div class="category-modal-header">
          <h3>所有标签</h3>
          <button class="category-modal-close" @click="closeAttributeModal">×</button>
        </div>
        <div class="category-modal-body">
          <!-- 扁平化处理 -->
          <button v-for="attribute in getAllAttributes()" :key="attribute.attributeid" class="category-button"
            @click="handleAttributeClick(attribute)">
            {{ attribute.attributename }} <span class="category-button-count">({{ attribute.articlecount || 0 }})</span>
          </button>
        </div>
      </div>
    </div>
  </Transition>
  <!-- 管理员 -->
  <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';
import Footer from '@/views/Footer.vue';

// ========== 组件初始化 ==========

// 路由相关状态
const router = useRouter();
const route = useRoute();

// 全局状态管理
import { useGlobalStore } from '@/store/globalStore';
const globalStore = useGlobalStore();
const Login = computed(() => globalStore.Login);

// ========== 响应式状态定义 ==========
// 页面标题和样式相关状态
const Cardtitle = ref('');
const classmoduleorrouter = ref(false);
const classnonsenset = ref(false);
const classsmallhero = ref(false);
const elrowtop = ref('transparent');
// hero区域的margin值，用于实现滚动时动态变化
const heroMarginBottom = ref('45%');
// hero区域的初始margin值，从CSS变量获取
const initialHeroMarginBottom = 45;
// hero是否开始向上移动
const heroIsMoving = ref(false);
// hero的transform值，用于实现向上移动和吸附效果
const heroTransform = ref('translateY(450px)');
const heroTransformValue = 450;
// hero的位置状态：static(静态)、moving(移动中)、sticky(吸附顶部)
const heroPosition = ref('static');

// 布局相关状态
const isleftmodluecontainer = ref(true);
const iscontentvisible = ref(false);
const isScrollingleftmodlue = 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 Categoriestree = ref<any[]>([])
const showCategoryModal = ref(false)
const showAttributeModal = ref(false)
// 关闭分类蒙板
const closeCategoryModal = () => {
  showCategoryModal.value = false;
}
// 关闭标签蒙板
const closeAttributeModal = () => {
  showAttributeModal.value = false;
}
// 左侧状态栏传值
const updateData = (data: any) => {
  // 处理异步数据
  // console.log(data.fetchCategoriestree)
  if (data.fetchCategoriestree && typeof data.fetchCategoriestree.then === 'function') {
    data.fetchCategoriestree.then(result => {
      Categoriestree.value = result || []
    })
  } else {
    Categoriestree.value = data.fetchCategoriestree || []
  }
}
// 分类相关状态
const CategoryModal = async (data: any) => {
  showCategoryModal.value = data.ifmodal
}
// 标签相关状态
const AttributeModal = async (data: any) => {
  showAttributeModal.value = data.ifmodal
}
//  ========== 蒙版事件 ==========

// 处理分类点击
const handleCategoryClick = (category: any) => {
  // 这里可以根据实际需求跳转到对应分类的文章列表页
  // 重置全局属性状态
  globalStore.removeValue('category')

  globalStore.setValue('category', {
    id: category.categoryid,
    name: category.categoryname
  })
  // console.log(category)
  router.push('/home/aericlecategory',)
  closeCategoryModal()
}

// 处理标签点击
const handleAttributeClick = (attribute: any) => {
  // 重置全局属性状态
  globalStore.removeValue('attribute')

  globalStore.setValue('attribute', {
    id: attribute.attributeid,
    name: attribute.attributename
  })
  // console.log(attribute)
  router.push('/home/aericletype',)
  closeAttributeModal()
}

// 获取所有标签，扁平化处理
const getAllAttributes = () => {
  return Categoriestree.value.flatMap(category => category.children || [])
}

// ========== 打字机效果模块 ==========

/**
 * 初始化并启动打字机效果
 * @param {string} text - 要显示的完整文本
 */
const startTypewriter = (text: string) => {
  // 重置状态
  heroText.value = '';
  heroIndex = 0;

  // 清除可能存在的定时器
  if (heroTimer) {
    clearInterval(heroTimer);
  }

  // 设置新的定时器，逐字显示文本
  heroTimer = window.setInterval(() => {
    if (heroIndex < text.length) {
      heroText.value += text[heroIndex];
      heroIndex++;
    } else {
      // 文本显示完毕，清除定时器
      clearInterval(heroTimer);
    }
  }, 100);
};

/**
 * 停止打字机效果并显示完整文本
 */
const stopTypewriter = () => {
  // 清除定时器
  if (heroTimer) {
    clearInterval(heroTimer);
  }
  // 非首页时清空hero内容
  if (rpsliturl[1] !== localhome) {
    heroText.value = '';
  } else {
    // 首页直接显示完整文本
    heroText.value = fullHeroText;
  }
};

// ========== 导航和路由处理模块 ==========

/**
 * 处理菜单选择并跳转到对应路由
 * @param {string} key - 菜单项的key值，对应路由路径
 */
const handleSelect = (key: string) => {
  router.push({ path: '/' + key });
};


/**
 * 根据路由路径设置页面状态
 */
const updatePageState = () => {
  // 根据是否为主页根路径设置hero区域状态
  classsmallhero.value = !(rpsliturl[1] == localhome && rpsliturl[2] == undefined);
  // 控制左侧模块容器的显示/隐藏
  isleftmodluecontainer.value = rpsliturl[1] !== "articlesave";
};

/**
 * 更新文章标题和相关显示状态
 */
const updateArticleTitle = () => {
  let articledata: any = null;
  // 根据不同路由参数获取文章标题数据
  if (rpsliturl[2] === 'aericleattribute') {
    // 按属性类型获取
    articledata = globalStore.getValue('attribute')?.name;
  }
  else if (rpsliturl[2] === 'aericletitle') {
    // 按标题搜索获取
    articledata = globalStore.getValue('articleserarch')?.name;
  }
  else if (rpsliturl[1] === 'nonsense') {
    // 疯言疯语页面特殊处理
    articledata = "疯言疯语";
  }

  // 确定标题区域的显示状态
  const shouldHideTitle =
    // 特殊页面不需要显示标题
    (rpsliturl[1] === 'articlelist' ||
      rpsliturl[1] === 'message' ||
      rpsliturl[1] === 'about') ||
    // 在主页且无标题数据时，不显示标题
    (rpsliturl[1] === localhome && !articledata);

  // 更新标题显示状态
  classnonsenset.value = !shouldHideTitle && !!articledata;
  classmoduleorrouter.value = !shouldHideTitle && !!articledata;

  // 设置标题内容
  if (articledata) {
    Cardtitle.value = articledata;
  }
};

// ========== 搜索功能模块 ==========

/**
 * 切换搜索框的显示/隐藏状态
 */
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.removeValue('articleserarch');
    // 存储搜索关键词到全局状态
    globalStore.setValue('articleserarch', {
      name: searchKeyword.value
    });
    // 跳转到搜索结果页面
    router.push({ path: `/home/aericletitle` });
  }

  // 搜索后保持搜索框打开状态
  if (searchCloseTimer) {
    clearTimeout(searchCloseTimer);
  }
};

// ========== 响应式处理模块 ==========

/**
 * 处理窗口大小变化
 * 根据屏幕宽度调整布局和内容显示
 */
const handleResize = () => {

  // 更新窗口宽度状态
  windowwidth.value = window.innerWidth > 768;

  // 首页特殊处理：小屏幕下默认显示内容区
  if (rpsliturl[1] === localhome) {
    iscontentvisible.value = window.innerWidth <= 768;
  }
  // 移动端首页默认显示内容区，桌面端初始隐藏
  iscontentvisible.value = window.innerWidth <= 768;
};

/**
 * 处理页面滚动事件
 * 根据滚动位置调整导航栏样式和内容显示动画
 */
const handleScroll = () => {
  let scrollY = 0;
  scrollY = window.scrollY;
  // 小屏幕设备只切换导航栏样式
  if (window.innerWidth <= 768) {
    updateNavbarStyle(scrollY);
    return;
  }

  // 大屏幕设备完整处理
  updateNavbarStyle(scrollY);
  // 仅在首页根路径应用滚动动画
  if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
    // 首页滚动动画处理
    if (scrollY <= 350) {
      HeroState(scrollY);
    }
    // 控制左侧模块的滚动状态
    isScrollingleftmodlue.value = scrollY > 600;
  }
};
// ========== 首页滚动动画模块 ==========
const HeroState = (scrollY: number) => {
  const windowHeight = window.innerHeight;
  // 计算滚动距离与窗口高度的比例，用于内容渐显
  const contentScrollRatio = Math.min(scrollY / windowHeight, 1);
  // 计算新的底部margin值，从初始值45%逐渐减少到25%
  const newMarginBottom = Math.max(initialHeroMarginBottom - (initialHeroMarginBottom * contentScrollRatio), 0);
  // 更新hero的底部margin值
  heroMarginBottom.value = `${newMarginBottom}%`;
  // 计算新的translateY值，从初始值450px逐渐减少到150px
  const translateYValue = Math.max(heroTransformValue - (heroTransformValue * contentScrollRatio * 5), 90);
  heroTransform.value = `translateY(${translateYValue}px)`;
  // 当滚动超过100px时开始显示，滚动到一屏高度时完全显示
  iscontentvisible.value = scrollY > 100;
  // 当滚动超过287px时logo被顶出屏幕，触发移动状态
  if (scrollY > 287) {
    heroPosition.value = 'moving';
    const translateYValue = Math.min(heroTransformValue - (heroTransformValue * contentScrollRatio * 5), 0);
    heroTransform.value = `translateY(${translateYValue / 2}px)`;
  }
};
/**
 * 根据滚动位置更新导航栏样式
 * @param {number} scrollY - 当前滚动位置
 */
const updateNavbarStyle = (scrollY: number) => {
  // 根据滚动位置设置导航栏样式
  // 当滚动超过1200px且屏幕宽度大于768px时隐藏导航栏
  if (scrollY > 1200 && window.innerWidth > 768) {
    elrowtop.value = 'hide'; // 隐藏导航栏
  } else {
    elrowtop.value = scrollY > 50 ? 'solid' : 'transparent'; // 固定或透明样式
  }
};

// ========== 路由监听和页面初始化 ==========

/**
 * 处理路由变化的核心函数
 * 更新页面状态、标题、激活菜单项等
 */
const handleRouteChange = () => {
  // 重新解析路由路径
  rpsliturl = route.path.split('/');
  // 移除全局状态值
  removeGlobalStoreValue();
  // 更新页面相关状态
  updatePageState();
  // setActiveIndex(rpsliturl[1]);
  updateArticleTitle();
  activeIndex.value = rpsliturl[1];
  // 页面跳转后回到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });

  // 根据是否为首页决定是否启动打字机效果
  if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
    // 首页启动打字机效果
    startTypewriter(fullHeroText);
    // 重置hero的margin值为初始值
    heroMarginBottom.value = `${initialHeroMarginBottom}%`;
    // 重置hero的移动状态
    heroTransform.value = `translateY(${heroTransformValue}px)`;
    heroIsMoving.value = false;
    heroPosition.value = 'static';
  } else {
    iscontentvisible.value = true;
    startTypewriter(fullHeroText);
    heroMarginBottom.value = `${2.5}%`;
    heroTransform.value = ``;
  }
};

/**
 * 初始化页面
 */
const initializePage = () => {
  // 初始化窗口大小
  handleResize();
  // 启动打字机效果（如果是首页）
  if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
    // 首页启动打字机效果
    startTypewriter(fullHeroText);
    // 重置hero的margin值为初始值
    heroMarginBottom.value = `${initialHeroMarginBottom}%`;
    // 重置hero的移动状态
    heroIsMoving.value = false;
    heroPosition.value = 'static';
    // 移动端首页默认显示内容区，桌面端初始隐藏
    iscontentvisible.value = window.innerWidth <= 768;
  } else {
    startTypewriter(fullHeroText);
    heroMarginBottom.value = `${2.5}%`;
  }

};
const removeGlobalStoreValue = () => {
  // 根据所在页面判断是否需要移除全局状态值
  if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
    // 首页移除全局状态值
    // globalStore.removeValue(value);
  }
  // 不在articlesave移除文章全局状态值
  if (rpsliturl[1] !== 'articlesave') {
    globalStore.removeValue('updatearticle');
  }
  // 不在首页移除
  if (rpsliturl[1] !== localhome) {
    globalStore.removeValue('articlestatus');
    globalStore.removeValue('attribute');
  }
  // 不在article或者不在articlesave移除文章全局状态值
  if (rpsliturl[1] !== 'article' && rpsliturl[1] !== 'articlesave') {
    globalStore.removeValue('articleInfo');
  }
}
// ========== 生命周期钩子 ==========

/**
 * 组件挂载时执行
 */
onMounted(() => {
  // 初始化页面
  initializePage();

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

/**
 * 组件卸载时执行
 */
onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize);
  window.removeEventListener('scroll', handleScroll);

  // 清理定时器
  if (heroTimer) {
    clearInterval(heroTimer);
  }
  if (searchCloseTimer) {
    clearTimeout(searchCloseTimer);
  }
});

// ========== 监听器 ==========

/**
 * 监听路由变化
 * 当路由变化时更新页面状态
 */
watch(
  () => route.path,
  handleRouteChange,
);
</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;
}

.el-input__wrapper {
  width: 80px;
}

.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;
}

.footer-container {
  margin-top: 20px;
}

/* 搜索框样式 */
/* ... 现有搜索框样式 ... */

/* 蒙版样式 */
.category-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  margin: 0;
  padding: 0;
}

.category-modal-content {
  background-color: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.category-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.category-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.category-modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.category-modal-close:hover {
  background-color: #f5f5f5;
  color: #333;
}

.category-modal-body {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  max-height: 60vh;
  overflow-y: auto;
}

.category-button {
  background-color: rgba(102, 161, 216, 0.1);
  border: 1px solid rgba(102, 161, 216, 0.3);
  border-radius: 6px;
  padding: 10px 15px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  color: #333;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.category-button:hover {
  background-color: rgba(102, 161, 216, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(102, 161, 216, 0.2);
}

.category-button-count {
  font-size: 12px;
  color: #66a1d8;
  font-weight: 500;
}

/* 蒙板动画 */
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-enter-active .category-modal-content,
.modal-leave-active .category-modal-content {
  transition: transform 0.3s ease;
}

.modal-enter-from .category-modal-content {
  transform: scale(0.9);
}

.modal-leave-to .category-modal-content {
  transform: scale(0.9);
}

/* 页脚样式 */
.footer-container {
  margin-top: 20px;
}

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