<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"
            @click="goToHelpCenter"
          >
            <el-icon><Help /></el-icon>
          </div>
        </el-tooltip>
        <!-- 主题/布局设置 -->
        <el-tooltip
          content="主题设置"
          placement="bottom"
        >
          <div
            class="left-action-item"
            @click="setLayout"
          >
            <el-icon><Setting /></el-icon>
          </div>
        </el-tooltip>
      </div>
    </div>
    <div class="right-menu">
      <HeaderNotice />
      <div class="avatar-container">
        <div class="avatar-wrapper">
          <el-dropdown
            class="user-info-dropdown hover-effect"
            trigger="click"
            teleported
            popper-class="navbar-dropdown"
            :popper-options="{
              modifiers: [
                {
                  name: 'offset',
                  options: {
                    offset: [0, 12],
                  },
                },
              ],
            }"
            @command="handleCommand"
          >
            <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="lockScreen"
                >
                  <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
            trigger="click"
            teleported
            popper-class="navbar-dropdown"
            :placement="'bottom-start'"
            @command="handleOrgSwitch"
          >
            <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
      v-model="showDialog"
      title="切换科室"
      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>


  </div>
</template>

<script setup>
import {ElMessageBox} from 'element-plus';
import {Fold, Expand} from '@element-plus/icons-vue';
import {Help, Setting} from "@element-plus/icons-vue";
import HeaderSearch from '@/components/HeaderSearch/index.vue';
import HeaderNotice from '@/layout/components/HeaderNotice/index.vue';
import useAppStore from '@/store/modules/app';
import useUserStore from '@/store/modules/user';
import useLockStore from '@/store/modules/lock';
import usePermissionStore from '@/store/modules/permission';
import {getOrg, switchOrg} from '@/api/login';

const appStore = useAppStore();
const userStore = useUserStore();
const lockStore = useLockStore();
const permissionStore = usePermissionStore();
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();

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

const showDialog = ref(false);
const orgId = ref('');
const orgOptions = ref([]);


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

function handleCommand(command) {
  switch (command) {
    case 'setLayout':
      setLayout();
      break;
    case 'lockScreen':
      lockStore.lockScreen(route.path);
      router.push('/lock');
      break;
    case 'logout':
      logout();
      break;
  }
}

async function loadOrgList() {
  try {
    const res = await getOrg();
    orgOptions.value = res.data || [];
  } catch (e) {
    // ignore
  }
}

async function handleOrgSwitch(val) {
  const selectedOrg = orgOptions.value.find(item => item.orgId === val);
  const orgName = selectedOrg ? selectedOrg.orgName : '该科室';
  ElMessageBox.confirm(`确定要切换到科室"${orgName}"吗？`, '切换科室', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await switchOrg(val);
      location.reload();
    } catch (e) {
      // ignore
    }
  }).catch(() => {});
}

function submit() {
  handleOrgSwitch(orgId.value);
}

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



function goToHelpCenter() {
  router.push('/help');
}



const noticeUnread = computed(() => noticeStore.noticeList.filter(n => n.noticeType === '1' && !noticeIsRead(n)).length)
const announceUnread = computed(() => noticeStore.noticeList.filter(n => n.noticeType === '2' && !noticeIsRead(n)).length)


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

onMounted(() => {
  loadOrgList();
});
</script>

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

  .left-menu {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;

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

      .hamburger {
        padding: 0 15px;
        height: 50px;
        display: flex;
        align-items: center;
        cursor: pointer;
        transition: background 0.3s;

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

    .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: #3B82F6;
          }
        }
      }
    }
  }

  .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: #3B82F6;
          }
        }

        .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: #3B82F6 !important;
      font-weight: 500 !important;
      background-color: #ecf5ff !important;
    }
  }
}
</style>

