<template>
  <div class="layout">
    <aside v-if="isAdmin" class="sidebar">
      <div class="brand">
        <div class="brand-logo">LM</div>
        <div class="brand-text">LAN Manager</div>
      </div>
      <nav class="nav">
        <router-link to="/machines" class="nav-item" active-class="active">
          <el-icon><Monitor /></el-icon>
          <span>机器列表</span>
        </router-link>
        <router-link v-if="isAdmin" to="/topology" class="nav-item" active-class="active">
          <el-icon><Share /></el-icon>
          <span>拓扑图</span>
        </router-link>
        <router-link v-if="isAdmin" to="/logs" class="nav-item" active-class="active">
          <el-icon><Document /></el-icon>
          <span>操作日志</span>
        </router-link>
      </nav>
      <div class="theme-toggle" @click="toggleTheme">
        <el-icon class="theme-icon"><component :is="isDark ? Sunny : Moon" /></el-icon>
        <span>{{ isDark ? '浅色模式' : '深色模式' }}</span>
      </div>
      <div class="sidebar-footer">
        <div class="user-info">
          <el-icon class="user-icon"><User /></el-icon>
          <span class="user-name">{{ isAdmin ? '管理员' : '访客' }}</span>
        </div>
        <el-button text class="logout-btn" @click="openChangePassword">
          <el-icon><Lock /></el-icon>
          <span>修改密码</span>
        </el-button>
        <el-button text class="logout-btn" @click="logout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出</span>
        </el-button>
      </div>
    </aside>

    <main class="main" :class="{ 'no-sidebar': !isAdmin }">
      <div class="main-inner">
        <router-view />
      </div>
    </main>

    <el-dialog
      v-model="pwdDialogVisible"
      title="修改密码"
      width="360px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="pwdFormRef"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="80px"
      >
        <el-form-item label="旧密码" prop="old_password">
          <el-input
            v-model="pwdForm.old_password"
            type="password"
            show-password
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input
            v-model="pwdForm.new_password"
            type="password"
            show-password
            placeholder="至少6位字符"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input
            v-model="pwdForm.confirm_password"
            type="password"
            show-password
            placeholder="再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pwdDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitChangePassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Monitor, Share, Document, User, SwitchButton, Sunny, Moon, Lock } from '@element-plus/icons-vue'
import { getAuth, refreshAuth } from '@/router'
import { logout as apiLogout, changePassword } from '@/api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const isAdmin = computed(() => getAuth().is_admin)
const isDark = ref(false)

onMounted(() => {
  isDark.value = document.documentElement.classList.contains('dark')
})

function toggleTheme() {
  isDark.value = !isDark.value
  document.documentElement.classList.toggle('dark', isDark.value)
  localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
}

async function logout() {
  try {
    await apiLogout()
  } catch (e) {}
  refreshAuth()
  ElMessage.success('已退出')
  router.push('/login')
}

const pwdDialogVisible = ref(false)
const pwdFormRef = ref(null)
const pwdForm = ref({
  old_password: '',
  new_password: '',
  confirm_password: '',
})

const validateConfirm = (rule, value, callback) => {
  if (value !== pwdForm.value.new_password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const pwdRules = {
  old_password: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirm, trigger: 'blur' },
  ],
}

function openChangePassword() {
  pwdForm.value = { old_password: '', new_password: '', confirm_password: '' }
  pwdDialogVisible.value = true
}

async function submitChangePassword() {
  if (!pwdFormRef.value) return
  try {
    await pwdFormRef.value.validate()
    await changePassword({
      old_password: pwdForm.value.old_password,
      new_password: pwdForm.value.new_password,
    })
    ElMessage.success('密码修改成功')
    pwdDialogVisible.value = false
  } catch (err) {
    const msg = err.response?.data?.error || err.message || '修改失败'
    ElMessage.error(msg)
  }
}
</script>

<style scoped>
.layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 220px;
  background: #0f172a;
  color: #fff;
  display: flex;
  flex-direction: column;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 100;
}

.brand {
  padding: 22px 18px 14px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,0.06);
}
.brand-logo {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: linear-gradient(135deg, #3b82f6, #60a5fa);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 800;
  font-size: 13px;
}
.brand-text {
  font-weight: 700;
  font-size: 14px;
  letter-spacing: 0.3px;
}

.nav {
  flex: 1;
  padding: 12px 10px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.nav-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border-radius: 8px;
  color: rgba(255,255,255,0.65);
  text-decoration: none;
  font-size: 13px;
  transition: background .15s ease, color .15s ease;
}
.nav-item:hover {
  background: rgba(255,255,255,0.06);
  color: rgba(255,255,255,0.9);
}
.nav-item.active {
  background: rgba(59, 130, 246, 0.18);
  color: #60a5fa;
  font-weight: 600;
}
.nav-item .el-icon {
  font-size: 16px;
}

.sidebar-footer {
  padding: 12px 10px 16px;
  border-top: 1px solid rgba(255,255,255,0.06);
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  font-size: 12px;
  color: rgba(255,255,255,0.55);
}
.user-icon {
  font-size: 14px;
}
.user-name {
  font-weight: 500;
  color: rgba(255,255,255,0.85);
}
.logout-btn {
  justify-content: flex-start;
  width: 100%;
  color: rgba(255,255,255,0.55);
  padding: 8px 10px;
  border-radius: 8px;
}
.logout-btn:hover {
  color: #fff;
  background: rgba(255,255,255,0.06);
}
.logout-btn span {
  margin-left: 8px;
  font-size: 12px;
}

.main {
  flex: 1;
  margin-left: 220px;
  min-height: 100vh;
  background: var(--bg);
}
.main-inner {
  padding: 10px;
}

.theme-toggle {
  margin: 0 10px 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border-radius: 8px;
  color: rgba(255,255,255,0.55);
  font-size: 13px;
  cursor: pointer;
  transition: background .15s ease, color .15s ease;
}
.theme-toggle:hover {
  background: rgba(255,255,255,0.06);
  color: rgba(255,255,255,0.9);
}
.theme-icon {
  font-size: 16px;
}

.main.no-sidebar {
  margin-left: 0;
}

@media (max-width: 768px) {
  .sidebar { width: 64px; }
  .brand-text, .nav-item span, .user-name, .logout-btn span { display: none; }
  .brand { justify-content: center; padding: 18px 10px; }
  .nav-item { justify-content: center; }
  .main { margin-left: 64px; }
  .main.no-sidebar { margin-left: 0; }
}
</style>
