<template>
  <el-container class="app-container" style="height: 100vh; overflow: hidden;">
    <el-header class="app-header">
      <div class="header-left">
        <img :src="LogoImg" class="app-logo" />
        <div class="logo">{{ systemTitle }}</div>
      </div>
      <div class="header-right">
        <el-tooltip content="全屏模式" placement="bottom">
          <el-button text @click="handleFullScreen" class="header-icon-btn">
            <el-icon size="18"><FullScreen /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="大屏展示" placement="bottom">
          <el-button text @click="handleBigScreen" class="header-icon-btn">
            <el-icon size="18"><Monitor /></el-icon>
          </el-button>
        </el-tooltip>
        <el-dropdown trigger="click" @command="handleCommand">
          <div class="user-info">
            <el-avatar bg-color="#409eff"><el-icon><User /></el-icon></el-avatar>
            <span class="user-name">{{ LoginUser?.uname }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="modifyPwd">
                <el-icon><Lock /></el-icon>
                <span>修改密码</span>
              </el-dropdown-item>
              <el-dropdown-item command="logout">
                <el-icon><SwitchButton /></el-icon>
                <span>退出系统</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <el-container>
      <el-aside :width="isCollapse ? '64px' : '200px'" class="app-aside">
        <div class="aside-wrapper">
          <div class="menu-scroll-container" :style="{ overflowY: isCollapse ? 'hidden' : 'auto' }">
            <el-menu
              :default-active="activeTabKey"
              :collapse="isCollapse"
              background-color="#1f2d3d"
              text-color="#e5e9f2"
              active-text-color="#409eff"
              :collapse-transition="false"
              class="app-menu"
            >
              <template v-for="menu in menuList" :key="menu.menuId">
                <el-sub-menu v-if="menu.menuType === 'M' && menu.children && menu.children.length > 0" :index="menu.menuId">
                  <template #title>
                    <el-icon><component :is="menu.menuIcon || 'Menu'" /></el-icon>
                    <span>{{ menu.menuName }}</span>
                  </template>
                  <template #default>
                    <template v-for="child in menu.children" :key="child.menuId">
                      <el-menu-item :index="child.menuId" @click="handleMenuClick(child)">
                        <el-icon><component :is="child.menuIcon || 'Menu'" /></el-icon>
                        <template #title>{{ child.menuName }}</template>
                      </el-menu-item>
                    </template>
                  </template>
                </el-sub-menu>
                <el-menu-item v-else-if="menu.menuType === 'C'" :index="menu.menuId" @click="handleMenuClick(menu)">
                  <el-icon><component :is="menu.menuIcon || 'Menu'" /></el-icon>
                  <template #title>{{ menu.menuName }}</template>
                </el-menu-item>
              </template>
            </el-menu>
          </div>
          <div class="aside-footer">
            <el-button 
              circle 
              @click="toggleSidebar"
              class="fold-btn"
              :class="{ 'fold-btn-active': isFoldBtnActive }"
              @mousedown="() => isFoldBtnActive = true"
              @mouseup="() => isFoldBtnActive = false"
              @mouseleave="() => isFoldBtnActive = false"
            >
              <el-icon size="16">
                <component :is="isCollapse ? 'Expand' : 'Fold'" />
              </el-icon>
            </el-button>
          </div>
        </div>
      </el-aside>
      
      <el-container class="main-container">
        <div class="tabs-container">
          <div class="tabs-wrapper">
            <div
              class="tab-item"
              :class="{ 'tab-active': activeTabKey === 'dashboard' }"
              @click="switchToHome"
            >
              <el-icon class="tab-icon"><House /></el-icon>
              <span class="tab-text">首页</span>
            </div>
            <el-button text class="scroll-btn" @click="scrollTab('left')" :disabled="tabs.length === 0">
              <el-icon size="14"><ArrowLeft /></el-icon>
            </el-button>
            <div class="tabs-scroll-box" ref="tabsScrollRef">
              <div class="dynamic-tabs">
                <div
                  v-for="tab in tabs"
                  :key="tab.key"
                  class="tab-item"
                  :class="{ 'tab-active': activeTabKey === tab.key }"
                  @click="switchTab(tab)"
                >
                  <span class="tab-text">{{ tab.name }}</span>
                  <el-icon class="tab-close-icon" @click.stop="closeTab(tab.key)">
                    <Close />
                  </el-icon>
                </div>
              </div>
            </div>
            <el-button text class="scroll-btn" @click="scrollTab('right')" :disabled="tabs.length === 0">
              <el-icon size="14"><ArrowRight /></el-icon>
            </el-button>
            <el-button text class="close-all-btn" @click="closeAllTabs" :disabled="tabs.length === 0">
              <el-icon size="14"><Close /></el-icon>
              关闭全部
            </el-button>
          </div>
        </div>
        
        <el-main class="content-container">
          <div class="content-wrapper">
            <router-view />
          </div>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog
      v-model="showEditPwdDialog"
      title="修改密码"
      width="35%"
      :close-on-click-modal="false"
      @close="handleEditPwdDialogClose"
      :before-close="handleDialogBeforeClose"
      class="custom-pwd-dialog"
    >
      <EditPswd ref="editPwdRef" @success="handlePwdModifySuccess" />
      <template #footer>
        <div class="dialog-footer">
          <el-button size="default" @click="closeEditPwdDialog">取消</el-button>
          <el-button size="default" type="primary" @click="submitEditPwd">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown, Lock, SwitchButton, User, FullScreen, Monitor,
  Expand, Fold, Close, ArrowLeft, ArrowRight, Menu, House
} from '@element-plus/icons-vue'
import { getHomeMenuList } from '@/api/bizMenu'
import LogoImg from '@/assets/logo.png'
import EditPswd from './components/editPswd.vue'

const isMounted = ref(true)
const systemTitle = ref("myPro管理系统")
const LoginUser = ref(JSON.parse(localStorage.getItem("loginUser")) || {});
const router = useRouter()
const route = useRoute()

const menuList = ref([])
const isCollapse = ref(false)
const tabsScrollRef = ref(null)
const tabs = ref([])
const activeTabKey = ref('dashboard')
const isFoldBtnActive = ref(false)
const menuNameMap = ref({})
const showEditPwdDialog = ref(false)
const editPwdRef = ref(null)

const getMenuList = async () => {
  if (!isMounted.value) return
  try {
    const res = await getHomeMenuList();
    menuList.value = res || [];
    const setMenuNameMap = (menus) => {
      menus.forEach(menu => {
        if (menu.menuId) menuNameMap.value[menu.menuId] = menu.menuName;
        if (menu.children && menu.children.length > 0) setMenuNameMap(menu.children);
      });
    }
    setMenuNameMap(menuList.value);
  } catch (error) {
	  console.log(error);
  }
}

const handleMenuClick = (menu) => {
  if (!isMounted.value) return
  const key = menu.menuId;
  const name = menu.menuName;
  if (!tabs.value.some(tab => tab.key === key)) {
    tabs.value.push({ key, name });
  }
  activeTabKey.value = key;
  if (menu.path) {
    router.push(menu.path).catch(err => {
      if (!err.message.includes('NavigationDuplicated')) {
        ElMessage.warning('路由跳转失败');
      }
    });
  } else {
    ElMessage.info('该菜单暂无路由路径');
  }
}

const switchTab = (tab) => {
  if (!isMounted.value) return
  activeTabKey.value = tab.key;
  const findMenu = (menus, menuId) => {
    for (const menu of menus) {
      if (menu.menuId === menuId) return menu;
      if (menu.children && menu.children.length > 0) {
        const res = findMenu(menu.children, menuId);
        if (res) return res;
      }
    }
    return null;
  }
  const menu = findMenu(menuList.value, tab.key);
  if (menu && menu.path) {
    router.push(menu.path).catch(err => {
      if (!err.message.includes('NavigationDuplicated')) {
        ElMessage.warning('路由跳转失败');
      }
    });
  }
}

const closeTab = (key) => {
  if (!isMounted.value) return
  const idx = tabs.value.findIndex(tab => tab.key === key);
  if (idx === -1) return;
  if (activeTabKey.value === key) {
    const nextTab = tabs.value[idx + 1] || tabs.value[idx - 1];
    if (nextTab) {
      activeTabKey.value = nextTab.key;
      switchTab(nextTab);
    } else {
      switchToHome();
    }
  }
  tabs.value.splice(idx, 1);
}

const closeAllTabs = () => {
  if (!isMounted.value) return
  ElMessageBox.confirm('确定关闭所有标签页?', '提示', { 
    type: 'warning',
    closeOnClickModal: false,
    showClose: false
  }).then(() => {
    tabs.value = [];
    switchToHome();
    ElMessage.success('已关闭所有标签页');
  });
}

const switchToHome = () => {
  if (!isMounted.value) return
  activeTabKey.value = 'dashboard';
  router.push('/dashboard').catch(err => {
    if (!err.message.includes('NavigationDuplicated')) {
      ElMessage.warning('路由跳转失败');
    }
  });
}

const scrollTab = (dir) => {
  if (!isMounted.value) return
  const el = tabsScrollRef.value;
  if (el && tabs.value.length > 0) {
    const scrollBox = el.querySelector('.dynamic-tabs');
    if (scrollBox) {
      scrollBox.scrollBy({ left: dir === 'left' ? -200 : 200, behavior: 'smooth' });
    }
  }
}

const toggleSidebar = () => {
  if (!isMounted.value) return
  isCollapse.value = !isCollapse.value;
}

const handleFullScreen = () => {
  if (!isMounted.value) return
  try {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
      ElMessage.success('已进入全屏模式');
    } else {
      document.exitFullscreen();
      ElMessage.success('已退出全屏模式');
    }
  } catch (error) {
    ElMessage.error(error);
  }
}

const handleBigScreen = () => {
  if (!isMounted.value) return
  const baseUrl = window.location.origin + "/#/bigScreen";
  window.open(baseUrl, '_blank');
}

const handleCommand = (cmd) => {
  if (!isMounted.value) return
  if (cmd === 'logout') {
    ElMessageBox.confirm('确定退出系统吗?', '退出确认', { 
      type: 'info',
      closeOnClickModal: false,
      showClose: false
    })
    .then(() => {
      localStorage.removeItem('loginUser');
      localStorage.removeItem('token');
      ElMessage.success('退出成功');
      router.push('/login');
    })
    .catch(() => {
      ElMessage.info('用户取消退出系统');
    });
  }
  
  if (cmd === 'modifyPwd') {
    nextTick(() => {
      showEditPwdDialog.value = true;
    });
  }
}

const closeEditPwdDialog = () => {
  if (!isMounted.value) return
  showEditPwdDialog.value = false;
  nextTick(() => {
    if (editPwdRef.value) {
      editPwdRef.value.resetForm();
    }
  });
}

const handleEditPwdDialogClose = () => {
  closeEditPwdDialog();
}

const handleDialogBeforeClose = (done) => {
  nextTick(() => {
    done();
  });
}

const submitEditPwd = () => {
  if (!isMounted.value || !editPwdRef.value || !showEditPwdDialog.value) return
  editPwdRef.value.submitForm().catch(err => {
    if (err && !err.message.includes('cancel')) {
      ElMessage.error(err.message);
    }
  });
}

const handlePwdModifySuccess = () => {
  if (!isMounted.value) return
  closeEditPwdDialog();
  ElMessage.success('密码修改成功，请重新登录');
}

onUnmounted(() => {
  isMounted.value = false
})

onMounted(() => {
  getMenuList();
  watch(() => route.path, (newPath) => {
    if (!isMounted.value) return
    activeTabKey.value = newPath === '/dashboard' ? 'dashboard' : route.params.menuId || activeTabKey.value;
  }, { immediate: true });
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app-logo {
  height: 45px;
  width: 52px;
  display: inline-block;
  vertical-align: middle;
}

.app-container {
  --primary-color: #4285f4;
  --primary-dark: #1f2d3d;
  --menu-hover-bg: #2c3e50;
  --tab-bg: #e8eaed;
  --tab-active-bg: #4285f4;
  --tab-text: #333;
  --tab-active-text: #fff;
  --tab-height: 28px;
  --tab-radius: 14px;
  --tab-padding: 0 12px;
  --divider-color: #e6e6e6;
  --header-bg-color: #c6e2ff;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px !important;
  background: var(--header-bg-color);
  border-bottom: 1px solid #e6e6e6;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
  letter-spacing: 1px;
  line-height: 45px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon-btn {
  width: 40px;
  height: 40px;
  color: #333 !important;
  border-radius: 4px;
  transition: all 0.2s;
}

.header-icon-btn:hover {
  background: var(--header-bg-color) !important;
  color: var(--primary-color) !important;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.2s;
}

.user-info:hover {
  background: var(--header-bg-color);
  color: var(--primary-color);
}

.user-name {
  font-size: 14px;
  color: #333;
}

.app-aside {
  background: var(--primary-dark) !important;
  height: calc(100vh - 60px) !important;
  transition: width 0.2s ease;
}

.aside-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.menu-scroll-container {
  flex: 1;
  padding-right: 0;
  height: calc(100% - 60px);
  scrollbar-width: thin;
  scrollbar-color: #2c3e50 #1f2d3d;
}

.menu-scroll-container:not([style*="overflowY: hidden"]) {
  padding-right: 2px;
}

.menu-scroll-container::-webkit-scrollbar {
  width: 4px;
}

.menu-scroll-container::-webkit-scrollbar-track {
  background: #1f2d3d;
  border-radius: 2px;
}

.menu-scroll-container::-webkit-scrollbar-thumb {
  background: #2c3e50;
  border-radius: 2px;
}

.menu-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #409eff;
}

.app-menu {
  height: 100%;
  border-right: none !important;
}

.aside-footer {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--primary-dark);
  border-top: 1px solid #2c3e50;
}

.fold-btn {
  width: 40px;
  height: 40px;
  background: transparent;
  color: #e5e9f2;
  border: none;
  transition: all 0.2s;
}

.fold-btn:hover {
  background: #2c3e50;
  color: #409eff;
}

.fold-btn-active {
  background: #0f48b9 !important;
  color: #fff !important;
}

.main-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
  overflow: hidden;
}

.tabs-container {
  padding: 4px 8px;
  background: #f1f3f4;
  border-bottom: 1px solid #e6e6e6;
}

.tabs-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 36px;
}

.scroll-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  border: none;
  background: #fff;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  transition: all 0.2s;
}

.scroll-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.scroll-btn:hover:not(:disabled) {
  background: #e8eaed;
  color: #333;
}

.tabs-scroll-box {
  flex: 1;
  overflow: hidden;
  min-width: 0;
}

.dynamic-tabs {
  display: flex;
  gap: 4px;
  overflow-x: auto;
  height: 100%;
  align-items: center;
  padding: 0 2px;
}

.dynamic-tabs::-webkit-scrollbar {
  display: none;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: var(--tab-padding);
  height: var(--tab-height);
  border-radius: var(--tab-radius);
  background: var(--tab-bg);
  color: var(--tab-text);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  box-shadow: 0 1px 1px rgba(0,0,0,0.05);
}

.tab-active {
  background: var(--tab-active-bg) !important;
  color: var(--tab-active-text) !important;
}

.tab-icon {
  font-size: 14px;
  margin-right: 4px;
}

.tab-close-icon {
  width: 16px;
  height: 16px;
  opacity: 0.8;
  transition: all 0.2s;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tab-close-icon:hover {
  opacity: 1;
  background: rgba(0,0,0,0.1);
  transform: none;
}

.tab-active .tab-close-icon {
  color: #fff;
}

.close-all-btn {
  padding: 0 12px;
  height: 28px;
  border-radius: 14px;
  background: #fff;
  color: #666;
  font-size: 12px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  transition: all 0.2s;
}

.close-all-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.close-all-btn:hover:not(:disabled) {
  background: #e8eaed;
  color: #333;
}

/* 核心修复：内容容器布局 */
.content-container {
  flex: 1;
  padding: 0 !important;
  overflow: hidden !important;
  display: flex !important;
  flex-direction: column !important;
}

.content-wrapper {
  margin: 8px;
  padding: 2px;
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  flex: 1 !important;
  height: calc(100% - 16px) !important;
  min-height: 0 !important;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  display: flex !important;
  flex-direction: column !important;
}

:deep(.el-sub-menu .el-menu) {
  background-color: transparent !important;
}

:deep(.el-sub-menu .el-menu-item) {
  padding-left: 40px !important;
}
:deep(.el-sub-menu .el-sub-menu .el-menu-item) {
  padding-left: 60px !important;
}

:deep(.el-menu-item.is-active) {
  background-color: var(--menu-hover-bg) !important;
  color: #409eff !important;
}
:deep(.el-sub-menu__title:hover) {
  background-color: var(--menu-hover-bg) !important;
}
:deep(.el-menu-item:hover) {
  background-color: var(--menu-hover-bg) !important;
}

:deep(.el-dropdown-menu) {
  border: 1px solid #e6e6e6;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
:deep(.el-tooltip__popper) {
  padding: 4px 8px;
  font-size: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

:deep(.custom-pwd-dialog) {
  --dialog-divider: #c6e2ff;
  --footer-height: 50px;
}

:deep(.custom-pwd-dialog .el-dialog) {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none !important;
  background: transparent !important;
  padding: 0 !important;
}

:deep(.custom-pwd-dialog .el-dialog__header) {
  padding: 8px 20px;
  border-bottom: 1px solid var(--dialog-divider);
  background: #fff !important;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  margin: 0 !important;
  height: auto !important;
}

:deep(.custom-pwd-dialog .el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
}

:deep(.custom-pwd-dialog .el-dialog__body) {
  padding: 12px 20px;
  border-bottom: 1px solid var(--dialog-divider);
  background: #fff !important;
  margin: 0 !important;
  height: auto !important;
}

:deep(.custom-pwd-dialog .el-dialog__footer) {
  height: var(--footer-height) !important;
  line-height: var(--footer-height) !important;
  padding: 0 20px !important;
  border-top: 1px solid var(--dialog-divider);
  background: #fff !important;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  text-align: right !important;
  margin: 0 !important;
  min-height: unset !important;
  display: block !important;
}

.dialog-footer {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: flex-end !important;
  gap: 12px;
  margin: 0 !important;
  padding: 0 !important;
  height: 100% !important;
  width: 100% !important;
}

:deep(.dialog-footer .el-button) {
  margin: 0 !important;
  vertical-align: middle !important;
}

:deep(.custom-pwd-dialog .el-dialog__headerbtn) {
  top: 8px !important;
}
</style>