<!-- =============================================================================
// 企微IT智能服务台 — 顶栏组件
// =============================================================================
// 说明：独立顶栏组件，从 Workspace.vue 顶部栏抽离
// 包含：Logo + 标题 + 主题切换开关 + 坐席状态 + 登出
// ============================================================================= -->

<template>
  <header class="top-bar">
    <!-- ==================================================================== -->
    <!-- 主顶栏 -->
    <!-- ==================================================================== -->
    <div class="top-bar-main">
      <!-- 左侧：Logo + 标题 -->
      <div class="top-bar-left">
        <span class="logo-block">IT</span>
        <span class="title-gradient">IT智能服务台</span>
        <span class="subtitle">· 坐席工作台 — AI驱动 · 多系统对接 · 一站式处理</span>
      </div>

      <!-- 右侧：主题切换开关 + 坐席状态 + 登出 -->
      <div class="top-bar-right">
        <!-- 主题切换开关（☀️ 滑轨 🌙，匹配原型v5.3） -->
        <div
          class="theme-switch"
          :title="themeStore.currentTheme === 'light' ? '切换到深色模式' : '切换到浅色模式'"
          @click="onThemeSwitch"
        >
          <span class="switch-icon">☀️</span>
          <div class="switch-track">
            <div class="switch-thumb"></div>
          </div>
          <span class="switch-icon">🌙</span>
        </div>

        <!-- 坐席状态切换 -->
        <el-dropdown trigger="click" @command="handleStatusChange">
          <span style="cursor: pointer; display: flex; align-items: center; gap: 4px;">
            <el-tag :type="statusTagType" size="small" effect="dark">
              {{ statusLabel }}
            </el-tag>
            <span class="agent-name">{{ agentStore.agentName }}</span>
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="online">
                🟢 在线 — 接收新会话
              </el-dropdown-item>
              <el-dropdown-item command="busy">
                🟡 忙碌 — 不接新会话
              </el-dropdown-item>
              <el-dropdown-item command="offline">
                ⚪ 离线 — 不接收任何会话
              </el-dropdown-item>
              <el-dropdown-item divided command="otp">
                🔐 OTP二次验证
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 登出按钮 -->
        <el-button text type="danger" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          登出
        </el-button>

        <!-- 小屏幕下显示/隐藏助手面板 -->
        <el-button
          class="assistant-toggle-btn"
          text
          @click="$emit('toggleAssistant')"
        >
          <el-icon><Operation /></el-icon>
        </el-button>
      </div>
    </div>
  </header>

  <!-- ==================================================================== -->
  <!-- OTP 设置对话框 -->
  <!-- ==================================================================== -->
  <el-dialog
    v-model="otpDialogVisible"
    title="OTP二次验证设置"
    width="400px"
    :close-on-click-modal="false"
  >
    <div v-if="otpLoading" v-loading="otpLoading" style="min-height: 200px;"></div>
    <div v-else-if="otpBindData">
      <!-- 已绑定状态 -->
      <template v-if="isOtpBound">
        <el-result icon="success" title="OTP已绑定">
          <template #sub-title>
            <p>当前账号已绑定OTP二次验证</p>
            <p style="color: var(--text-tertiary); font-size: 12px;">
              密钥：{{ otpBindData.secret }}
            </p>
          </template>
        </el-result>
        <el-button type="danger" @click="handleUnbindOtp">解绑OTP</el-button>
      </template>
      <!-- 未绑定状态：显示二维码 -->
      <template v-else>
        <div style="text-align: center;">
          <p style="margin-bottom: 16px;">请使用身份验证器（如Google Authenticator）扫码绑定</p>
          <img :src="otpBindData.qr_code" alt="OTP二维码" style="width: 200px; height: 200px; margin: 0 auto;" />
          <el-divider>或手动输入密钥</el-divider>
          <el-input v-model="otpBindData.secret" readonly>
            <template #append>
              <el-button @click="copyToClipboard(otpBindData.secret)">复制</el-button>
            </template>
          </el-input>
          <el-divider>验证启用</el-divider>
          <el-input v-model="otpInputCode" placeholder="输入6位OTP码" maxlength="6" style="width: 200px;" />
          <el-button type="primary" style="margin-top: 12px;" @click="handleVerifyOtp">
            验证并启用
          </el-button>
        </div>
      </template>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { computed, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAgentStore } from '@/stores/agent'
import { useThemeStore } from '@/stores/theme'
import { useWebSocket } from '@/composables/useWebSocket'
import { useConversationStore } from '@/stores/conversation'
import { bindOtp, verifyOtp, unbindOtp } from '@/api/agent'

// ============================================================================
// 事件
// ============================================================================
defineEmits<{
  (e: 'toggleAssistant'): void
}>()

// ============================================================================
// 状态
// ============================================================================

/** 坐席 Store */
const agentStore = useAgentStore()

/** 主题 Store */
const themeStore = useThemeStore()

/** 会话 Store */
const conversationStore = useConversationStore()

/** WebSocket 组合式函数 */
const { disconnect: disconnectWs } = useWebSocket()

// ============================================================================
// OTP 双因素认证
// ============================================================================

/** OTP 对话框可见性 */
const otpDialogVisible = ref(false)

/** OTP 绑定数据（二维码和密钥） */
const otpBindData = ref<{ qr_code: string; secret: string } | null>(null)

/** 用户输入的 OTP 码 */
const otpInputCode = ref('')

/** OTP 加载状态 */
const otpLoading = ref(false)

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败，请手动复制')
  }
}

/** 是否已绑定 OTP */
const isOtpBound = ref(false)

/**
 * 打开 OTP 设置对话框
 */
async function handleOpenOtp(): Promise<void> {
  otpLoading.value = true
  otpDialogVisible.value = true
  otpInputCode.value = ''
  try {
    const data = await bindOtp()
    otpBindData.value = data
    isOtpBound.value = !!data.secret
  } catch (error) {
    console.error('获取OTP绑定信息失败:', error)
    ElMessage.error('获取OTP绑定信息失败')
  } finally {
    otpLoading.value = false
  }
}

/**
 * 验证并启用 OTP
 */
async function handleVerifyOtp(): Promise<void> {
  if (!otpInputCode.value || otpInputCode.value.length < 6) {
    ElMessage.warning('请输入6位OTP码')
    return
  }
  otpLoading.value = true
  try {
    await verifyOtp(agentStore.userId, otpInputCode.value)
    ElMessage.success('OTP验证成功，已启用二次验证')
    otpDialogVisible.value = false
  } catch (error) {
    console.error('OTP验证失败:', error)
  } finally {
    otpLoading.value = false
  }
}

/**
 * 解绑 OTP
 */
async function handleUnbindOtp(): Promise<void> {
  try {
    await ElMessageBox.confirm('确定要解绑OTP吗？解绑后将不再需要二次验证。', '提示', {
      confirmButtonText: '确定解绑',
      cancelButtonText: '取消',
      type: 'warning',
    })
    otpLoading.value = true
    await unbindOtp()
    ElMessage.success('OTP已解绑')
    otpDialogVisible.value = false
  } catch (error) {
    if ((error as Error)?.message?.includes('cancel')) {
      // 用户取消
    } else {
      console.error('解绑OTP失败:', error)
    }
  } finally {
    otpLoading.value = false
  }
}

// ============================================================================
// 计算属性
// ============================================================================

/** 坐席状态标签文字 */
const statusLabel = computed(() => {
  const statusMap: Record<string, string> = {
    online: '在线',
    busy: '忙碌',
    offline: '离线',
  }
  return statusMap[agentStore.agentStatus] || '离线'
})

/** 坐席状态标签类型 */
const statusTagType = computed(() => {
  const typeMap: Record<string, string> = {
    online: 'success',
    busy: 'warning',
    offline: 'info',
  }
  return typeMap[agentStore.agentStatus] || 'info'
})

// ============================================================================
// 方法
// ============================================================================

/**
 * 主题开关切换回调（el-switch 的 @change）
 * 直接调用 themeStore.toggleTheme()，watch 会自动同步开关状态
 */
function onThemeSwitch(): void {
  themeStore.toggleTheme()
}

/**
 * 切换坐席状态
 */
async function handleStatusChange(status: string): Promise<void> {
  if (status === 'otp') {
    // 打开OTP设置
    await handleOpenOtp()
    return
  }
  try {
    await agentStore.changeStatus(status)
    ElMessage.success(`已切换为${statusLabel.value}`)
  } catch (error) {
    console.error('切换状态失败:', error)
  }
}

/**
 * 登出
 */
async function handleLogout(): Promise<void> {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    disconnectWs()
    conversationStore.stopAllPolling()
    agentStore.logout()
  } catch {
    // 用户取消
  }
}
</script>

<style scoped>
.top-bar {
  flex-shrink: 0;
}

.top-bar-main {
  height: 56px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
}

.top-bar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-block {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  border-radius: 6px;
  background: linear-gradient(135deg, var(--accent), var(--accent));
  color: var(--bg-secondary);
  font-size: 14px;
  font-weight: 800;
  letter-spacing: -0.5px;
  flex-shrink: 0;
}

.title-gradient {
  font-size: 17px;
  font-weight: 700;
  background: linear-gradient(135deg, var(--accent), var(--accent));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  white-space: nowrap;
}

.subtitle {
  font-size: 13px;
  color: var(--text-tertiary);
  white-space: nowrap;
}

.top-bar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.theme-toggle-btn {
  font-size: 18px;
  padding: 4px 8px;
}

.agent-name {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 主题切换滑轨样式（匹配原型v5.3） */
.theme-switch {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  user-select: none;
}

.theme-switch .switch-icon {
  font-size: 15px;
}

.theme-switch .switch-track {
  width: 40px;
  height: 22px;
  background: var(--border-light);
  border-radius: 11px;
  position: relative;
  transition: background 0.3s;
}

[data-theme="dark"] .theme-switch .switch-track {
  background: var(--accent);
}

.theme-switch .switch-thumb {
  width: 18px;
  height: 18px;
  background: var(--bg-secondary);
  border-radius: 50%;
  position: absolute;
  top: 2px;
  left: 2px;
  transition: transform 0.3s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

[data-theme="dark"] .theme-switch .switch-thumb {
  transform: translateX(18px);
}

/* 小屏幕下显示助手切换按钮 */
.assistant-toggle-btn {
  display: none;
}

@media (max-width: 1024px) {
  .assistant-toggle-btn {
    display: inline-flex;
  }
}
</style>
