<template>
  <div class="top-nav">
    <!-- 顶部容器 -->
    <div id="topContainer" class="container">
      <!-- 统一显示logo和导航 -->
      <div class="logo">
        <!-- Logo图片，点击跳转首页 -->
        <img v-if="JSON.stringify(logoInfoNew) !== '{}'" @click="$router.push(homePath)" style="cursor:pointer;"
          class="logoImg" :src="logoInfoNew.home.logoImg || ''" alt="">

        <!-- 主导航菜单 -->
        <nav class="main-nav">
          <div class="nav-list">
            <!-- 首页 -->
            <p :class="{ active: $route.path.includes('/index') }">
              <a @click="$router.push('/homePage/index')">{{ translations[language].home }}</a>
            </p>
            <!-- 产品与服务：鼠标移入显示子菜单 -->
            <p @mouseleave="sildeOut" @mouseenter="sildeIn(product_service)">
              <a>{{ translations[language].ecosystem }}</a>
            </p>
            <!-- 供需广场 -->
            <p :class="{ active: $route.path.includes('/supply') }">
              <a @click="$router.push('/ncmatchHome/supplyAndDemandSquare')">{{ translations[language].supply }}</a>
            </p>
            <!-- 关于我们 -->
            <p :class="{ active: $route.path.includes('/about') }" @mouseleave="sildeOut"
              @click="$router.push('/homePage/about')">
              <a>{{ translations[language].aboutUs }}</a>
            </p>
          </div>
        </nav>
      </div>

      <!-- 用户区域：登录/注册按钮和用户下拉菜单 -->
      <div class="user-area">
        <!-- 搜索框 -->
        <!-- <div class="search-box">
          <i class="el-icon-search"></i>
          <input type="text" :placeholder="translations[language].searchPlaceholder">
        </div> -->
        <!-- 中英互译 -->
        <div class="language-toggle" @click="toggleLanguage">
          <span class="iconfont icon-ditu_diqiu_o"></span>
          <span class="language-text">{{ language === 'zh' ? 'English' : '中文' }}</span>
        </div>
        <!-- AI -->
        <i class="iconfont icon-AIzhushou functions"></i>
        <!-- 客服 -->
        <i class="iconfont icon-kefu functions"></i>
        <!-- 控制台按钮（已登录） -->
        <a @click="goB" v-if="loginState" class="login-btn">{{ translations[language].console }}</a>
        <!-- 消息 - 修改这里：点击时打开消息中心 -->
        <i class="iconfont icon-xiaoxi functions" @click="handleMessageClick"></i>
        <!-- 登录按钮（未登录） -->
        <a @click="$router.push({
          path: '/login',
          query: {
            fromPath: 'homePage'
          }
        })" v-if="!loginState" class="login-btn">{{ translations[language].login }}</a>
        <!-- 注册按钮（未登录） -->
        <a @click="$router.push('/registrationPage')" v-if="!loginState" class="register-btn">{{
          translations[language].register }}</a>

        <!-- 用户下拉菜单（已登录） -->
        <el-dropdown v-if="loginState" @visible-change="handleShow"
          class="avatar-container right-menu-item hover-effect nick-name-style" style="margin-right: 0" trigger="click">
          <div class="avatar-wrapper">
            <!-- 显示用户名首字母头像和用户名 -->
            <i
              style="font-size: 18px; color: #262626;font-weight: 400;cursor: pointer;display: flex;justify-content: flex-end;align-items: center">
              <div class="imgUser"><img src="../../../../assets/image/user.png" alt=""></div>
              {{ nick_name }}
              <!-- 下拉箭头图标 -->
              <i id="resverIcon" class="el-icon-arrow-up el-icon--right resverIcon"></i>
            </i>
          </div>
          <!-- 用户信息下拉菜单内容 -->
          <el-dropdown-menu slot="dropdown" style="width: 230px;font-size: 16px;" divided>
            <!-- 用户信息头部 -->
            <div style="display: flex;flex-direction: column;padding:15px 15px;background-color: #f0f2f5">
              <span style="font-weight: bold;font-size: 20px;margin-bottom: 5px;color: #333333">{{ nick_name }}</span>
              <span style="font-size: 12px;color:#666;display: flex;justify-content:flex-start;align-items: center"> ID:
                <!-- 用户ID，点击复制按钮可复制 -->
                <span ref="contentToCopy">
                  {{
                    userId
                  }}
                </span>
                <!-- 复制按钮 -->
                <svg @click="copyBtn" class="copy-btn" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"
                  width="12" height="12" style="fill: #1019ab;">
                  <path
                    d="M394.666667 106.666667h448a74.666667 74.666667 0 0 1 74.666666 74.666666v448a74.666667 74.666667 0 0 1-74.666666 74.666667H394.666667a74.666667 74.666667 0 0 1-74.666667-74.666667V181.333333a74.666667 74.666667 0 0 1 74.666667-74.666666z m0 64a10.666667 10.666667 0 0 0-10.666667 10.666666v448a10.666667 10.666667 0 0 0 10.666667 10.666667h448a10.666667 10.666667 0 0 0 10.666666-10.666667V181.333333a10.666667 10.666667 0 0 0-10.666666-10.666666H394.666667z m245.333333 597.333333a32 32 0 0 1 64 0v74.666667a74.666667 74.666667 0 0 1-74.666667 74.666666H181.333333a74.666667 74.666667 0 0 1-74.666666-74.666666V394.666667a74.666667 74.666667 0 0 1 74.666666-74.666667h74.666667a32 32 0 0 1 0 64h-74.666667a10.666667 10.666667 0 0 0-10.666666 10.666667v448a10.666667 10.666667 0 0 0 10.666666 10.666666h448a10.666667 10.666667 0 0 0 10.666667-10.666666v-74.666667z"
                    p-id="1521"></path>
                </svg>
              </span>
            </div>
            <!-- 分割线 -->
            <el-divider style="margin: 0!important;"></el-divider>
            <!-- 客户角色余额和充值按钮 -->
            <div v-if="role.includes('客户')"
              style="padding: 0 18px;  width: 100%;height: 60px;display: flex;justify-content: space-between;align-items: center">
              <span style="color:#666;display: block;font-size: 14px;" class="moneyNow"><span
                  style="display: block;margin-bottom: 5px">{{ translations[language].balance }}</span>{{
                    mybalance ? mybalance : initMybalance()
                  }} ￥</span>
              <el-button v-if="!isShowKbossCharge" type="primary" @click="$router.push('/kbossCharge')" plain
                style="padding: 8px; ">
                {{ translations[language].recharge }}
              </el-button>
            </div>
            <!-- 个人中心菜单项 -->
            <el-dropdown-item v-if="role.includes('客户')" @click.native="$router.push('/customer/customerInformation')">
              <span style="display: block">{{ translations[language].personalCenter }}</span>
            </el-dropdown-item>
            <!-- 退出登录菜单项 -->
            <el-dropdown-item @click.native="logout">
              <span style="display: block">{{ translations[language].logout }}</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <!-- 悬浮面板：显示生态与合作的详细子菜单 -->
    <div @mouseleave="sildeOut" @mouseenter="keepPanel" v-show="isShowPanel" class="panel">
      <div class="inPanel">
        <!-- 左侧面板：一级和二级菜单 -->
        <div class="panelLeft">
          <ul class="outUl">
            <li style="cursor: default" class="outLi" v-for="item in showPanelData" :key="item.firTitle">
              <span style="cursor: default!important;" :class="['tilte', 'activeFir']">
                {{
                  getTranslation(item.firTitle)
                }}
              </span>
              <ul class="inUl">
                <li class="inLi" v-for="i in item.secMenu" :key="i.id">
                  <span style="position: relative" @mouseenter="sildeSecMenu(i)"
                    :class="['twoMenuStyle', secId === i.id ? 'activeSec' : '']">{{ getTranslation(i.secTitle) }}</span>
                </li>
              </ul>
            </li>
          </ul>
        </div>
        <!-- 分隔线 -->
        <span class="ge"></span>
        <!-- 左侧面板：三级菜单（如果存在且不等于二级菜单标题） -->
        <div
          v-if="secMenuData.length > 0 && secMenuData[0].thrMenu && secMenuData[0].thrMenu.length > 0 && secMenuData[0].thrMenu[0].thrTitle != null && secMenuData[0].secTitle !== secMenuData[0].thrMenu[0].thrTitle"
          class="panelLeft">
          <ul>
            <li style="font-size: 14px!important;" @mouseenter="sildeThrMenu(thr)" v-for="(thr, index) in threeData"
              :key="index">
              {{ getTranslation(thr.thrTitle) }}
            </li>
          </ul>
        </div>
        <!-- 分隔线 -->
        <span
          v-if="secMenuData.length > 0 && secMenuData[0].thrMenu && secMenuData[0].thrMenu.length > 0 && secMenuData[0].thrMenu[0].thrTitle != null && secMenuData[0].secTitle !== secMenuData[0].thrMenu[0].thrTitle"
          class="ge"></span>
        <!-- 右侧面板：最细粒度的菜单项 -->
        <div class="panelRight"
          v-if="showPanelRightData.length > 0 && showPanelRightData[0] && showPanelRightData[0].value">
          <ul class="leastMenu inBox">
            <li class="clickItem" style="font-size: 14px!important;margin: 8px 0;cursor: pointer"
              v-for="itemR in showPanelRightData[0].value" :key="itemR.id" @click="clickGo(itemR)">
              {{ getTranslation(itemR.name) }} <span v-if="itemR.discount" class="zhe">{{
                itemR.discount }}折</span>
            </li>
          </ul>
        </div>
        <!-- 当没有数据时显示空状态 -->
        <div class="panelRight" v-else>
          <div style="text-align: center; color: #999; padding: 20px;">
            {{ translations[language].noData }}
          </div>
        </div>
      </div>
    </div>

    <!-- 消息中心组件 -->

    <message-center ref="messageCenter" :visible.sync="messageCenterVisible" :userId="userId"
      @unread-count-update="handleUnreadCountUpdate" />
  </div>
</template>

<script>
import Vue from 'vue'
// 导入测试数据（可能用于本地开发或模拟）
import { computingData, networkData, storageData, testData } from "@/views/homePage/components/topBox/testData";
// 导入API请求函数
import { reqNavList, reqNewHomeFestival, reqNewHomeSync } from "@/api/newHome";
// 导入Vuex辅助函数
import { mapGetters, mapState } from "vuex";
// 导入其他API函数
import { getLogoAPI, getUserInfoAPI } from "@/api/login";
import { reqApplyChannel } from "@/api/customer/channel";
// 导入store实例
import store from "@/store";
// 导入工具函数
import { getHomePath } from '@/views/setting/tools'
// 导入语言管理
import { languageStore, languageBus } from '@/utils/language'

// 导入消息中心组件
import MessageCenter from '@/components/MessageCenter/MessageCenter.vue'

export default Vue.extend({
  name: "TopBox",
  components: {
    MessageCenter
  },
  data() {
    return {
      homePath: getHomePath(), // 首页路径
      isShowKbossCharge: false, // 是否显示Kboss充值按钮
      role: sessionStorage.getItem("jueseNew") == "admin" ? [] : sessionStorage.getItem("jueseNew"), // 用户角色
      userId: sessionStorage.getItem("userId"), // 用户ID
      firId: "", // 一级菜单ID
      secId: "", // 二级菜单ID
      nick_name: "", // 用户昵称
      showTimer: null, // 显示面板的定时器
      hideTimer: null, // 藏面板的定时器
      showPanelData: [], // 展示的面板数据
      secMenuData: [], // 二级菜单数据
      showPanelRightData: [], // 展示的右侧面板数据
      threeData: [], // 三级菜单数据
      fourData: [], // 四级菜单数据（未使用）
      product_service: [], // 产品服务数据
      language: 'zh', // 默认设置为中文
      languageChangedHandler: null, // 语言变化事件处理器
      messageCount: 0, // 未读消息数量
      translations: {
        zh: {
          home: '首页',
          ecosystem: '产品与服务',
          supply: '供需广场',
          aboutUs: '关于我们',
          balance: '余额',
          recharge: '充值',
          personalCenter: '个人中心',
          logout: '退出登录',
          searchPlaceholder: '搜索',
          console: '控制台',
          login: '登录',
          register: '立即注册',
          noData: '暂无数据',
          // 一级菜单翻译
          '云': '云',
          '算': '算',
          '网': '网',
          '用': '用',
          // 二级菜单翻译
          '百度云': '百度云',
          '智算': '智算',
          '算力网络': '算力网络',
          'AI应用': 'AI应用',
          // 三级菜单翻译
          '计算': '计算',
          '网络': '网络',
          '存储': '存储',
          '数据库': '数据库',
          '泛CDN': '泛CDN',
          'AI能力引擎': 'AI能力引擎',
          '云与业务安全': '云与业务安全',
          '大数据平台': '大数据平台',
          '云原生平台': '云原生平台',
          '智能内容科技': '智能内容科技',
          'SME企业服务': 'SME企业服务',
          '视频云平台': '视频云平台',
          '智能短信': '智能短信',
          '智慧医疗': '智慧医疗',
          '智慧客服': '智慧客服',
          // 产品名称翻译
          '云服务器_GPU': '云服务器_GPU',
          '云服务器_BCC': '云服务器_BCC',
          '专属服务器': '专属服务器',
          '轻量应用服务器': '轻量应用服务器',
          '专线接入': '专线接入',
          '对等连接': '对等连接',
          '智能云解析': '智能云解析',
          '弹性公网IP': '弹性公网IP',
          'IPv6公网网关': 'IPv6公网网关',
          '共享带宽': '共享带宽',
          'NAT网关': 'NAT网关',
          '智能流量管理': '智能流量管理',
          'EIP带宽包': 'EIP带宽包',
          'VPN网关': 'VPN网关',
          '服务网卡': '服务网卡',
          '云智能网': '云智能网',
          '负载均衡': '负载均衡',
          '文件存储': '文件存储',
          '对象存储': '对象存储',
          '云磁盘': '云磁盘',
          '内容分发网络': '内容分发网络',
          '数据可视化私有化': '数据可视化私有化',
          '消息服务 for Kafka': '消息服务 for Kafka',
          '云数据库RDS': '云数据库RDS',
          'MapReduce': 'MapReduce',
          '云数据库SCS for Redis': '云数据库SCS for Redis',
          '云数据库HBase': '云数据库HBase',
          '云数据库DocDB for MongoDB': '云数据库DocDB for MongoDB',
          '数据传输服务': '数据传输服务',
          '音视频直播': '音视频直播',
          '动态加速': '动态加速',
          '文字识别': '文字识别',
          '语音能力引擎': '语音能力引擎',
          '自然语言处理': '自然语言处理',
          '图像识别': '图像识别',
          '图像搜索': '图像搜索',
          '卡证识别': '卡证识别',
          '图像增强与特效': '图像增强与特效',
          '人脸识别': '人脸识别',
          '机器翻译': '机器翻译',
          '密钥管理服务': '密钥管理服务',
          '主机安全': '主机安全',
          '云防火墙': '云防火墙',
          '应用防火墙': '应用防火墙',
          '入侵检测系统': '入侵检测系统',
          '云堡垒机': '云堡垒机',
          'DDoS防护服务': 'DDoS防护服务',
          '实时音视频': '实时音视频',
          '音视频处理': '音视频处理',
          'Elasticsearch': 'Elasticsearch',
          '数据仓库DORIS': '数据仓库DORIS',
          '商标知产服务': '商标知产服务',
          '容器引擎': '容器引擎',
          '工商财税服务': '工商财税服务',
          '媒体内容分析': '媒体内容分析',
          '备案服务': '备案服务',
          '智能门户': '智能门户',
          '容器镜像服务': '容器镜像服务',
          '域名服务': '域名服务',
          '简单消息服务': '简单消息服务',
          '容器云': '容器云',
          '裸金属': '裸金属',
          '一体机-昆仑芯': '一体机-昆仑芯',
          '一体机-天数智芯': '一体机-天数智芯',
          '互联网专线': '互联网专线',
          'SDWAN': 'SDWAN',
          'DCI': 'DCI',
          'AI专线': 'AI专线',
          '灵医智能体': '灵医智能体',
          '客悦·智能客服': '客悦·智能客服'
        },
        en: {
          home: 'Home',
          ecosystem: 'Products & Services',
          supply: 'Supply',
          aboutUs: 'About Us',
          balance: 'Balance',
          recharge: 'Recharge',
          personalCenter: 'Personal Center',
          logout: 'Logout',
          searchPlaceholder: 'Search',
          console: 'Console',
          login: 'Login',
          register: 'Register Now',
          noData: 'No Data',
          // 一级菜单翻译
          '云': 'Cloud',
          '算': 'Computing',
          '网': 'Network',
          '用': 'Application',
          // 二级菜单翻译
          '百度云': 'Baidu Cloud',
          '智算': 'Intelligent Computing',
          '算力网络': 'Computing Power Network',
          'AI应用': 'AI Application',
          // 三级菜单翻译
          '计算': 'Compute',
          '网络': 'Network',
          '存储': 'Storage',
          '数据库': 'Database',
          '泛CDN': 'CDN',
          'AI能力引擎': 'AI Engine',
          '云与业务安全': 'Cloud & Business Security',
          '大数据平台': 'Big Data Platform',
          '云原生平台': 'Cloud Native Platform',
          '智能内容科技': 'Intelligent Content Tech',
          'SME企业服务': 'SME Enterprise Service',
          '视频云平台': 'Video Cloud Platform',
          '智能短信': 'Smart SMS',
          '智慧医疗': 'Smart Healthcare',
          '智慧客服': 'Smart Customer Service',
          // 产品名称翻译
          '云服务器_GPU': 'Cloud Server GPU',
          '云服务器_BCC': 'Cloud Server BCC',
          '专属服务器': 'Dedicated Server',
          '轻量应用服务器': 'Lightweight App Server',
          '专线接入': 'Direct Connect',
          '对等连接': 'Peer Connection',
          '智能云解析': 'Smart Cloud DNS',
          '弹性公网IP': 'Elastic Public IP',
          'IPv6公网网关': 'IPv6 Public Gateway',
          '共享带宽': 'Shared Bandwidth',
          'NAT网关': 'NAT Gateway',
          '智能流量管理': 'Smart Traffic Management',
          'EIP带宽包': 'EIP Bandwidth Package',
          'VPN网关': 'VPN Gateway',
          '服务网卡': 'Service Network Card',
          '云智能网': 'Cloud Smart Network',
          '负载均衡': 'Load Balancer',
          '文件存储': 'File Storage',
          '对象存储': 'Object Storage',
          '云磁盘': 'Cloud Disk',
          '内容分发网络': 'Content Delivery Network',
          '数据可视化私有化': 'Data Visualization Private',
          '消息服务 for Kafka': 'Message Service for Kafka',
          '云数据库RDS': 'Cloud Database RDS',
          'MapReduce': 'MapReduce',
          '云数据库SCS for Redis': 'Cloud Database SCS for Redis',
          '云数据库HBase': 'Cloud Database HBase',
          '云数据库DocDB for MongoDB': 'Cloud Database DocDB for MongoDB',
          '数据传输服务': 'Data Transfer Service',
          '音视频直播': 'Audio/Video Live',
          '动态加速': 'Dynamic Acceleration',
          '文字识别': 'Text Recognition',
          '语音能力引擎': 'Speech Engine',
          '自然语言处理': 'Natural Language Processing',
          '图像识别': 'Image Recognition',
          '图像搜索': 'Image Search',
          '卡证识别': 'Card/Certificate Recognition',
          '图像增强与特效': 'Image Enhancement & Effects',
          '人脸识别': 'Face Recognition',
          '机器翻译': 'Machine Translation',
          '密钥管理服务': 'Key Management Service',
          '主机安全': 'Host Security',
          '云防火墙': 'Cloud Firewall',
          '应用防火墙': 'Application Firewall',
          '入侵检测系统': 'Intrusion Detection System',
          '云堡垒机': 'Cloud Bastion Host',
          'DDoS防护服务': 'DDoS Protection Service',
          '实时音视频': 'Real-time Audio/Video',
          '音视频处理': 'Audio/Video Processing',
          'Elasticsearch': 'Elasticsearch',
          '数据仓库DORIS': 'Data Warehouse DORIS',
          '商标知产服务': 'Trademark & IP Service',
          '容器引擎': 'Container Engine',
          '工商财税服务': 'Business & Tax Service',
          '媒体内容分析': 'Media Content Analysis',
          '备案服务': 'Filing Service',
          '智能门户': 'Smart Portal',
          '容器镜像服务': 'Container Image Service',
          '域名服务': 'Domain Name Service',
          '简单消息服务': 'Simple Message Service',
          '容器云': 'Container Cloud',
          '裸金属': 'Bare Metal',
          '一体机-昆仑芯': 'All-in-One Kunlun Chip',
          '一体机-天数智芯': 'All-in-One Days Chip',
          '互联网专线': 'Internet Leased Line',
          'SDWAN': 'SDWAN',
          'DCI': 'DCI',
          'AI专线': 'AI Leased Line',
          '灵医智能体': 'LingYi Medical AI',
          '客悦·智能客服': 'KeYue Smart Customer Service'
        }
      }
    }
  },
  created() {
    // 组件创建时初始化homePath
    this.homePath = getHomePath()
    // 如果sessionStorage中有userId，则设置登录状态为true
    if (sessionStorage.getItem('userId')) {
      this.$store.commit('setLoginState', true); // 同步到 Vuex
    }
    // 如果不需要显示注册按钮，则获取用户信息
    !this.showRegisterButton && this.getUserInfo();

    // 初始化组件
    this.init()

    // 修复：确保从共享状态获取当前语言
    this.initLanguage()

    // 初始化导航数据
    this.initData()
  },
  mounted() {
    // 组件挂载时，从sessionStorage获取用户名
    if (sessionStorage.getItem("username")) {
      this.nick_name = sessionStorage.getItem("username");
    }
    // 滚动到顶部容器
    this.$nextTick(() => {
      const topContainer = document.getElementById('topContainer');
      if (topContainer) {
        topContainer.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        });
      }
    });
  },
  beforeDestroy() {
    // 移除事件监听
    if (this.languageChangedHandler) {
      languageBus.$off('language-changed', this.languageChangedHandler)
    }
  },
  computed: {
    // 映射Vuex中的getters
    ...mapGetters(["sidebar", "avatar", "device"]),
    // 映射Vuex中的state
    ...mapState({
      isShowPanel: (state) => state.product.showHomeNav, // 是否显示导航面板
      navIndex: (state) => state.product.navIndex, // 导航索引
      gridObj: state => state.operationAnalysis.gridObj, // 未使用
      mybalance: state => state.user.mybalance, // 用户余额
      logoutUrl: state => state.login.logoutUrl, // 退出登录URL
      loginStateVuex: state => state.login.loginState, // Vuex中的登录状态
      logoInfoNew: state => state.product.logoInfoNew, // Logo信息
    }),
    // 计算登录状态：基于Vuex状态或sessionStorage中的userId
    loginState() {
      const userId = sessionStorage.getItem('userId');
      return this.loginStateVuex || (userId !== null && userId !== 'null' && userId !== '');
    },
    // 计算是否显示注册按钮：基于组织类型和用户登录状态
    showRegisterButton() {
      const orgType = window.sessionStorage.getItem('org_type');
      const userId = window.sessionStorage.getItem('userId');
      console.log("此时是:", orgType !== '2' && orgType !== '3' && userId !== null)
      return orgType !== '2' && orgType !== '3' && userId === null;
    },
    // 计算用户名
    username() {
      return sessionStorage.getItem('username') || '';
    },
  },
  methods: {
    // 处理消息图标点击
    handleMessageClick() {
      if (this.loginState) {
        // 已登录状态：打开消息中心
        // 已登录状态：打开消息中心
        this.messageCenterVisible = true;
        // 同时调用组件方法确保初始化
        if (this.$refs.messageCenter) {
          this.$refs.messageCenter.open();
        }
      } else {
        // 未登录状态：跳转到登录页
        this.handleGoLogin()
      }
    },

    // 处理未读消息数量更新
    handleUnreadCountUpdate(count) {
      this.messageCount = count;
    },

    // 初始化语言状态
    initLanguage() {
      // 直接从store获取当前语言，确保一致性
      this.language = languageStore.getLanguage()
      console.log('topBox初始化语言:', this.language)

      // 保存事件处理函数的引用，以便正确移除
      this.languageChangedHandler = (lang) => {
        console.log('topBox接收到语言变化:', lang)
        this.language = lang
      }

      // 监听语言变化事件
      languageBus.$on('language-changed', this.languageChangedHandler)
    },

    // 切换语言 - 统一使用共享状态
    toggleLanguage() {
      const newLanguage = this.language === 'zh' ? 'en' : 'zh';
      console.log('topBox切换语言到:', newLanguage);

      // 使用共享状态管理，确保所有组件同步
      languageStore.setLanguage(newLanguage);

      // 调试信息
      setTimeout(() => {
        console.log('切换后验证 - topBox语言:', this.language);
        console.log('切换后验证 - store语言:', languageStore.getLanguage());
      }, 200);
    },

    // 获取翻译文本的通用方法
    getTranslation(key) {
      if (!key) return ''
      return this.translations[this.language]?.[key] || key
    },

    // 调试语言状态
    debugLanguage() {
      console.log('=== topBox语言调试信息 ===');
      console.log('当前语言:', this.language);
      console.log('languageStore状态:', languageStore.getLanguage());
      console.log('localStorage状态:', localStorage.getItem('language'));
      languageStore.debug();
    },

    // 控制台按钮点击事件：根据角色跳转不同页面
    goB() {
      if (sessionStorage.getItem('jueseNew').includes('客户')) {
        this.$router.push('/product/productHome')
      } else if (sessionStorage.getItem('jueseNew').includes('运营')) {
        this.$router.push('/operation/supplierManagement')
      }
    },

    // 初始化Logo信息
    init() {
      let remoteUrl = ''
      // 根据环境设置API基础URL
      if (window.location.href.includes("dev")) {
        remoteUrl = 'https://www.kaiyuancloud.cn/dev/reseller/get_ipc_logo.dspy'
      } else if (window.location.href.includes("localhost")) {
        remoteUrl = 'http://localhost:9527/'
      } else {
        remoteUrl = 'https://www.kaiyuancloud.cn/reseller/get_ipc_logo.dspy'
      }

      let params = {
        url_link: window.location.href.split("#")[0] // 获取当前页面URL
      }
      getLogoAPI(params).then((res) => {
        console.log("获取接口触发了")
        if (res.status == true && res.data && res.data.length) {
          console.log("res.data[0].additional_msg", res.data[0].additional_msg)
          // 提交Logo信息到Vuex
          this.$store.commit('setLogoInfoNew', res.data[0].additional_msg);
          this.isShow = true
          if (res.data[0].orgname == '中关村数智人工智能产业联盟') {
            this.logoUrlOut = 'https://www.ncmatch.cn'
          }

          this.photosUrl = res.data[0];
          if (this.photosUrl.orgname != '业主机构') {
            this.isLogo = true
            this.logoImg = this.photosUrl.logo;

            this.$store.commit('setLogo', this.photosUrl.logo)
            this.logoText = this.photosUrl.orgname;
          } else {
            this.$store.commit('setLogo', "")
          }
        } else {
          this.$message({
            // message: res.msg,
            message: "获取ipc失败~",
            type: "error",
          });
        }
      });
    },

    // 退出登录
    async logout() {
      this.$store.commit('setLoginState', false) // 设置Vuex登录状态为false

      // 清除本地存储
      store.commit('tagsView/resetBreadcrumbState');
      sessionStorage.removeItem("auths");
      sessionStorage.removeItem("routes");
      sessionStorage.removeItem("user");
      sessionStorage.removeItem("userId");
      sessionStorage.removeItem("org_type")

      localStorage.removeItem("auths");
      localStorage.removeItem("routes");
      localStorage.removeItem("user");
      localStorage.removeItem("userId");
      localStorage.removeItem("org_type")
      localStorage.removeItem('userId')

      // 如果当前页面不是首页，则跳转到首页
      if (!window.location.href.includes('homePage/index')) {
        await this.$router.push(getHomePath());
      }
    },

    // 修改密码
    edituserPassword() {
      this.passwordDialog = true;
    },

    // 申请渠道管理
    channelFirstBtn() {
      reqApplyChannel({ user_id: this.userId }).then(res => {
        if (res.code == "100" || res.code == "210") {
          this.$message.success(res.msg)
        } else if (res.code == "300") {
          this.channelManagementShow = true
        } else if (res.code == "200") {
          this.$router.push('/customer/channelMangement')
        }
      })
    },

    // 初始化余额（从sessionStorage获取）
    initMybalance() {
      return sessionStorage.getItem('mybalance')
    },

    // 复制用户ID
    copyBtn() {
      const textToCopy = this.$refs.contentToCopy.innerText;
      navigator.clipboard.writeText(textToCopy).then(() => {
        this.$message.success('复制成功！')
      }).catch((error) => {
        console.error('复制失败', error);
      });
    },

    // 获取用户信息
    async getUserInfo() {
      getUserInfoAPI({ id: this.userId }).then((res) => {
        if (res.status) {
          // this.nick_name = res.data[0].nick_name;
          this.userInfoList = res.data;
          sessionStorage.setItem("orgid", res.data[0].orgid);
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },

    // 处理下拉菜单显示/隐藏时的图标旋转
    handleShow(isShow) {
      let resverNode = document.getElementById('resverIcon')

      if (isShow) {
        if (this.role.includes('客户')) {
          this.$store.dispatch('user/getCustmoersMoney') // 获取客户余额
        }

        resverNode.style.transform = 'rotate(180deg)' // 旋转图标
      } else {
        resverNode.style.transform = 'rotate(0)' // 恢复图标
      }
    },

    // 鼠标进入三级菜单项
    sildeThrMenu(item) {
      console.log("it", item)
      let res = []
      res.push(item)
      this.showPanelRightData = res
    },

    // 点击菜单项进行跳转或打开新窗口
    clickGo(item) {
      this.$store.commit('setShowHomeNav', false) // 隐藏导航面板
      console.log("电机的item是", item)
      let userId = sessionStorage.getItem('userId')
      const orgType = window.sessionStorage.getItem('org_type');
      let isKehu = orgType === '2' || orgType === '3';
      console.log("userId", userId)
      if (item.type === '百度云') {
        if (this.loginState) {
          // 百度云产品跳转逻辑
          this.$store.commit('setRedirectUrl', item.url)
          localStorage.setItem('redirectUrl', item.url)
          localStorage.setItem('userRescourseUrl', item.listUrl)
          this.$router.push({
            name: 'baiduProductShow',
            params: {
              listUrl: item.listUrl,
              url: item.url
            }
          })
        } else {
          this.$router.push({
            path: "/login",
            query: {
              fromPath: 'homePage',
              type: 'bd',
              listUrl: item.listUrl,
              url: item.url
            }
          })
        }
      } else if (item.type === '阿里云') {
        if (this.loginState) {
          // 阿里云同步和节日活动逻辑
          reqNewHomeSync().then(response => {
            if (response.status) {
              reqNewHomeFestival().then(res => {
                if (res.status) {
                  window.open(res.data) // 打开阿里云页面
                } else {
                  this.$message.warning(res.msg)
                }
              })
            } else {
              this.$message.warning(response.msg)
            }
          })
        } else {
          this.$router.push({
            path: "/login",
            query: {
              fromPath: 'homePage',
              type: 'ali',
            }
          })
        }
      } else if (item.type === '智算' || item.type === '算力网络') {
        if (item.name === '容器云') {
          if (this.loginState) {
            this.$router.push('/product/productHome/k8s/createK8s')
          } else {
            this.$router.push({
              path: "/login",
              query: {
                fromPath: 'homePage',
                type: 'rqy',
              }
            })
          }
        } else {
          this.$router.push({
            path: '/homePage/detail',
            query: {
              id: item.id,
            }
          })
        }
      } else if (item.name === '灵医智能体') {
        this.$router.push('/homePage/hospital')
      } else if (item.name === '客悦·智能客服') {
        this.$router.push('/homePage/customerService')
      }
    },

    // 改变面板数据
    changeData(data) {
      this.showPanelData = data || []

      // 更安全的初始化方式
      this.secMenuData = data?.[0]?.secMenu || []

      // 初始化threeData和showPanelRightData
      if (this.secMenuData.length > 0) {
        const firstSecMenu = this.secMenuData[0]
        this.threeData = firstSecMenu.thrMenu || []

        // 处理thrTitle为null的情况
        if (this.threeData.length > 0) {
          this.showPanelRightData = this.threeData.map(item => ({
            ...item,
            thrTitle: item.thrTitle || firstSecMenu.secTitle
          }))
        } else {
          this.showPanelRightData = [{
            thrTitle: firstSecMenu.secTitle,
            value: []
          }]
        }
      } else {
        this.threeData = []
        this.showPanelRightData = []
      }
    },

    // 初始化导航数据
    initData() {
      reqNavList({ url_link: window.location.href }).then(res => {
        console.log("res", res.data.product_service)
        if (res.status) {
          this.product_service = this.buildData(res.data.product_service) // 构建数据结构
          this.changeData(this.product_service)
        }
      }).catch(error => {
        console.error("获取导航数据失败:", error)
        // 可以设置一些默认数据或显示错误信息
        this.product_service = []
        this.changeData([])
      })
    },

    // 构建导航数据结构
    buildData(data) {
      let res = [];
      data.forEach(item => {
        if (item.secMenu && Array.isArray(item.secMenu)) {
          item.secMenu.forEach(secItem => {
            if (secItem.thrMenu && Array.isArray(secItem.thrMenu)) {
              secItem.thrMenu.forEach(thrItem => {
                if (thrItem.value && Array.isArray(thrItem.value)) {
                  thrItem.value.forEach(valueItem => {
                    valueItem.type = secItem.secTitle; // 添加type属性，值为secTitle
                  });
                }
              });
            }
          });
        }
      });
      return data; // 返回修改后的原始数据
    },

    // 鼠标进入二级菜单项
    sildeSecMenu(item) {
      console.log("获取的item时", item)
      this.secId = item.id

      // 处理thrMenu可能为空或thrTitle为null的情况
      if (!item.thrMenu || item.thrMenu.length === 0) {
        this.threeData = []
        this.showPanelRightData = [{
          thrTitle: item.secTitle,
          value: []
        }]
        return
      }

      // 处理thrTitle为null的情况
      this.threeData = item.thrMenu.map(menu => ({
        ...menu,
        thrTitle: menu.thrTitle || item.secTitle
      }))

      this.showPanelRightData = this.threeData
    },

    // 返回测试数据（未使用）
    networkData() {
      return networkData
    },
    storageData() {
      return storageData
    },
    testData() {
      return testData
    },

    // 鼠标进入一级菜单项
    sildeItemIn(item) {
      this.firId = item.id
      this.secId = item.secMenu[0].id
      console.log("获取的item时", item)
      this.secMenuData = item.secMenu || []
      this.showPanelRightData = this.secMenuData[0].thrMenu || []
    },
    computingData() {
      return computingData
    },

    // 鼠标进入生态与合作菜单
    sildeIn(item) {
      console.log("sildeIn", item)
      this.changeData(item)
      if (this.hideTimer) {
        clearTimeout(this.hideTimer)
      }
      // 延时显示面板，避免鼠标快速移动时面板闪烁
      this.showTimer = setTimeout(() => {
        this.$store.commit('setShowHomeNav', true)
      }, 100)
    },

    // 鼠标离开导航区域
    sildeOut() {
      if (this.showTimer) {
        clearTimeout(this.showTimer)
      }
      // 延时隐藏面板，给鼠标移动到面板上的时间
      this.hideTimer = setTimeout(() => {
        this.$store.commit('setShowHomeNav', false)
      }, 200)
    },

    // 鼠标进入面板区域，取消隐藏
    keepPanel() {
      if (this.hideTimer) {
        clearTimeout(this.hideTimer)
      }
    },

    // 处理登录跳转逻辑
    handleGoLogin() {
      let token = this.$store.getters.token;
      if (!token) {
        // 提示登录
        this.$message.warning('请先登录哦~');
        this.$router.push({
          path: '/login'
        });
      } else {

      }
    }
  },
})
</script>

<style scoped lang="less">
.top-nav {
  font-size: 18px !important;

  * {
    font-size: 18px !important;
  }

  font-weight: 500;
  color: #222F60 !important;
  position: relative;
  background-color: #fff;
  box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.08);
  width: 100%;
  z-index: 1000;

  .container {
    font-size: 18px;
    width: 100%;
    height: 100%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 20px;
  }

  .logo {
    display: flex;
    align-items: center;

    .logoImg {
      width: 148px;
    }
  }

  .main-nav {
    margin-left: 44px;
    z-index: 10000;

    .nav-list {
      display: flex;
      list-style: none;
      margin: 0;
      padding: 0;

      p {
        height: 100%;
        padding-right: 40px;
        position: relative;

        a {
          text-decoration: none;
          font-size: 18px !important;
          padding: 5px 0;
          transition: all 0.3s;

          &:hover {
            color: #1E6FFF;
          }
        }

        &.active a {
          color: #1E6FFF;
          font-weight: bold;
        }
      }
    }
  }

  .user-area {
    display: flex;
    align-items: center;

    .search-box {
      display: flex;
      align-items: center;
      border: 2px solid #d2d7e6;
      border-radius: 8px;
      padding: 8px;

      input {
        margin-left: 10px;
        border: 0;
        outline: none;
      }
    }

    .language-toggle {
      cursor: pointer;
      margin-right: 20px;
      // width: 60px;
      text-align: center;
      border-radius: 4px;
      font-size: 14px;
      text-decoration: none;
      transition: all 0.3s;
      color: #333;
      z-index: 1001;
      display: flex;
      align-items: center;

      .icon-ditu_diqiu_o {
        margin-right: 5px;
        font-size: 24px !important;
      }

      &:hover {
        color: #1E6FFF;
      }
    }

    a {
      // padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      text-decoration: none;
      // margin-left: 10px;
      transition: all 0.3s;
    }

    .login-btn {
      margin-right: 20px;
      color: #333;

      &:hover {
        color: #1E6FFF;
      }
    }

    .register-btn {
      // height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: linear-gradient(90deg, #275AFF 0%, #2EBDFA 100%);
      border-radius: 10px;
      padding: 6px 10px;
      color: white;

      &:hover {
        opacity: 0.9;
      }
    }

    .icon-xiaoxi {
      font-size: 24px !important;
    }

    .functions {
      padding-right: 20px;
      font-size: 20px;
      color: #000;

      &:hover {
        color: #1E6FFF;
      }
    }

  }
}

.panel {
  .inPanel {
    padding: 20px;
    border-radius: 8px;

    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    height: calc(100vh - 100px);
    background: #fff;
    margin: 10px 20px 20px;
    margin-left: 0;
    margin-right: 0;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    transition: opacity 0.3s ease;
  }

  display: flex;
  flex-direction: column;

  justify-content: flex-start;
  align-items: center;
  color: #091221;
  position: absolute;
  top: 84px;
  left: 0;
  width: calc(100% - 450px);
  margin-left: 250px;
  z-index: 999;
  overflow-y: auto;

  .panelLeft {
    height: 100% !important;
    justify-content: stretch;
    font-size: 14px !important;
    width: 200px;
    overflow-y: auto;

    li {
      padding: 10px;
      //cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        cursor: pointer;
        color: #1E6FFF;
      }
    }
  }

  .panelRight {
    flex: 1;
    padding-left: 20px;
    overflow-y: auto;
  }
}

.activeFir {
  background-image: linear-gradient(90deg, rgba(210, 228, 253, .6), hsla(0, 0%, 100%, .6));
  border-radius: 4px;
  cursor: pointer;
}

.twoMenuStyle {
  cursor: pointer;
  position: relative;
  color: #091221;
  font-size: 14px !important;

  &::after {
    transition: all .3s ease-in-out;
    content: '';
    width: 0;
    position: absolute;
    bottom: -5px;
    left: 0;
    height: 2px;
    background: #091221;
    border-radius: 1px;
  }
}

.activeSec {
  font-weight: 600;

  &::after {
    width: 100% !important;
  }
}

.subTitle {
  font-size: 16px;
  color: #2468f2;
  font-weight: 600;
  margin: 5px 0;
  display: inline-block;
}

.leastMenu {
  overflow-y: auto;

  .inBox {
    li {
      font-size: 14px !important;
      margin: 6px 0;
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;

      &:hover {
        cursor: pointer;
        color: #1E6FFF !important;
      }
    }
  }
}

.ge {
  background-image: url('https://bce.bdstatic.com/portal-cloud-server/images/nav/dropdown_bar_middle.png');
  box-sizing: border-box;
  display: block;
  height: 100%;
  width: 20px;
  margin: 0 10px;
}

.zhe {
  font-size: 12px !important;
  border-radius: 4px;
  padding: 1px 2px;
  color: red;
  display: inline-block;
  margin-left: 3px;
}

.outUl {
  .outLi {
    padding: 10px;

    .tilte {
      width: 100%;
      display: inline-block;
      padding: 5px;
    }

    .inUl {
      .inLi {
        padding: 10px 10px 10px 5px;
      }
    }
  }
}

.logoImg {
  width: 148px;
  height: 48px;
}

.clickItem {
  //margin: 30px 0 !important;
  margin-bottom: 15px !important;

  &:hover {
    color: #1E6FFF !important;
  }
}

.imgUser {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  color: white;
  margin-right: 8px;

  img {
    width: 40px;
    height: 40px;
  }
}

.company-name {
  font-size: 24px;
  font-weight: bold;
  color: #222F60;
  cursor: pointer;
  transition: color 0.3s ease;

  &:hover {
    color: #1E6FFF;
  }
}
</style>
