<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>
            <span v-if="messageStore.totalUnread > 0" class="menu-unread-badge">
              {{ messageStore.totalUnread > 99 ? '99+' : messageStore.totalUnread }}
            </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' || user.role === 'DEVELOPER')"
          >
            <template #title>
              <el-icon><Monitor /></el-icon>
              <span>运维服务</span>
            </template>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/system-logs">
              <el-icon><Document /></el-icon>
              <span>后台日志</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/system-status">
              <el-icon><Monitor /></el-icon>
              <span>服务器资源监控</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/login-logs">
              <el-icon><List /></el-icon>
              <span>登录日志</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/message-search">
              <el-icon><ChatLineSquare /></el-icon>
              <span>消息查询</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/backup">
              <el-icon><Download /></el-icon>
              <span>数据备份</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/restore">
              <el-icon><RefreshRight /></el-icon>
              <span>数据还原</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/ssl-config">
              <el-icon><Lock /></el-icon>
              <span>证书配置</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/login-config">
              <el-icon><Setting /></el-icon>
              <span>登录配置</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/app-categories">
              <el-icon><Folder /></el-icon>
              <span>应用分类管理</span>
            </el-menu-item>
            <el-menu-item v-if="user.role === 'SUPER_ADMIN'" index="/dashboard/admin-api-keys">
              <el-icon><Key /></el-icon>
              <span>API Key 管理</span>
            </el-menu-item>
          </el-sub-menu>

          <el-sub-menu
            v-if="user && (user.role === 'SUPER_ADMIN' || user.role === 'DEVELOPER')"
            index="help-docs"
          >
            <template #title>
              <el-icon><QuestionFilled /></el-icon>
              <span>帮助文档</span>
            </template>
            <el-menu-item index="/dashboard/help">
              <el-icon><Document /></el-icon>
              <span>接口开发文档</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/api-skill">
              <el-icon><MagicStick /></el-icon>
              <span>UAP应用接口skill</span>
            </el-menu-item>
            <el-menu-item index="/dashboard/admin-api-skill">
              <el-icon><Key /></el-icon>
              <span>UAP管理API接口skill</span>
            </el-menu-item>
          </el-sub-menu>
        </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-popover
                placement="bottom"
                :width="260"
                trigger="hover"
                @show="handleDownloadPopoverShow"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    link
                    class="header-download-link"
                    :disabled="downloadLinksLoading || !clientDownloadHref"
                    @click="openClientDownload"
                  >
                    下载客户端
                  </el-button>
                </template>
                <div class="download-popover">
                  <div v-if="downloadQrDataUrl" class="download-qr-wrap">
                    <img :src="downloadQrDataUrl" alt="客户端下载二维码" class="download-qr-img" />
                  </div>
                  <p v-else class="download-qr-empty">暂无可用下载链接</p>
                  <div class="download-popover-actions">
                    <el-button
                      size="small"
                      :disabled="!downloadQrDataUrl || copyDownloadQrLoading"
                      :loading="copyDownloadQrLoading"
                      @click="copyDownloadQrImage"
                    >
                      复制图片
                    </el-button>
                  </div>
                </div>
              </el-popover>
              <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="identityQr">
                      <span class="dropdown-item-with-icon">
                        <el-icon><Postcard /></el-icon>
                        个人二维码
                      </span>
                    </el-dropdown-item>
                    <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>

    <!-- 个人身份二维码 -->
    <el-dialog
      v-model="identityQrVisible"
      title="个人二维码"
      width="420px"
      align-center
      destroy-on-close
      @closed="onIdentityQrDialogClosed"
    >
      <div v-loading="identityQrLoading" class="identity-qr-body">
        <p class="identity-qr-hint">请向核验人员出示，密文约 1 分钟内有效。</p>
        <div v-if="identityQrDataUrl" class="identity-qr-img-wrap">
          <img :src="identityQrDataUrl" alt="个人二维码" class="identity-qr-img" />
        </div>
        <p v-if="identityQrExpiresText" class="identity-qr-expires">
          有效期至：{{ identityQrExpiresText }}
        </p>
      </div>
      <template #footer>
        <el-button @click="identityQrVisible = false">关闭</el-button>
        <el-button type="primary" :loading="identityQrLoading" @click="fetchIdentityQr">
          刷新
        </el-button>
      </template>
    </el-dialog>

    <!-- 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, onUnmounted, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { Grid, List, User, ArrowDown, Connection, Monitor, Document, Download, RefreshRight, Lock, Setting, ChatDotRound, ChatLineSquare, Folder, Menu, Upload, Postcard, MagicStick, QuestionFilled, Key } from '@element-plus/icons-vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import QRCode from 'qrcode'
import api from '../utils/request'
import { getDownloadLinks, type DownloadLinksPublic } from '../api/public'
import { useMessageStore } from '../store/message'

const router = useRouter()
const authStore = useAuthStore()
const messageStore = useMessageStore()
const user = computed(() => authStore.user)
const downloadLinks = ref<DownloadLinksPublic | null>(null)
const downloadLinksLoading = ref(false)
const downloadQrDataUrl = ref('')
const copyDownloadQrLoading = ref(false)

const isMobileUa = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)

const clientDownloadHref = computed(() => {
  const links = downloadLinks.value
  if (!links) return ''
  if (isMobileUa()) {
    return links.mobile || links.pc || ''
  }
  return links.pc || links.mobile || ''
})

const qrDownloadHref = computed(() => {
  const links = downloadLinks.value
  if (!links) return ''
  // 扫码场景默认给移动端（安卓）下载地址
  return links.mobile || links.pc || ''
})

const ensureDownloadLinksLoaded = async () => {
  if (downloadLinks.value || downloadLinksLoading.value) return
  downloadLinksLoading.value = true
  try {
    const res = await getDownloadLinks()
    downloadLinks.value = res.data
  } catch {
    downloadLinks.value = null
  } finally {
    downloadLinksLoading.value = false
  }
}

const ensureDownloadQrGenerated = async () => {
  if (!qrDownloadHref.value) {
    downloadQrDataUrl.value = ''
    return
  }
  if (downloadQrDataUrl.value) return
  downloadQrDataUrl.value = await QRCode.toDataURL(qrDownloadHref.value, {
    width: 220,
    margin: 2,
    errorCorrectionLevel: 'M'
  })
}

const handleDownloadPopoverShow = async () => {
  await ensureDownloadLinksLoaded()
  await ensureDownloadQrGenerated()
}

const openClientDownload = async () => {
  await ensureDownloadLinksLoaded()
  if (!clientDownloadHref.value) {
    ElMessage.warning('暂无可用下载链接')
    return
  }
  window.open(clientDownloadHref.value, '_blank', 'noopener,noreferrer')
}

const copyDownloadQrImage = async () => {
  if (!downloadQrDataUrl.value) return
  if (!window.isSecureContext || !('clipboard' in navigator) || !('ClipboardItem' in window)) {
    ElMessage.warning('当前环境不支持复制图片，请手动保存二维码')
    return
  }

  copyDownloadQrLoading.value = true
  try {
    const qrBlob = await (await fetch(downloadQrDataUrl.value)).blob()
    await navigator.clipboard.write([new ClipboardItem({ 'image/png': qrBlob })])
    ElMessage.success('二维码图片已复制')
  } catch {
    ElMessage.error('复制失败，请检查浏览器权限')
  } finally {
    copyDownloadQrLoading.value = false
  }
}

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

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' }]
})

// 个人身份二维码（GET /identity-qr/）
const identityQrVisible = ref(false)
const identityQrLoading = ref(false)
const identityQrDataUrl = ref('')
const identityQrExpiresText = ref('')

const formatExpiresAt = (iso: string) => {
  try {
    const d = new Date(iso)
    return d.toLocaleString('zh-CN', { hour12: false })
  } catch {
    return iso
  }
}

const fetchIdentityQr = async () => {
  identityQrLoading.value = true
  identityQrDataUrl.value = ''
  identityQrExpiresText.value = ''
  try {
    const { data } = await api.get<{ token: string; expires_at: string }>('/identity-qr/')
    identityQrExpiresText.value = formatExpiresAt(data.expires_at)
    identityQrDataUrl.value = await QRCode.toDataURL(data.token, {
      width: 280,
      margin: 2,
      errorCorrectionLevel: 'M'
    })
  } catch {
    // 全局已提示
  } finally {
    identityQrLoading.value = false
  }
}

const openIdentityQr = () => {
  identityQrVisible.value = true
  fetchIdentityQr()
}

const onIdentityQrDialogClosed = () => {
  identityQrDataUrl.value = ''
  identityQrExpiresText.value = ''
}

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()
  }
  messageStore.initWebSocket()
  messageStore.fetchUnreadCount()
  ensureDownloadLinksLoaded()
})

onUnmounted(() => {
  messageStore.disconnect()
})
</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;
}

.menu-unread-badge {
  background: #ff4d4f;
  color: #fff;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  margin-left: auto;
}

.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;
  gap: 12px;
}
.header-download-link {
  font-size: 14px;
}
.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #333;
}
.username {
  margin-right: 5px;
  font-size: 14px;
}
.dropdown-item-with-icon {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}
.identity-qr-body {
  min-height: 120px;
}
.identity-qr-hint {
  margin: 0 0 12px;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}
.identity-qr-img-wrap {
  display: flex;
  justify-content: center;
  padding: 8px 0;
}
.identity-qr-img {
  display: block;
  width: 280px;
  height: 280px;
}
.identity-qr-expires {
  margin: 12px 0 0;
  text-align: center;
  font-size: 13px;
  color: #909399;
}
.download-popover {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.download-qr-wrap {
  display: flex;
  justify-content: center;
}
.download-qr-img {
  width: 220px;
  height: 220px;
  display: block;
}
.download-qr-empty {
  margin: 0;
  text-align: center;
  color: #909399;
  font-size: 13px;
}
.download-popover-actions {
  display: flex;
  justify-content: center;
}
.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}
</style>
