<template>
  <div class="navbar">
    <div class="left-menu">
      <div class="hamburger-container">
        <div class="hamburger" @click="toggleSideBar">
          <el-icon :size="20">
            <component :is="sidebar.opened ? 'Fold' : 'Expand'" />
          </el-icon>
        </div>
      </div>
      <!-- 搜索和公告通知 -->
      <div class="left-actions">
        <template v-if="appStore.device !== 'mobile'">
          <header-search id="header-search" class="left-action-item" />
        </template>
        <!-- 公告和通知按钮 -->
        <el-tooltip content="公告/通知" placement="bottom">
          <div class="left-action-item notice-btn" @click="openNoticePanel">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notice-badge">
              <el-icon><Bell /></el-icon>
            </el-badge>
          </div>
        </el-tooltip>
        <!-- 帮助中心按钮 -->
        <el-tooltip content="帮助中心" placement="bottom">
          <div class="left-action-item" @click="goToHelpCenter">
            <el-icon><Help /></el-icon>
          </div>
        </el-tooltip>
      </div>
    </div>
    <div class="right-menu">
      <div class="avatar-container">
        <div class="avatar-wrapper">
          <el-dropdown
            @command="handleCommand"
            class="user-info-dropdown hover-effect"
            trigger="click"
            teleported
            popper-class="navbar-dropdown"
            :popper-options="{
              modifiers: [
                {
                  name: 'offset',
                  options: {
                    offset: [0, 12],
                  },
                },
              ],
            }"
          >
            <div class="user-info">
              <img :src="userStore.avatar" class="user-avatar" />
              <span class="nick-name">{{ userStore.nickName }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <router-link to="/user/profile">
                  <el-dropdown-item>个人中心</el-dropdown-item>
                </router-link>
                <el-dropdown-item divided command="logout">
                  <span>退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <span class="divider">|</span>
          <el-dropdown
            @command="handleOrgSwitch"
            trigger="click"
            teleported
            popper-class="navbar-dropdown"
            :placement="'bottom-start'"
          >
            <span class="org-name">{{ userStore.orgName }}</span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in orgOptions"
                  :key="item.orgId"
                  :command="item.orgId"
                  :class="{ 'is-active': item.orgId === userStore.orgId }"
                >
                  {{ item.orgName }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <span class="divider" />
        </div>
      </div>
    </div>
    <el-dialog title="切换科室" v-model="showDialog" width="400px" append-to-body destroy-on-close>
      <el-select v-model="orgId" filterable clearable>
        <el-option
          v-for="item in orgOptions"
          :key="item.orgId"
          :label="item.orgName"
          :value="item.orgId"
        />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="showDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 公告/通知面板 -->
    <NoticePanel ref="noticePanelRef" @updateUnreadCount="updateUnreadCount" />
  </div>
</template>

<script setup>
import {onMounted, ref, computed} from 'vue';
import {ElMessageBox} from 'element-plus';
import {Fold, Expand, Bell} from '@element-plus/icons-vue';
import HeaderSearch from '@/components/HeaderSearch';
import NoticePanel from '@/components/NoticePanel';
import useAppStore from '@/store/modules/app';
import useUserStore from '@/store/modules/user';
import {getOrg, switchOrg} from '@/api/login';
import {getUnreadCount} from '@/api/system/notice';
import {useRouter} from 'vue-router';
import {Help} from "@element-plus/icons-vue";

const appStore = useAppStore();
const userStore = useUserStore();
const router = useRouter();
const orgOptions = ref([]);
const showDialog = ref(false);
const orgId = ref('');
const noticePanelRef = ref(null);
const unreadCount = ref(0);

const sidebar = computed(() => appStore.sidebar);

// 加载未读数量
function loadUnreadCount() {
  getUnreadCount().then(res => {
    unreadCount.value = res.data || 0;
  }).catch(() => {
    unreadCount.value = 0;
  });
}

// 更新未读数量
function updateUnreadCount() {
  loadUnreadCount();
}

// 切换侧边栏
function toggleSideBar() {
  appStore.toggleSideBar();
}

function loadOrgList() {
  getOrg().then((res) => {
    orgOptions.value = res.data;
  });
}

onMounted(() => {
  loadOrgList();
  loadUnreadCount();
});

function handleOrgSwitch(selectedOrgId) {
  if (selectedOrgId === userStore.orgId) {
    return;
  }

  const selectedOrg = orgOptions.value.find((item) => item.orgId === selectedOrgId);
  const orgName = selectedOrg ? selectedOrg.orgName : '该科室';

  ElMessageBox.confirm(`确定要切换到科室"${orgName}"吗？`, '切换科室', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    orgId.value = selectedOrgId;
    switchOrg(selectedOrgId).then((res) => {
      if (res.code === 200) {
        userStore.logOut().then(() => {
          location.href = '/index';
        });
      }
    });
  });
}

function handleCommand(command) {
  switch (command) {
    case 'setLayout':
      setLayout();
      break;
    case 'logout':
      logout();
      break;
    default:
      break;
  }
}

function logout() {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => {
    userStore.logOut().then(() => {
      location.href = '/index';
    });
  })
  .catch(() => {});
}

function submit() {
  switchOrg(orgId.value).then((res) => {
    if (res.code === 200) {
      userStore.logOut().then(() => {
        location.href = '/index';
      });
    }
  });
}

const emits = defineEmits(['setLayout']);
function setLayout() {
  emits('setLayout');
}

// 打开公告/通知面板
function openNoticePanel() {
  if (noticePanelRef.value) {
    noticePanelRef.value.open();
  }
}

function goToHelpCenter() {
  window.open(window.location.origin + '/help-center/vuepress-theme-vdoing-doc/docs/.vuepress/dist/pages/520e67/index.html', '_blank');
}
</script>

<style lang='scss' scoped>
.navbar {
  height: 50px;
  width: 100%;
  overflow: hidden;
  position: relative;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;

  .left-menu {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    gap: 8px;

    .hamburger-container {
      display: flex;
      align-items: center;

      .hamburger {
        cursor: pointer;
        padding: 0 12px;
        height: 50px;
        display: flex;
        align-items: center;
        transition: background 0.3s;
        color: #5a5e66;

        &:hover {
          background-color: #f6f6f6;
          color: var(--el-color-primary);
        }
      }
    }

    .left-actions {
      display: flex;
      align-items: center;
      gap: 4px;

      .left-action-item {
        display: flex;
        align-items: center;
        padding: 0 10px;
        height: 50px;
        font-size: 16px;
        color: #606266;
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background-color: #f6f6f6;
        }

        .notice-badge {
          :deep(.el-badge__content) {
            top: -5px;
            right: -5px;
          }
        }

        .el-icon {
          font-size: 20px;

          &:hover {
            color: #409eff;
          }
        }
      }
    }
  }

  .right-menu {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    white-space: nowrap;

    &:focus {
      outline: none;
    }

    .avatar-container {
      margin-right: 0;
      margin-left: 5px;
      flex-shrink: 0;
      position: relative;
      z-index: 1003;
      display: flex;
      align-items: center;

      .avatar-wrapper {
        display: flex;
        align-items: center;
        gap: 8px;
        position: relative;

        .user-info-dropdown {
          display: flex;
          align-items: center;
          cursor: pointer;
        }

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

        .user-avatar {
          cursor: pointer;
          width: 32px;
          height: 32px;
          border-radius: 6px;
          flex-shrink: 0;
        }
        .nick-name {
          font-weight: 500;
          color: #606266;
          font-size: 14px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100px;
          flex-shrink: 0;
        }
        .divider {
          color: #dcdfe6;
          font-size: 14px;
          margin: 0 8px;
          flex-shrink: 0;
        }
        .org-name {
          font-weight: 500;
          color: #606266;
          font-size: 14px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 120px;
          flex-shrink: 0;
          cursor: pointer;
          transition: color 0.3s;

          &:hover {
            color: #409eff;
          }
        }

        .el-icon {
          cursor: pointer;
          position: absolute;
          right: -15px;
          top: 25px;
          font-size: 12px;
          color: #fff;
        }
      }
    }
  }

  @media (max-width: 768px) {
    padding: 0 10px;

    .left-menu {
      .hamburger-container {
        .hamburger {
          padding: 0 8px;
        }
      }

      .left-actions {
        .left-action-item {
          padding: 0 6px;
        }
      }
    }

    .right-menu {
      .avatar-container {
        .avatar-wrapper {
          gap: 4px;

          .nick-name {
            max-width: 60px;
            font-size: 12px;
          }

          .org-name {
            max-width: 80px;
            font-size: 12px;
          }

          .divider {
            margin: 0 4px;
            font-size: 12px;
          }

          .user-avatar {
            width: 28px;
            height: 28px;
          }
        }
      }
    }
  }

  @media (max-width: 480px) {
    padding: 0 8px;

    .left-menu {
      .hamburger-container {
        .hamburger {
          padding: 0 6px;
        }
      }

      .left-actions {
        .left-action-item {
          padding: 0 4px;
        }
      }
    }

    .right-menu {
      .avatar-container {
        .avatar-wrapper {
          .nick-name {
            display: none;
          }

          .divider {
            display: none;
          }

          .org-name {
            max-width: 80px;
            font-size: 11px;
          }

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

<style lang="scss">
.navbar-dropdown {
  margin-bottom: 8px !important;
  z-index: 10010 !important;

  .el-dropdown-menu {
    margin-bottom: 0 !important;
    z-index: 10010 !important;
    max-height: 300px !important;
    overflow-y: auto !important;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 3px;

      &:hover {
        background: rgba(0, 0, 0, 0.3);
      }
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    .el-dropdown-menu__item.is-active {
      color: #409eff !important;
      font-weight: 500 !important;
      background-color: #ecf5ff !important;
    }
  }
}
</style>
