<template>
  <div class="dashboard-container">
    <el-container class="main-container">
      <el-aside width="240px" class="aside">
        <div class="logo-container">
          <img src="/logo.png" alt="Logo" class="logo-img" />
          <span class="logo-text">统一登录平台</span>
        </div>
        <el-menu
          router
          :default-active="$route.path"
          class="el-menu-vertical"
        >
          <el-menu-item index="/dashboard/launchpad">
            <el-icon><Menu /></el-icon>
            <span>快捷导航</span>
          </el-menu-item>

          <el-menu-item index="/dashboard/messages">
            <el-icon><ChatDotRound /></el-icon>
            <span>消息中心</span>
          </el-menu-item>

          <el-menu-item 
            v-if="user && (user.role === 'SUPER_ADMIN' || user.role === 'DEVELOPER')" 
            index="/dashboard/apps"
          >
            <el-icon><Grid /></el-icon>
            <span>应用管理</span>
          </el-menu-item>
          <el-menu-item 
            v-if="user && (user.role === 'SUPER_ADMIN' || user.role === 'DEVELOPER')" 
            index="/dashboard/client-distributions"
          >
            <el-icon><Upload /></el-icon>
            <span>客户端分发</span>
          </el-menu-item>
          
          <el-menu-item index="/dashboard/mappings">
            <el-icon><Connection /></el-icon>
            <span>平台账号管理</span>
          </el-menu-item>

          <el-menu-item v-if="user && user.role === 'SUPER_ADMIN'" index="/dashboard/users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>

          <el-sub-menu index="ops" v-if="user && user.role === 'SUPER_ADMIN'">
            <template #title>
              <el-icon><Monitor /></el-icon>
              <span>运维服务</span>
            </template>
            <el-menu-item index="/dashboard/system-logs">
              <el-icon><Document /></el-icon>
              <span>后台日志</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/system-status">
              <el-icon><Monitor /></el-icon>
              <span>服务器资源监控</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/login-logs">
              <el-icon><List /></el-icon>
              <span>登录日志</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/backup">
              <el-icon><Download /></el-icon>
              <span>数据备份</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/restore">
              <el-icon><RefreshRight /></el-icon>
              <span>数据还原</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/ssl-config">
              <el-icon><Lock /></el-icon>
              <span>证书配置</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/login-config">
              <el-icon><Setting /></el-icon>
              <span>登录配置</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/app-categories">
              <el-icon><Folder /></el-icon>
              <span>应用分类管理</span>
            </el-menu-item>
          </el-sub-menu>

          <el-menu-item 
            v-if="user && (user.role === 'SUPER_ADMIN' || user.role === 'DEVELOPER')"
            index="/dashboard/help"
          >
            <el-icon><QuestionFilled /></el-icon>
            <span>使用帮助</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      
      <el-container class="content-container">
        <el-header>
          <div class="header-content">
            <div class="breadcrumb">
              <!-- Breadcrumb placeholder -->
            </div>
            <div class="user-actions">
              <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link">
                  <span v-if="user" class="username">{{ user.mobile }}</span>
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
                    <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-header>
        
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- Change Password Dialog -->
    <el-dialog v-model="changePwdVisible" title="修改密码" width="400px">
      <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" label-width="100px">
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="pwdForm.old_password" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="pwdForm.new_password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirm_password">
          <el-input v-model="pwdForm.confirm_password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="changePwdVisible = false">取消</el-button>
        <el-button type="primary" @click="submitChangePwd" :loading="changingPwd">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { Grid, List, QuestionFilled, User, ArrowDown, Connection, Monitor, Document, Download, RefreshRight, Lock, Setting, ChatDotRound, Folder, Menu, Upload } from '@element-plus/icons-vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import api from '../utils/request'

const router = useRouter()
const authStore = useAuthStore()
const user = computed(() => authStore.user)

// Logout & Menu Command
const handleCommand = (command: string) => {
  if (command === 'logout') {
    handleLogout()
  } else if (command === 'changePassword') {
    openChangePwd()
  }
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// Change Password Logic
const changePwdVisible = ref(false)
const changingPwd = ref(false)
const pwdFormRef = ref<FormInstance>()
const pwdForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

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

const pwdRules = reactive<FormRules>({
  old_password: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirm_password: [{ required: true, validator: validatePass2, trigger: 'blur' }]
})

const openChangePwd = () => {
  pwdForm.old_password = ''
  pwdForm.new_password = ''
  pwdForm.confirm_password = ''
  changePwdVisible.value = true
}

const submitChangePwd = async () => {
  if (!pwdFormRef.value) return
  await pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPwd.value = true
      try {
        await api.post('/simple/me/change-password', {
          old_password: pwdForm.old_password,
          new_password: pwdForm.new_password
        })
        ElMessage.success('密码修改成功')
        changePwdVisible.value = false
      } catch (e) {
        // handled
      } finally {
        changingPwd.value = false
      }
    }
  })
}

onMounted(() => {
  if (!user.value) {
    authStore.fetchUser()
  }
})
</script>

<style scoped>
.dashboard-container {
  height: 100%;
  width: 100%;
}
.main-container {
  height: 100%;
}
.content-container {
  height: 100%;
  overflow: hidden;
}
.aside {
  background-color: #304156;
  color: #fff;
  height: 100%;
}
.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3649;
  padding: 0 10px;
}
.logo-img {
  height: 32px;
  margin-right: 10px;
}
.logo-text {
  font-weight: bold;
  font-size: 16px;
  white-space: nowrap;
}
.el-menu-vertical {
  border-right: none;
  background-color: #304156;
}
:deep(.el-menu-item) {
  color: #bfcbd9;
}
:deep(.el-menu-item.is-active) {
  color: #409eff;
  background-color: #263445;
}
:deep(.el-menu-item:hover) {
  background-color: #263445;
}

:deep(.el-sub-menu__title) {
  color: #bfcbd9 !important;
}
:deep(.el-sub-menu__title:hover) {
  background-color: #263445 !important;
}

/* Fix nested menu background color */
:deep(.el-sub-menu .el-menu) {
  background-color: #1f2d3d !important;
}
:deep(.el-sub-menu .el-menu-item) {
  background-color: #1f2d3d !important;
}
:deep(.el-sub-menu .el-menu-item:hover) {
  background-color: #001528 !important;
}

.el-header {
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 20px;
  background-color: #fff;
}
.user-actions {
  display: flex;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #333;
}
.username {
  margin-right: 5px;
  font-size: 14px;
}
.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}
</style>
