<template>
  <div class="clinical-shell">
    <el-container class="clinical-container">
      <el-aside :width="isCollapse ? '64px' : '220px'" class="clinical-sidebar">
        <div class="brand-lockup" v-show="!isCollapse">
          <img src="/logo.png" class="brand-lockup__logo" alt="医梦AI" />
          <div class="brand-lockup__text">
            <span class="brand-lockup__name">医梦AI</span>
            <span class="brand-lockup__sub brand-sub">OKR · 绩效</span>
          </div>
          <svg class="brand-lockup__pulse" viewBox="0 0 160 18" aria-hidden="true" focusable="false">
            <path d="M2 9h52l6-6 8 12 9-12 6 6h75" />
          </svg>
        </div>
        <div class="brand-lockup collapsed" v-show="isCollapse">
          <img src="/logo.png" class="brand-lockup__mini" alt="医梦AI" />
        </div>

        <el-menu
          :default-active="route.path"
          :collapse="isCollapse"
          :collapse-transition="false"
          background-color="transparent"
          text-color="rgba(255,255,255,0.7)"
          active-text-color="var(--color-accent)"
          router
        >
          <el-menu-item index="/periods">
            <span class="nav-ico">▦</span>
            <template #title>考核周期</template>
          </el-menu-item>
          <el-menu-item index="/okr/my">
            <span class="nav-ico">◎</span>
            <template #title>我的 OKR</template>
          </el-menu-item>
          <el-menu-item index="/okr/team">
            <span class="nav-ico">⬡</span>
            <template #title>团队 OKR</template>
          </el-menu-item>
          <el-menu-item index="/okr/alignment">
            <span class="nav-ico">⇄</span>
            <template #title>OKR 对齐</template>
          </el-menu-item>
          <el-menu-item index="/scores/my">
            <span class="nav-ico">⊞</span>
            <template #title>我的绩效</template>
          </el-menu-item>

          <div class="menu-group-title" v-show="!isCollapse">考评管理</div>

          <el-menu-item index="/scoring" v-if="true">
            <span class="nav-ico">▱</span>
            <template #title>绩效打分</template>
          </el-menu-item>
          <el-menu-item index="/feedback" v-if="true">
            <span class="nav-ico">◠</span>
            <template #title>绩效沟通</template>
          </el-menu-item>
          <el-menu-item index="/score-appeals" v-if="auth.isHrAdminOrAbove">
            <span class="nav-ico">⌧</span>
            <template #title>绩效申诉</template>
          </el-menu-item>

          <div class="menu-group-title" v-show="!isCollapse">系统管理</div>

          <el-menu-item index="/org" v-if="auth.isHrAdminOrAbove">
            <span class="nav-ico">⬢</span>
            <template #title>组织架构</template>
          </el-menu-item>
          <el-menu-item index="/kpi/templates" v-if="auth.isHrAdminOrAbove">
            <span class="nav-ico">⊟</span>
            <template #title>绩效模板</template>
          </el-menu-item>
          <el-menu-item index="/system/dimensions" v-if="auth.isHrAdminOrAbove">
            <span class="nav-ico">⌗</span>
            <template #title>考核维度</template>
          </el-menu-item>
          <el-menu-item index="/system/logs" v-if="auth.isHrAdminOrAbove">
            <span class="nav-ico">≣</span>
            <template #title>操作日志</template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header class="clinical-topbar">
          <div class="topbar-left">
            <el-button text @click="isCollapse = !isCollapse">
              <el-icon :size="20"><Fold v-if="!isCollapse" /><Expand v-else /></el-icon>
            </el-button>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/' }">工作台</el-breadcrumb-item>
              <el-breadcrumb-item v-if="route.meta.title">{{ route.meta.title }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="topbar-right">
            <el-popover placement="bottom-end" :width="360" trigger="click">
              <template #reference>
                <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
                  <el-button text>
                    <el-icon :size="20"><Bell /></el-icon>
                  </el-button>
                </el-badge>
              </template>
              <div class="notify-panel">
                <div class="notify-header">
                  <span>消息通知</span>
                  <el-button text size="small" @click="markAllRead">全部已读</el-button>
                </div>
                <div class="notify-list" v-if="recentNotifications.length > 0">
                  <div
                    v-for="n in recentNotifications" :key="n.id"
                    class="notify-item" :class="{ unread: n.isRead === 0 }"
                    @click="handleNotifyClick(n)"
                  >
                    <div class="notify-title">{{ n.title }}</div>
                    <div class="notify-content">{{ n.content }}</div>
                    <div class="notify-time">{{ n.createdAtFriendly }}</div>
                  </div>
                </div>
                <div v-else class="notify-empty">暂无通知</div>
                <div class="notify-footer">
                  <el-button text size="small" @click="goNotifications">查看全部</el-button>
                </div>
              </div>
            </el-popover>
            <span class="user-info">
              {{ auth.user?.realName }}
              <el-tag size="small" effect="plain" class="role-tag">{{ auth.roleLabel }}</el-tag>
            </span>
            <el-button text type="danger" @click="handleLogout">退出</el-button>
          </div>
        </el-header>

        <el-main class="clinical-main">
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { notificationApi } from '../api'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const isCollapse = ref(false)

const unreadCount = ref(0)
const recentNotifications = ref([])
let pollTimer = null

async function fetchUnreadCount() {
  try {
    const data = await notificationApi.getUnreadCount()
    unreadCount.value = data.count
  } catch {}
}
async function fetchRecent() {
  try {
    const data = await notificationApi.getPage({ page: 1, size: 20 })
    recentNotifications.value = data.records || []
  } catch {}
}
async function markAllRead() {
  await notificationApi.markAllRead()
  unreadCount.value = 0
  await fetchRecent()
}
function handleNotifyClick(n) {
  notificationApi.markRead(n.id)
  setTimeout(async () => {
    if (n.refType === 'objective' && n.refId) {
      try {
        const { okrApi } = await import('../api')
        const detail = await okrApi.getDetail(n.refId)
        router.push('/okr/my?periodId=' + detail.periodId)
      } catch { router.push('/okr/my') }
    } else if (n.refType === 'score') {
      router.push('/scores/my')
    } else if (n.refType === 'feedback') {
      router.push('/feedback')
    } else if (n.refType === 'period') {
      router.push('/periods')
    } else if (n.refType === 'score_appeal') {
      router.push('/score-appeals')
    }
  }, 100)
}
function goNotifications() {
  router.push('/notifications')
}

onMounted(async () => {
  if (!auth.user) await auth.fetchUser()
  fetchUnreadCount()
  fetchRecent()
  pollTimer = setInterval(fetchUnreadCount, 60000)
})

onUnmounted(() => {
  if (pollTimer) clearInterval(pollTimer)
})

function handleLogout() {
  auth.logout()
  router.push('/login')
}
</script>

<style scoped>
.clinical-shell { height: 100vh; color: var(--color-text); }
.clinical-container { height: 100vh; }
.clinical-sidebar {
  background: var(--color-sidebar-bg);
  overflow-y: auto;
  transition: width 0.2s ease;
}
.brand-lockup {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 16px 14px 28px;
  border-bottom: 1px solid var(--color-sidebar-border);
}
.brand-lockup.collapsed { justify-content: center; padding: 14px 8px; }
.brand-lockup__logo { width: 72px; height: 36px; object-fit: contain; flex-shrink: 0; }
.brand-lockup__mini { width: 38px; height: 22px; object-fit: contain; }
.brand-lockup__text { min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.brand-lockup__name { font-size: var(--font-size-lg); font-weight: 700; color: var(--color-white); letter-spacing: 0; }
.brand-lockup__sub { font-size: 11px; color: var(--color-sidebar-muted); }
.brand-lockup__pulse {
  position: absolute;
  left: 14px;
  right: 14px;
  bottom: 8px;
  width: calc(100% - 28px);
  height: 18px;
  color: var(--color-accent);
  opacity: 0.52;
}
.brand-lockup__pulse path {
  fill: none;
  stroke: currentColor;
  stroke-width: 1.2;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.menu-group-title {
  padding: 10px 20px 4px;
  font-size: 10px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.35);
  text-transform: uppercase;
  letter-spacing: 0.8px;
}
.el-menu {
  border-right: none !important;
}
.el-menu-item {
  position: relative;
  margin: 2px 8px;
  border-radius: var(--radius-sm);
}
.el-menu-item.is-active {
  background: rgba(58, 212, 216, 0.08) !important;
}
.el-menu-item.is-active::before {
  content: "";
  position: absolute;
  left: 0;
  top: 10px;
  bottom: 10px;
  width: 2px;
  border-radius: var(--radius-xs);
  background: var(--color-accent);
}
.clinical-topbar {
  height: var(--layout-topbar);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--color-surface);
  border-bottom: 1px solid var(--color-border);
  padding: 0 20px;
}
.topbar-left { display: flex; align-items: center; gap: 8px; }
.topbar-right { display: flex; align-items: center; gap: 12px; }
.user-info { font-size: 13px; color: var(--color-text-secondary); }
.role-tag {
  margin-left: 4px;
  vertical-align: middle;
  border-color: var(--color-border);
  color: var(--color-brand);
  background: var(--color-surface-tint-brand);
}
.clinical-main {
  min-height: calc(100vh - var(--layout-topbar));
  padding: 20px 24px;
  background: var(--color-bg);
}

.notify-panel { max-height: 400px; overflow-y: auto; }
.notify-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 8px; border-bottom: 1px solid var(--color-border-soft); margin-bottom: 4px; font-weight: 600; }
.notify-item { padding: 10px 8px; border-bottom: 1px solid var(--color-border-soft); cursor: pointer; border-radius: 4px; }
.notify-item:hover { background: var(--color-surface-subtle); }
.notify-item.unread { background: var(--color-accent-soft); border-left: 2px solid var(--color-accent); }
.notify-title { font-size: 13px; font-weight: 600; color: var(--color-text); }
.notify-content { font-size: 12px; color: var(--color-text-secondary); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.notify-time { font-size: 11px; color: var(--color-text-muted); margin-top: 2px; }
.notify-empty { padding: 20px; text-align: center; color: var(--color-text-muted); font-size: 13px; }
.notify-footer { padding-top: 8px; text-align: center; border-top: 1px solid var(--color-border-soft); margin-top: 4px; }

/* v2 几何图标替代 el-icon */
.nav-ico {
  display: inline-block;
  width: 18px;
  margin-right: 8px;
  color: rgba(255, 255, 255, 0.4);
  font-size: 14px;
  text-align: center;
}
.el-menu-item.is-active .nav-ico {
  color: var(--color-accent);
}

/* v2 品牌副标题大写小字 */
.brand-sub {
  color: rgba(255, 255, 255, 0.45);
  font-size: 9px;
  letter-spacing: 0.8px;
  text-transform: uppercase;
}

@media (max-width: 700px) {
  .clinical-sidebar {
    display: none;
  }

  .clinical-topbar {
    padding: 0 12px;
  }

  .topbar-left {
    min-width: 0;
  }

  .topbar-right {
    gap: 6px;
  }

  .user-info {
    display: none;
  }

  .clinical-main {
    padding: 14px;
  }
}
</style>
