<script setup>
import {
  Management,
  Promotion,
  User,
  SwitchButton,
  CaretBottom,
  Timer,
  Ship,
  HomeFilled,
  Connection,
  Clock,
  EditPen,
  Comment,
  Menu,
  Avatar,
  MessageBox,
  ChatDotRound,
  Service
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import PasswdUpdate from '@/components/PasswdUpdate.vue'
import { ref } from 'vue'
import router from '@/router'
import UserImg from '@/assets/default.png'
const userStore = useUserStore()
const passwdUpdate = ref()
const isExpand = ref(true)
const menuWidth = ref(180)
const loading = ref(false) // 新增加载状态
const userInfo = ref({ ...userStore.user })

const handleCommand = async (key) => {
  if (key === 'logout') {
    await handleLogout()
  } else if (key === 'password') {
    passwdUpdate.value.open(userStore.user.id)
  } else {
    await handleNavigation(`/user/${key}`)
  }
}

const handleLogout = async () => {
  try {
    loading.value = true // 开始加载

    await ElMessageBox.confirm('确认退出吗？', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })

    // 显示退出中提示
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '账号退出中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 模拟延迟，确保用户体验
    await new Promise((resolve) => setTimeout(resolve, 500))

    // 清除用户数据
    userStore.setToken('')
    userStore.setUser({})

    // 导航到登录页
    await router.push('/login')

    // 确保路由切换完成后再关闭loading
    loadingInstance.close()
    ElMessage.success('已安全退出')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出失败')
    }
  } finally {
    loading.value = false
  }
}

const handleNavigation = async (path) => {
  try {
    loading.value = true
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    await router.push(path)
    // 确保路由切换完成
    await new Promise((resolve) => setTimeout(resolve, 100))
    loadingInstance.close()
  } catch (error) {
    ElMessage.error('导航失败')
  } finally {
    loading.value = false
  }
}

const reset = async () => {
  loading.value = true
  try {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '重新登录中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    userStore.setToken('')
    userStore.setUser({})
    await router.push('/login')
    loadingInstance.close()
    ElMessage.info('请重新登录')
  } finally {
    loading.value = false
  }
}

const handleChange = () => {
  isExpand.value = !isExpand.value
  menuWidth.value = isExpand.value ? 180 : 80
}
</script>
<template>
  <!-- 
    el-menu 整个菜单组件
      :default-active="$route.path" 配置默认高亮的菜单项
      router router选项开启，el-menu-item 的 index 就是点击跳转的路径
    el-menu-item 菜单项
      index="" 配置的是访问的跳转路径，配合 default-active的值实现高亮
   -->
  <el-container class="layout-container">
    <el-aside :width="menuWidth + 'px'">
      <div
        style="
          color: white;
          line-height: 60px;
          padding-left: 15px;
          font-size: 20px;
          font-weight: 700;
          border-bottom: 1px solid black;
        "
      >
        <span v-show="isExpand">场 地 预 约</span> 后 台
      </div>
      <el-menu
        name="menu-expand"
        :collapse="!isExpand"
        :collapse-transition="false"
        active-text-color="#ffd04b"
        background-color="rgb(47, 64, 80)"
        :default-active="$route.path"
        text-color="#fff"
        router
        show-timeout
        hide-timeout
      >
        <el-menu-item index="/index">
          <el-icon><HomeFilled /></el-icon>
          <span>系统首页</span>
        </el-menu-item>
        <el-menu-item index="/carousel">
          <el-icon><Connection /></el-icon>
          <span>轮播管理</span>
        </el-menu-item>
        <el-menu-item index="/type/manage">
          <el-icon><Management /></el-icon>
          <span>场馆管理</span>
        </el-menu-item>
        <el-menu-item index="/field/manage">
          <el-icon><Ship /></el-icon>
          <span>场地管理</span>
        </el-menu-item>
        <el-menu-item index="/time/manage">
          <el-icon><Timer /></el-icon>
          <span>场地禁用</span>
        </el-menu-item>
        <el-sub-menu index="/comment">
          <template #title>
            <el-icon><Comment /></el-icon>
            <span>评论管理</span>
          </template>
          <el-menu-item index="/comment/user">
            <el-icon><Comment /></el-icon>
            <span>用户评论</span>
          </el-menu-item>
          <el-menu-item index="/comment/word">
            <el-icon><Comment /></el-icon>
            <span>敏感词</span>
          </el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="/user">
          <template #title>
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/user/manage">
            <el-icon><User /></el-icon>
            <span>普通用户</span>
          </el-menu-item>
          <el-menu-item index="/user/admin">
            <el-icon><User /></el-icon>
            <span>管理员用户</span>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item index="/data/visible">
          <el-icon><Promotion /></el-icon>
          <span>数据可视化</span>
        </el-menu-item>
        <el-menu-item index="/system/log">
          <el-icon><Clock /></el-icon>
          <span>系统日志</span>
        </el-menu-item>
        <el-menu-item index="/user/info">
          <el-icon><Avatar /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
        <el-menu-item index="/message/box">
          <el-icon><MessageBox /></el-icon>
          <span>设备日志</span>
        </el-menu-item>
        <el-menu-item index="/message/netty">
          <el-icon><ChatDotRound /></el-icon>
          <span>聊天室</span>
        </el-menu-item>
        <el-menu-item index="/ai">
          <el-icon><Service /></el-icon>
          <span>ai问答</span>
        </el-menu-item>

        <!-- <el-sub-menu index="/user">
          <template #title>
            <el-icon><UserFilled /></el-icon>   
            <span>日志信息</span>
          </template>
          <el-menu-item index="/user/profile">
            <el-icon><User /></el-icon>
            <span>登录日志</span>
          </el-menu-item>
          <el-menu-item index="/user/profile">
            <el-icon><User /></el-icon>
            <span>系统日志</span>
          </el-menu-item>
        </el-sub-menu> -->
      </el-menu>
    </el-aside>
    <el-container>
      <el-header>
        <div>
          <div class="header-menu" @click="handleChange">
            <el-icon><Menu /></el-icon>
          </div>
          当前账号：<strong>{{
            userStore.user.account || userStore.user.username
          }}</strong>
        </div>
        <el-dropdown placement="bottom-end" @command="handleCommand">
          <span class="el-dropdown__box">
            <img
              :src="userInfo.isUpload === 0 ? UserImg : userStore.user.avatar"
              alt="用户头像"
              style="width: 3vw; height: 5vh; border-radius: 5vw"
            />
            <el-icon><CaretBottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="info" :icon="User"
                >基本资料</el-dropdown-item
              >
              <!-- <el-dropdown-item command="avatar" :icon="Crop"
                >更换头像</el-dropdown-item
              > -->
              <el-dropdown-item command="password" :icon="EditPen"
                >重置密码</el-dropdown-item
              >
              <el-dropdown-item command="logout" :icon="SwitchButton"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <el-main>
        <router-view></router-view>
      </el-main>
      <!-- <el-footer>{{ formatTime(new Date()) }}</el-footer> -->
    </el-container>
  </el-container>
  <PasswdUpdate ref="passwdUpdate" @success="reset"> </PasswdUpdate>
</template>
<style lang="scss" scoped>
.layout-container {
  height: 100vh;
  .el-aside {
    background-color: rgb(47, 64, 80);
    &__logo {
      height: 100px;
      background: url('@/assets/login_bg.jpg') no-repeat center / 120px auto;
    }
    .el-menu {
      border-right: none;
      overflow-y: auto; // 垂直滚动
      overflow-x: hidden; // 防止水平滚动条
      padding-bottom: 20px; // 防止滚动条遮挡底部
      &::-webkit-scrollbar {
        // 自定义滚动条样式
        width: 8px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: rgba(255, 255, 255, 0.3);
        border-radius: 4px;
      }
    }
  }
  .el-header {
    background-color: #fff;
    display: flex;
    height: 8vh;
    align-items: center;
    justify-content: space-between;
    .el-dropdown__box {
      display: flex;
      align-items: center;
      .el-icon {
        color: #999;
        margin-left: 10px;
      }
      &:active,
      &:focus {
        outline: none;
      }
    }
  }
  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
  }
}
.header-menu {
  float: left;
  margin-right: 10px;
  font-size: 20px;
  cursor: pointer;
}
.header-menu:hover {
  color: skyblue;
}

.aside-transition {
  transition: width 0.5s ease;
}

/* 菜单文字淡入淡出效果 */
.menu-expand-enter-active,
.menu-expand-leave-active {
  transition:
    opacity 0.4s ease,
    max-width 1s ease;
}

.menu-expand-enter-from,
.menu-expand-leave-to {
  opacity: 0;
  max-width: 0;
}

.menu-expand-enter-to,
.menu-expand-leave-from {
  opacity: 1;
  max-width: 100px;
}

/* 菜单项文字容器 */
.el-menu-item span,
.el-sub-menu__title span {
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  vertical-align: bottom;
}

/* 修复折叠菜单滚动条导致的宽度变化 */
:deep(.el-menu--collapse) {
  width: 80px !important;
  min-width: 80px !important;
  max-width: 80px !important;
  transition: width 0.3s ease;
}
</style>
