<template>
  <div class="header">
    <div class="header-list">
      <el-row>
        <div class="header-top">
          <el-col :span="4">
            <div class="logo">
              <img src="@/assets/image/logo.png">
            </div>
          </el-col>
          <el-col :span="12">
            <ul class="header-menu">
              <router-link v-for="(item, index) in headlist" :key="index" :to="item.path">
                <li><span>{{ item.title }}</span></li>
              </router-link>
            </ul>
          </el-col>
          <el-col :span="8">
            <div class="header-right">
              <div class="start">
                <el-button color="#ea4322" @click="handleOpenStartPage">
                  立即入驻
                </el-button>
              </div>
              <!-- <div class="login">
                <el-button plain color="#f85535"  @click="openLoginForm" class="login-button">
                  商家登录
                </el-button>
              </div> -->
              <div v-if="isLoggedIn" class="logout">
                <el-button type="danger" plain   @click="logout" class="logout-button">
                  退出
                </el-button>
              </div>
            </div>
          </el-col>
        </div>
      </el-row>
    </div>

    <div class="login-register-module">
      <span @click="handleOpenStartPage">立即入驻</span>
      <span>|</span>
      <span @click="openLoginForm">商家登录</span>
      <span v-if="isLoggedIn" @click="logout">退出</span>
    </div>

    <!-- 汉堡菜单 -->
    <div class="hamburger-menu" @click="toggleMenu">
      <span :class="{ 'hamburger-icon': true, 'rotate-top': isMenuOpen, }"></span>
      <span :class="{ 'hamburger-icon': true, 'hide-middle': isMenuOpen }"></span>
      <span :class="{ 'hamburger-icon': true, 'rotate-bottom': isMenuOpen }"></span>
    </div>
    <div :class="{ 'mobile-menu': true, 'open': isMenuOpen }">
      <ul class="mobile-menu-list">
        <li v-for="(item, index) in headlist" :key="index">
          <router-link :to="item.path" @click="toggleMenu">
            <span>{{ item.title }}</span>
          </router-link>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import { getApproval_status } from '@/api/login';

const emits = defineEmits(['open-login-form', 'open-register-form']);

const openLoginForm = () => {
  emits('open-login-form');
};

const openRegisterForm = () => {
  emits('open-register-form');
};

// 导航栏数据
const headlist = ref([
  { title: '首页', path: '/index' },
  { title: '使用教程', path: '/help' },
  { title: '关于我们', path: '/about' },
]);
const toRouter=(pathString:string)=>{
  router.push({path:pathString})
}
const router = useRouter();
const userStore = useUserStore();

// 从 userStore 中获取登录状态
const isLoggedIn = ref(userStore.isLoggedIn);

// 每次页面加载时检查 token
onMounted(() => {
  const storedToken = localStorage.getItem('token');
  if (storedToken) {
    userStore.setToken(storedToken); // 如果有 token，设置 token 并更新登录状态
  }
  isLoggedIn.value = userStore.isLoggedIn; // 更新登录状态
});

// 监听 userStore.isLoggedIn 的变化
watch(() => userStore.isLoggedIn, (newVal) => {
  isLoggedIn.value = newVal; // 确保 isLoggedIn 始终与 userStore.isLoggedIn 保持一致
  if (isLoggedIn.value === null) console.log("登陆过期");
  // getApproval_status().then((res) => {
  //   if (res.code === 0 && res.status === 200) {
  //     localStorage.setItem('approval_status', res.data.approval_status);
  //   } else {

  //   }
  // });
});

// 处理免费开店按钮点击事件
const handleOpenStartPage = () => {
  if (isLoggedIn.value) {
    if (localStorage.getItem('approval_status') != null && localStorage.getItem('approval_status') === '4') {
      router.push({ name: 'start' });
    } else {
      router.push({ name: 'check' }); // 已登录跳转到 check 页面
    }
  } else {
    openRegisterForm(); // 未登录弹出注册组件
  }
};

// 退出登录函数
const logout = () => {
  userStore.clearToken();
  userStore.removeMobilePhone();
  userStore.removeIdentity();
  isLoggedIn.value = false; // 更新登录状态为未登录
  router.push('/'); // 可以根据需求跳转到其他页面
};

// 汉堡菜单相关逻辑
const isMenuOpen = ref(false);

const toggleMenu = () => {
  isMenuOpen.value = !isMenuOpen.value;
};

// 监听窗口 resize 事件
let resizeHandler: () => void;
onMounted(() => {
  resizeHandler = () => {
    const clientWidth = document.documentElement.clientWidth;
    const isMobile = clientWidth <= 768;
    if (!isMobile && isMenuOpen.value) {
      isMenuOpen.value = false;
    }
  };
  window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler);
});
</script>

<style scoped>

.hamburger-menu {
  position: fixed; /* 修改为固定定位 */
  top: 20px; /* 调整顶部位置 */
  right: 20px; /* 调整右侧位置 */
  width: 25px;
  height: 25px;
  cursor: pointer;
  z-index: 10011; /* 设置比 header-list 更高的 z-index */
  display: none;
}

.hamburger-icon {
  display: block;
  width: 100%;
  height: 3px;
  background-color: #303133;
  margin: 5px 0;
  transition: all 0.3s ease-in-out;
  transform-origin: center;
}

.rotate-top {
  transform: translateY(8px) rotate(45deg);
}

.hide-middle {
  opacity: 0;
}

.rotate-bottom {
  transform: translateY(-8px) rotate(-45deg); 
}

.mobile-menu {
  position: fixed;
  top: 70px; /* 移动到 header-top 下方 */
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff; /* 修改背景颜色为白色 */
  z-index: 10010;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s ease-in-out;
  opacity: 0; /* 初始设置为透明 */
  visibility: hidden; /* 初始隐藏 */
}

.mobile-menu.open {
  opacity: 1; /* 显示时不透明 */
  visibility: visible; /* 显示 */
}

.mobile-menu-list {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 90%;
  max-width: 300px;
  border-radius: 10px;
  overflow: hidden;
  z-index: 10010;
}

.mobile-menu-list li {
  padding: 10px;
  line-height: 30PX;
  border-bottom: 1px solid 	#DCDCDC;
}
.mobile-menu-list li a {
  text-decoration: none;
}
.mobile-menu-list li:last-child {
  border-bottom: none;
}

.login-register-module {
  position: fixed;
  top: 20px;
  right: 60px;
  z-index: 10010; 
  display: flex;
  justify-content: center;
  align-items: center;
  display: none;
}

.login-register-module span {
  margin-right: 10px;
  line-height: 35px;
  cursor: pointer;
}
.login-register-module span:hover {
  color: blue;
}

.logo {
  display: inline-block;
  img{
    height: 48px;
  }
}

@media (max-width: 768px) {
  .header-menu {
    display: none;
  }
}
</style>