<template>
  <div class="home-page">
    <!-- Top Bar -->
    <nav class="navbar">
      <div class="container-fluid">
        <div class="navbar-header">
          <img style="width: 60px; height: 48.5px; float: left; margin: 10px 5px 0px 0px;" src="/api/resource/Logo" />
          <a class="navbar-brand" style="font-size:30px;line-height:35px;padding-left:20px;">{{ systemTitle }}</a>
        </div>
        <div class="collapse navbar-collapse" id="navbar-collapse" v-if="!isPublicPage">
          <div class="navbar-actions">
            <div class="user-info">
              <span class="user-name">{{ user.name }}</span>
              <span class="role-name">{{ user.roleName }}</span>
            </div>
            <button class="action-btn" @click="updatePwd">
              <i class="el-icon-lock"></i> 修改密码
            </button>
            <button class="action-btn" @click="swithSystem">
              <i class="el-icon-refresh"></i> 切换系统
            </button>
            <button class="action-btn" @click="logout">
              <i class="el-icon-switch-button"></i> 退出登录
            </button>
          </div>
        </div>
      </div>
    </nav>
    <!-- #Top Bar -->
    
    <div class="page_content">
      <!-- Sidebar -->
      <div class="leftsidebar" v-if="!isPublicPage">
        <div class="sidebar">
          <div class="user-info">
            <div class="user-details">
              <span class="user-name">{{ user.name }}</span>
              <span class="role-name">{{ user.roleName }}</span>
            </div>
          </div>
          <div class="menu-list">
            <!-- 递归渲染菜单 -->
            <template v-for="menu in panels" :key="menu.id">
              <div class="menu-item">
                <div 
                  class="menu-header"
                  @click="menutoggle(menu)"
                >
                  <i :class="menu.icon || 'el-icon-folder'" v-if="menu.cNodes.length > 0"></i>
                  <i :class="menu.icon || 'el-icon-document'" v-else></i>
                  <span>{{ menu.title }}</span>
                  <i 
                    class="el-icon-arrow-right"
                    :class="{ 'rotate': menu.childShow }"
                  ></i>
                </div>
                <div 
                  class="sub-menu"
                  v-if="menu.cNodes.length > 0 && menu.childShow"
                >
                  <!-- 递归渲染子菜单 -->
                  <template v-for="subMenu in menu.cNodes" :key="subMenu.id">
                    <div 
                      v-if="subMenu.cNodes.length === 0" 
                      class="sub-menu-item"
                      @click="navigateTo(subMenu)"
                    >
                      <i :class="subMenu.icon || 'el-icon-document'"></i>
                      <span>{{ subMenu.title }}</span>
                    </div>
                    <!-- 处理三级及以上菜单 -->
                    <div v-else class="sub-menu-parent">
                      <div 
                        class="sub-menu-header"
                        @click="menutoggle(subMenu)"
                      >
                        <i :class="subMenu.icon || 'el-icon-folder'"></i>
                        <span>{{ subMenu.title }}</span>
                        <i 
                          class="el-icon-arrow-right"
                          :class="{ 'rotate': subMenu.childShow }"
                        ></i>
                      </div>
                      <div 
                        class="sub-sub-menu"
                        v-if="subMenu.cNodes.length > 0 && subMenu.childShow"
                      >
                        <div 
                          v-for="subSubMenu in subMenu.cNodes" 
                          :key="subSubMenu.id"
                          class="sub-sub-menu-item"
                          @click="navigateTo(subSubMenu)"
                        >
                          <i :class="subSubMenu.icon || 'el-icon-document'"></i>
                          <span>{{ subSubMenu.title }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <!-- #Sidebar -->
      
      <!-- Main Content -->
      <section class="content">
        <div class="container-fluid">
          <router-view></router-view>
        </div>
      </section>
      <!-- #Main Content -->
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomePage',
  data() {
    return {
      systemTitle: '联达拖轮管理系统',
      user: {
        name: '',
        roleName: ''
      },
      isPublicPage: false,
      menuList: [],
      panels: []
    }
  },
  mounted() {
    // 从本地存储获取用户信息
    this.user.name = localStorage.getItem('username') || ''
    this.user.roleName = localStorage.getItem('roleName') || ''
    this.isPublicPage = localStorage.getItem('publicPage') === 'true'
    
    // 加载菜单列表
    console.log('isPublicPage:', this.isPublicPage)
    console.log('开始获取菜单列表')
    this.getMenuList()
  },
  methods: {
    // 获取菜单列表
    async getMenuList() {
      try {
        console.log('开始执行getMenuList方法')
        const token = localStorage.getItem('token')
        console.log('获取到的token:', token)
        if (!token) {
          this.$message.error('未获取到登录令牌')
          return
        }

        // 从后端API获取菜单数据
        console.log('准备发送请求到后端获取菜单')
        const response = await fetch('/api/menu/getMenus', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        })

        console.log('获取菜单的响应状态:', response.status)
        console.log('获取菜单的响应状态文本:', response.statusText)
        
        if (!response.ok) {
          throw new Error('获取菜单失败，状态码: ' + response.status)
        }

        const menuData = await response.json()
        console.log('从后端获取到的菜单数据:', menuData)
        
        // 转换后端返回的菜单数据格式为前端需要的格式
        const formattedMenuList = this.convertMenuFormat(menuData)
        console.log('转换后的菜单数据:', formattedMenuList)
        
        this.menuList = formattedMenuList
        if (this.menuList.length > 0) {
          this.panels = this.buildMenuTree(this.menuList, 'mainMenu')
          this.initActive(this.panels)
          console.log('构建完成的菜单面板:', this.panels)
        }
      } catch (error) {
        console.error('获取菜单失败:', error)
        this.$message.error('获取菜单失败，请刷新页面重试')
        
        // 使用默认菜单作为 fallback
        this.useDefaultMenus()
      }
    },
    
    // 转换后端返回的菜单数据格式
    convertMenuFormat(menuData) {
      console.log('转换前的菜单数据:', menuData)
      return menuData.map(menu => {
        const formattedMenu = {
          MenuId: menu.id,
          Title: menu.title,
          Icon: menu.icon || 'el-icon-document',
          Url: menu.url || '',
          IsVisible: 1,
          Childrens: []
        }
        
        if (menu.subMenus && menu.subMenus.length > 0) {
          formattedMenu.Childrens = this.convertMenuFormat(menu.subMenus)
        }
        
        return formattedMenu
      })
    },
    
    // 使用默认菜单作为 fallback
    useDefaultMenus() {
      const defaultMenus = [
        {
          MenuId: 1,
          Title: '首页',
          Icon: 'el-icon-s-home',
          Url: 'mainindex',
          IsVisible: 1,
          Childrens: []
        },
        {
          MenuId: 2,
          Title: '通知管理',
          Icon: 'el-icon-bell',
          Url: '',
          IsVisible: 1,
          Childrens: [
            {
              MenuId: 21,
              Title: '我的通知',
              Icon: 'el-icon-message',
              Url: 'mynotice',
              IsVisible: 1,
              Childrens: []
            },
            {
              MenuId: 22,
              Title: '公告管理',
              Icon: 'el-icon-document',
              Url: 'announcement',
              IsVisible: 1,
              Childrens: []
            }
          ]
        },
        {
          MenuId: 3,
          Title: '调度管理',
          Icon: 'el-icon-s-operation',
          Url: '',
          IsVisible: 1,
          Childrens: [
            {
              MenuId: 31,
              Title: '引航计划',
              Icon: 'el-icon-s-grid',
              Url: 'pilot-plan',
              IsVisible: 1,
              Childrens: []
            }
          ]
        },
        {
          MenuId: 4,
          Title: '系统设置',
          Icon: 'el-icon-setting',
          Url: '',
          IsVisible: 1,
          Childrens: [
            {
              MenuId: 41,
              Title: '角色管理',
              Icon: 'el-icon-user',
              Url: 'role',
              IsVisible: 1,
              Childrens: []
            },
            {
              MenuId: 42,
              Title: '用户管理',
              Icon: 'el-icon-users',
              Url: 'user',
              IsVisible: 1,
              Childrens: []
            }
          ]
        }
      ]
      
      this.menuList = defaultMenus
      this.panels = this.buildMenuTree(this.menuList, 'mainMenu')
      this.initActive(this.panels)
    },

    
    // 构建菜单树
    buildMenuTree(menuList, parentId) {
      const returnVal = []
      menuList.forEach(menu => {
        if (menu.IsVisible !== 1) {
          return
        }
        const pmenu = {
          id: menu.MenuId,
          title: menu.Title,
          icon: menu.Icon,
          name: menu.Url,
          url: menu.Url,
          cNodes: [],
          childShow: 0,
          parentIds: parentId
        }
        // 递归构建子菜单，支持多级菜单
        if (menu.Childrens && menu.Childrens.length > 0) {
          pmenu.cNodes = this.buildMenuTree(menu.Childrens, parentId + '.' + pmenu.id)
        }
        returnVal.push(pmenu)
      })
      return returnVal
    },
    
    // 初始化菜单激活状态
    initActive(menuList) {
      const statename = this.$route.name
      menuList.forEach(value => {
        const p_realState = this.sliceStateName(value.name)
        if (p_realState === statename) {
          this.menutoggle(value)
        }
        this.initActive(value.cNodes)
      })
    },
    
    // 点击菜单事件
    menutoggle(node) {
      const childShow = node.cNodes.length > 0 ? (node.childShow > 0 ? 0 : 1) : 1
      const codes = node.parentIds.split('.')
      codes.push(node.id)
      this.resetActive(this.panels, codes)
      node.childShow = childShow
    },
    
    // 重置菜单激活状态
    resetActive(list, codes) {
      list.forEach(node => {
        const index = codes.indexOf(node.id)
        node.childShow = index >= 0 ? 1 : 0
        if (node.cNodes && node.cNodes.length > 0) {
          this.resetActive(node.cNodes, codes)
        }
      })
    },
    
    // 导航到菜单对应的路由
    navigateTo(menu) {
      if (menu.url) {
        this.$router.push(`/${menu.url}`)
      }
    },
    
    // 截取状态名称
    sliceStateName(statename) {
      if (!statename) return null
      const index = statename.indexOf('(')
      if (index >= 0) {
        return statename.slice(0, index)
      }
      return statename
    },
    
    // 修改密码
    updatePwd() {
      // 打开修改密码对话框
      this.$alert('修改密码功能开发中', '提示', {
        confirmButtonText: '确定'
      })
    },
    
    // 切换系统
    swithSystem() {
      // 模拟切换系统功能
      this.$confirm('是否切换系统？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中需要调用API获取公司列表并切换
        this.$message.success('系统切换功能开发中')
      }).catch(() => {
        // 取消切换
      })
    },
    
    // 退出登录
    logout() {
      this.$confirm('是否退出登录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除用户信息
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        localStorage.removeItem('roleName')
        localStorage.removeItem('selectedCompany')
        localStorage.removeItem('publicPage')
        
        // 跳转到登录页面
        this.$router.push('/login')
      }).catch(() => {
        // 取消退出
      })
    }
  }
}
</script>

<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 页面主容器 */
.home-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏样式 */
.navbar {
  background-color: #3c8dbc;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  height: 64px;
}

.container-fluid {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.navbar-header {
  display: flex;
  align-items: center;
}

.navbar-brand {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: white;
  font-size: 20px;
  font-weight: 600;
}

.navbar-brand img {
  width: 48.5px;
  height: 48.5px;
  margin-right: 12px;
}

.collapse {
  display: flex;
  align-items: center;
}

.navbar-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
}

.role-name {
  font-size: 12px;
  opacity: 0.8;
}

.action-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

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

.action-btn i {
  font-size: 16px;
}

/* 页面布局 */
.page_content {
  display: flex;
  justify-content: space-between;
  margin-top: 64px;
  min-height: calc(100vh - 64px);
}

/* 侧边栏样式 */
.leftsidebar {
  width: 220px; /* 使用固定宽度，确保足够的空间显示菜单项 */
  min-width: 200px; /* 设置最小宽度，防止过度压缩 */
  max-width: 300px; /* 设置最大宽度，防止占用过多空间 */
  background-color: #222d32;
  color: white;
  position: fixed;
  top: 64px;
  left: 0;
  bottom: 0;
  overflow-y: auto;
  overflow-x: hidden; /* 隐藏水平滚动条 */
  transition: all 0.3s ease;
  z-index: 999;
}

.sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 用户信息区域 */
.sidebar .user-info {
  padding: 20px;
  border-bottom: 1px solid #367fa9;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.sidebar .user-details {
  text-align: center;
}

.sidebar .user-name {
  font-size: 16px;
  font-weight: 600;
}

.sidebar .role-name {
  font-size: 12px;
  opacity: 0.8;
}

/* 菜单列表样式 */
.menu-list {
  flex: 1;
  padding: 16px 0;
}

.menu-item {
  margin-bottom: 4px;
}

.menu-header {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  gap: 12px;
}

.menu-header:hover {
  background-color: #1e282c;
}

.menu-header i {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.menu-header span {
  flex: 1;
  font-size: 14px;
}

.menu-header .el-icon-arrow-right {
  transition: transform 0.3s ease;
}

.menu-header .el-icon-arrow-right.rotate {
  transform: rotate(90deg);
}

/* 子菜单样式 */
.sub-menu {
  background-color: #1e282c;
  border-left: 3px solid #3c8dbc;
}

.sub-menu-item {
  display: flex;
  align-items: center;
  padding: 10px 20px 10px 48px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  gap: 12px;
}

.sub-menu-item:hover {
  background-color: #1a2226;
}

.sub-menu-item i {
  font-size: 14px;
  width: 16px;
  text-align: center;
}

.sub-menu-item span {
  font-size: 13px;
}

/* 子菜单父项样式 */
.sub-menu-parent {
  background-color: #1e282c;
}

.sub-menu-header {
  display: flex;
  align-items: center;
  padding: 10px 20px 10px 48px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  gap: 12px;
}

.sub-menu-header:hover {
  background-color: #1a2226;
}

.sub-menu-header i {
  font-size: 14px;
  width: 16px;
  text-align: center;
}

.sub-menu-header span {
  font-size: 13px;
  flex: 1;
}

.sub-menu-header .el-icon-arrow-right {
  transition: transform 0.3s ease;
  font-size: 12px;
}

.sub-menu-header .el-icon-arrow-right.rotate {
  transform: rotate(90deg);
}

/* 三级及以上子菜单样式 */
.sub-sub-menu {
  background-color: #1a2226;
  border-left: 3px solid #367fa9;
}

.sub-sub-menu-item {
  display: flex;
  align-items: center;
  padding: 8px 20px 8px 64px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  gap: 12px;
}

.sub-sub-menu-item:hover {
  background-color: #161e21;
}

.sub-sub-menu-item i {
  font-size: 12px;
  width: 14px;
  text-align: center;
}

.sub-sub-menu-item span {
  font-size: 12px;
}

/* 主内容区域样式 */
.content {
  margin-left: 220px; /* 与侧边栏宽度保持一致 */
  flex: 1;
  min-height: calc(100vh - 64px);
  padding: 20px;
  background-color: #ecf0f5;
  transition: all 0.3s ease;
}

.container-fluid {
  padding: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .leftsidebar {
    width: 200px; /* 在中等屏幕上适当减小侧边栏宽度 */
  }
  
  .content {
    margin-left: 200px; /* 与侧边栏宽度保持一致 */
  }
}

@media (max-width: 768px) {
  .container-fluid {
    padding: 0 16px;
  }
  
  .navbar-brand {
    font-size: 16px;
  }
  
  .navbar-brand img {
    width: 32px;
    height: 32px;
  }
  
  .navbar-actions {
    gap: 8px;
  }
  
  .action-btn {
    font-size: 12px;
    padding: 6px 8px;
  }
  
  .user-info {
    display: none;
  }
  
  .leftsidebar {
    width: 180px; /* 在小屏幕上进一步减小侧边栏宽度 */
  }
  
  .content {
    margin-left: 180px; /* 与侧边栏宽度保持一致 */
  }
  
  .menu-header,
  .sub-menu-item {
    padding-left: 12px;
    padding-right: 12px;
  }
  
  .sub-menu-item {
    padding-left: 36px;
  }
  
  .content {
    padding: 16px;
  }
}

/* 侧边栏折叠样式 */
.sidebar-collapsed .leftsidebar {
  width: 60px; /* 适当增加折叠后的宽度，确保图标能正常显示 */
}

.sidebar-collapsed .content {
  margin-left: 60px; /* 与侧边栏宽度保持一致 */
}

.sidebar-collapsed .menu-header span,
.sidebar-collapsed .sub-menu-item span,
.sidebar-collapsed .sidebar .user-info {
  display: none;
}

.sidebar-collapsed .menu-header,
.sidebar-collapsed .sub-menu-item {
  padding-left: 20px;
  padding-right: 20px;
  justify-content: center;
}

.sidebar-collapsed .sub-menu {
  display: none;
}
</style>