<template>
  <div class="main-container">
    <template v-if="alreadyLogin">
      <!-- 顶部导航栏 -->
      <el-header class="top-header">
        <!-- Logo区域 -->
        <div class="logo-container">
          <!-- Logo显示（根据屏幕尺寸切换） -->
          <img v-if="!isMobile" src="../public/logobig.svg" @click="handleLeftClick('home')" style="cursor: pointer; height: 30px;" />
          <img v-else="isMobile" src="../public/logo.svg" @click="handleLeftClick('home')" style="cursor: pointer; height: 30px; margin-right: 10px;" />
        </div>

        <!-- 横向菜单（桌面端显示）暂时v-show隐藏，不能删除 -->
        <el-menu ref="parentRef"
                 mode="horizontal"
                 v-show="false"
                 class="horizontal-menu"
                 :default-active="currentTitle.routes"
                 @select="menuChange">
          <template v-for="menu in menuValue" :key="menu.label">
            <el-sub-menu v-if="menu.options" :index="menu.value">
              <template #title>
                <el-icon>
                  <component :is="menu.icon" />
                </el-icon>
                <span>{{ menu.label }}</span>
              </template>
              <el-menu-item v-for="item in menu.options"
                            :key="item.value"
                            :index="item.value">
                <el-icon>
                  <component :is="item.icon" />
                </el-icon>
                {{ item.label }}
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index="menu.value">
              <el-icon>
                <component :is="menu.icon" />
              </el-icon>
              {{ menu.label }}
            </el-menu-item>
          </template>
        </el-menu>

        <!-- 中间区域 -->
        <div class="header-center">
          <img src="../public/pic/BLWTG.png" class="center-logo" />
          <span class="center-text">宝来威-天工平台</span>
        </div>

        <!-- 右侧操作区 -->
        <div class="header-right">
<!--          <el-select v-model="selectedProjectId" placeholder="请选择项目" filterable clearable @change="handleProjectChangeApp"
                     style="width:250px;margin: 0 10px;" :disabled="isProjectLocked">
            <el-option v-for="project in projectList" :key="project.id" :label="project.projectName" :value="project.id" />
          </el-select>
          <el-popover placement="bottom-end" :width="1100" trigger="click">
            <template #reference>
              <el-button v-if="selectedProject">项目详情</el-button>
            </template>
            <template #default>
              <el-descriptions border column="4" size="small" class="details" v-if="selectedProject">
                <el-descriptions-item label="项目名称">{{ selectedProject.projectName }}</el-descriptions-item>
                <el-descriptions-item label="详细地址">{{ selectedProject.addressDetail }}</el-descriptions-item>
                <el-descriptions-item label="所在地区">{{ selectedProject.quyu }} · {{ selectedProject.shengfen }}</el-descriptions-item>
                <el-descriptions-item label="项目编号">{{ selectedProject.projectCode }}</el-descriptions-item>
                <el-descriptions-item label="审批状态">
                  <el-tag size="small" :type="selectedProject.shengpiStatus === '3' ? 'success' : 'warning'">
                    {{ selectedProject.shengpiStatus === '3' ? '已批准' : '待审批' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="报备信息">{{ selectedProject.customization }}</el-descriptions-item>
                <el-descriptions-item label="房间信息">{{ selectedProject.roomTypeCount }} 种房型 · {{ selectedProject.roomTotalCount }} 间客房</el-descriptions-item>
                <el-descriptions-item label="最后更新">{{ formatDate(selectedProject.updatetime) }}</el-descriptions-item>
              </el-descriptions>
            </template>
          </el-popover>-->

          <!-- 刷新 -->
<!--          <el-button link size="large" style="font-size:22px"
                     @click="refreshToHome"
                     icon="Refresh" />-->

          <!-- 用户头像 -->
          <el-popover v-model:visible="showPopover"
                      placement="bottom-end"
                      trigger="click">
            <template #reference>
              <el-avatar class="user-avatar"
                         :src="userAvatar" />
            </template>
            <div class="user-menu">
              <el-button link @click="handleAction('logout')">退出登录</el-button>
            </div>
          </el-popover>
        </div>
      </el-header>

      <!-- 路由内容区 -->
      <div class="router-container" :class="{'mobile-view': isMobile}">
        <keep-alive :include="cachedViews">
          <router-view v-slot="{ Component }">
            <component :is="Component"
                       :key="route.fullPath"
                       class="router-view-container" />
          </router-view>
        </keep-alive>
      </div>
    </template>

    <template v-else>
      <router-view />
    </template>

    <el-footer class="global-footer" :class="{'mobile-footer': isMobile}" v-if="!isMobile">
      Copyright © 2025 宝来威智能(广东)有限公司. All Rights Reserved.
    </el-footer>
  </div>
</template>

<script setup>
  import { useDark, useToggle } from '@vueuse/core'
  import { provide, ref, onMounted, computed, reactive, inject, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
  import en from 'element-plus/dist/locale/en.mjs'
  import { useRouter, useRoute } from 'vue-router'
  import { createAxiosInstance } from './axios.js'

  const language = ref('zh-cn')
  const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))

  const isDark = useDark()
  const toggleDark = useToggle(isDark)

  const toggle = () => {
    language.value = language.value === 'zh-cn' ? 'en' : 'zh-cn'
  }

  const checkLoginStatus = () => {
    alreadyLogin.value = localStorage.getItem('login') == 'true'
  }


  const userAvatar = ref("")
  const drawerVisible = ref(false) // 控制移动端侧边栏显示

  // 检测屏幕大小变化的函数
  const isMobile = ref(false)
  const checkIfMobile = () => {
    isMobile.value = window.innerWidth < 768;
  }


  const projectList = ref([]);
  const selectedProjectId = ref(null);
  const selectedProject = ref(null)
  const cloudHttp = createAxiosInstance(0);
  const localHttp = createAxiosInstance(1);

  const getProject = async () => {
    try {
      const rs = await cloudHttp.post('AasProjectInfoes/Get_ProjectByStatusCode');
      projectList.value = rs.data.response.sort((a, b) => b.id - a.id);
    } catch (error) {
      console.error('获取项目列表失败:', error);
      ElMessage.error('获取项目列表失败');
    }
  }
  const handleProjectChangeApp = async (projectId) => {
    if (!projectId) {
      selectedProject.value = null;
      return;
    }
    selectedProject.value = projectList.value.find(p => p.id === projectId);
    if (!selectedProject.value) {
      ElMessage.warning('未找到选中的项目');
      return;
    }
  };
  const helloworld = () => {
    try {
      if (getUrl() == "/login") {
        return
      }
      const rs = cloudHttp.post('Login/Helloooo').then(rs => {
        if (rs.data != 'hello') {
          router.push('/login')
        }

      })
    } catch (error) {
      console.log(error);
    }
  };
  onMounted(async () => {
    localStorage.setItem('login', true)
    helloworld()
    // 初始检查登录状态
    checkLoginStatus()
    userAvatar.value = config.httpAds + localStorage.getItem('avatar')

    // 初始检查屏幕尺寸
    checkIfMobile();
    // 添加窗口大小变化监听
    window.addEventListener('resize', checkIfMobile);
    // 主题初始化
    const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleColorSchemeChange = (e) => {
      webToDark(e.matches)
    }

    // 初始设置
    webToDark(darkModeQuery.matches)

    // 监听系统主题变化
    darkModeQuery.addEventListener('change', handleColorSchemeChange)

    // 清理监听器
    return () => {
      darkModeQuery.removeEventListener('change', handleColorSchemeChange)
      window.removeEventListener('resize', checkIfMobile);
    }
  })
  const getUrl = () => {
    const url = window.location.href;
    const lastSlashIndex = url.lastIndexOf('/');
    return url.substring(lastSlashIndex);
  }

  const alreadyLogin = ref(false)

  const router = useRouter()
  const route = useRoute()

  const config = inject('config')
  const username = localStorage.getItem('username')

  const currentTitle = reactive({
    label: '',
    routes: localStorage.getItem('url'),
  })

  const showPopover = ref(false)

  const menuValue = reactive([
    {
      label: "菜单",
      value: "dashboard",
      icon: "Menu",
      options: [
        /*{ label: "主页", value: "/home", icon: "House" },*/
        { label: "面板选型", value: "/panelselection", icon: "EditPen" },
      ]
    },
  ]);

  // 左侧返回首页按钮点击处理
  const handleLeftClick = (type) => {
    switch (type) {
      case 'home':
        menuChange("/home")
        break;
      default:
        console.log('跳转错误！');
        break;
    }
  }

  // 菜单操作处理
  const handleAction = (action) => {
    showPopover.value = false
    switch (action) {
      case 'profile':
        router.push('/user')
        break;
      case 'logout':
        localStorage.setItem('login', false)
        router.push('/login')
        break;
      default:
        console.log('跳转错误！');
        break;
    }
  }

  const refreshToHome = () => {
    localHttp.post('ConfigPY/RefreshConfig')
    router.push('/home')
    setTimeout(() => {
      location.reload(true);
    }, 0);
  }
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  // 菜单处理
  const menuChange = (val) => {
    if (currentTitle.routes == val) {
      return
    }
    currentTitle.label = val;
    currentTitle.routes = val;
    localStorage.setItem('url', val)
    router.push(val)

    // 移动端选择菜单后关闭侧边栏
    if (isMobile.value) {
      drawerVisible.value = false
    }
  }
  // 控制深色模式
  const isDarkMode = ref(false)
  const webToDark = (dark) => {
    // 获取 <html> 元素的类名
    let ishtmldark = null;
    if (document.documentElement.className.indexOf('dark') !== -1) {
      ishtmldark = false
    } else {
      ishtmldark = true
    }
    document.documentElement.removeAttribute('theme-mode')
    isDarkMode.value = false
    if (!ishtmldark) {
      toggleDark()
    }
  }
  const toggleTheme = () => {
    isDarkMode.value = !isDarkMode.value
    let root = document.documentElement;
    toggleDark()
    if (!isDarkMode.value) {
      // 如果当前是暗色主题，切换到亮色主题
      root.style.setProperty('--color-background', '#ffffff');
      root.style.setProperty('--color-background-soft', '#f8f8f8');
      root.style.setProperty('--color-background-mute', '#f2f2f2');
      root.style.setProperty('--color-border', 'rgba(60, 60, 60, 0.12)');
      root.style.setProperty('--color-border-hover', 'rgba(60, 60, 60, 0.29)');
      root.style.setProperty('--color-heading', '#2c3e50');
      root.style.setProperty('--color-text', '#2c3e50');
      root.setAttribute('data-theme', 'light');
      setTimeout(() => {
        root.removeAttribute('theme-mode');
      }, 20);
    } else {
      // 如果当前是亮色主题，切换到暗色主题
      root.style.setProperty('--color-background', '#242424');
      root.style.setProperty('--color-background-soft', '#222222');
      root.style.setProperty('--color-background-mute', '#282828');
      root.style.setProperty('--color-border', 'rgba(84, 84, 84, 0.48)');
      root.style.setProperty('--color-border-hover', 'rgba(84, 84, 84, 0.65)');
      root.style.setProperty('--color-heading', '#ffffff');
      root.style.setProperty('--color-text', 'rgba(235, 235, 235, 0.64)');
      root.setAttribute('data-theme', 'dark');
      setTimeout(() => {
        root.setAttribute('theme-mode', 'dark');
      }, 20);
    }
  }

  // 监听路由变化
  watch(() => route.path, (newPath) => {
    if (newPath === '/login') return

    // 同步更新当前激活菜单
    currentTitle.routes = newPath
    localStorage.setItem('url', newPath)
  }, { immediate: true })
  // 监听路由变化
/*  watch(() => alreadyLogin, async (newPath) => {
    if (newPath.value) {
      //await getProject()
    }
  }, {
    deep: true,
    immediate: true
  })*/

  const ajaxfile = async (form) => {
    if (!form.File || !form.File instanceof File) {
      throw new Error('文件对象无效!');
    }

    try {
      const formData = new FormData();
      formData.append('File', form.File);
      formData.append('Folder', form.Folder);

      const settings = {
        method: 'POST',
        headers: {
          "Cookie": "isCN=zh-cn"
        },
        body: formData
      };
      const token = localStorage.getItem('token');
      settings.headers['Authorization'] = `Bearer ${token}`;

      const response = await fetch(config.httpApi + 'FileUpload/UploadFile', settings);
      return await response.json();
    } catch (error) {
      console.error('error:', error);
    }
  };

  provide('checkLoginStatus', checkLoginStatus)
  provide('projectList', projectList);
  provide('selectedProjectId', selectedProjectId);
  provide('selectedProject', selectedProject);
  provide('cloudHttp', cloudHttp);
  provide('localHttp', localHttp);
  provide('formatDate', formatDate);
  provide('ajaxfile', ajaxfile)
  provide('isMobile', isMobile)
</script>

<style scoped>
  .main-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }

  /* 顶部导航栏样式 */
  .top-header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    z-index: 1000;
    position: sticky;
    top: 0;
    padding: 0 10px;
  }

  .logo-container {
    display: flex;
    align-items: center;
    padding: 0 10px;
  }

  /* 横向菜单样式 */
  .horizontal-menu {
    flex: 1;
    height: 100%;
    border-bottom: none;
  }

  /* 中间区域样式 */
  .header-center {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 2;
  }

  .center-logo {
    width: 60px;
    height: 60px;
    margin-right: 10px;
  }

  .center-text {
    font-size: 23px;
    font-weight: 500;
    white-space: nowrap;
  }

  .header-right {
    display: flex;
    align-items: center;
    padding-right: 10px;
    gap: 15px;
  }

  .user-avatar {
    cursor: pointer;
    transition: transform 0.2s;
  }

    .user-avatar:hover {
      transform: scale(1.1);
    }

  .user-menu {
    padding: 8px 0;
    display: flex;
    flex-direction: column;
    min-width: 120px;
  }

  /* 路由内容区样式 */
  .router-container {
    flex: 1;
    overflow: auto;
    padding: 5px;
    margin-top: 5px;
  }

    .router-container.mobile-view {
      padding: 5px;
      margin-top: 5px;
    }

  /* 底部样式 */
  .global-footer {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: sticky;
    bottom: 0;
    z-index: 1000;
    background: rgba(128, 128, 128, 0.2);
    backdrop-filter: blur(2px);
    -webkit-backdrop-filter: blur(10px);
    font-size: 12px;
  }

    .global-footer.mobile-footer {
      font-size: 10px;
      padding: 0 5px;
      text-align: center;
    }

  /* 调整菜单项间距 */
  :deep(.el-menu--horizontal) > .el-menu-item,
  :deep(.el-menu--horizontal) > .el-sub-menu .el-sub-menu__title {
    height: 100%;
    display: flex;
    align-items: center;
  }

  /* 调整菜单图标样式 */
  :deep(.el-menu--horizontal) .el-icon {
    margin-right: 5px;
  }

  /* 移动端侧边栏样式 */
  .mobile-drawer {
    z-index: 2000;
  }

  .mobile-menu-container {
    padding: 20px;
    height: 100%;
    background-color: #fff;
  }

  .mobile-logo {
    display: flex;
    justify-content: center;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
  }

  /* 移动端适配 */
  @media (max-width: 768px) {
    .top-header {
      padding: 0 5px;
    }

    .logo-container {
      padding: 0 5px;
    }

    .header-center {
      display: none; /* 在移动端隐藏中间区域 */
    }

    .header-right {
      padding-right: 5px;
      gap: 10px;
    }

    .user-avatar {
      width: 30px;
      height: 30px;
    }
  }
</style>
