<template>
  <div class="navbar">
    <div class="right-menu">
      <template v-if="appStore.device !== 'mobile'">
        <header-search id="header-search" class="right-menu-item" />
      </template>
      <!-- 公告和通知按钮 -->
      <el-tooltip content="公告/通知" placement="bottom">
        <div class="right-menu-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>
      <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 command="setLayout" v-if="settingsStore.showSettings">
                  <span>布局设置</span>
                </el-dropdown-item> -->
                <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} from 'vue';
import {ElMessageBox} from 'element-plus';
import {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 useSettingsStore from '@/store/modules/settings';
import {getOrg, switchOrg} from '@/api/login';
import {getUnreadCount} from '@/api/system/notice';

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

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

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

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();
  }
}
</script>

<style lang='scss' scoped>
.navbar {
  height: 50px;
  overflow: visible;
  position: relative;
  background-color: transparent;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 10px;
  flex-shrink: 0;
  min-width: 200px;
  z-index: 1002;

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

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: flex;
      align-items: center;
      padding: 0 6px;
      height: 100%;
      font-size: 16px;
      color: #606266;
      flex-shrink: 0;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(255,255,255,0.1);
        }
      }
    }

    .notice-btn {
      cursor: pointer;
      padding: 0 10px;
      height: 100%;
      display: flex;
      align-items: center;

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

      .el-icon {
        font-size: 20px;
        color: #606266;

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

    .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: 30px;
          height: 30px;
          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) {
    min-width: 150px;
    padding-right: 5px;

    .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: 24px;
            height: 24px;
          }
        }
      }
    }
  }

  @media (max-width: 480px) {
    min-width: 120px;
    padding-right: 5px;

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

          .divider {
            display: none;
          }

          .org-name {
            max-width: 80px;
            font-size: 11px;
          }
        }
      }
    }
  }
}
</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>
