<template>
  <div class="profile-page">
    <div class="header">
      <div class="header-left">
        <h1>👤 个人中心</h1>
        <button @click="goToDashboard" class="back-btn">🏠 返回首页</button>
      </div>
      <button @click="handleLogout" class="logout-btn">退出登录</button>
    </div>

    <div class="profile-content">
      <!-- 用户基本信息 -->
      <div class="card">
        <h2>基本信息</h2>
        <div class="user-info">
          <div class="info-item">
            <label>用户名:</label>
            <span>{{ userInfo?.username || '未获取' }}</span>
          </div>
          <div class="info-item">
            <label>姓名:</label>
            <span>{{ userInfo?.nickName || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>用户ID:</label>
            <span>{{ userInfo?.userId || '未知' }}</span>
          </div>
          <div class="info-item">
            <label>部门:</label>
            <span>{{ userInfo?.currentDeptId || '未分配' }}</span>
          </div>
          <div class="info-item">
            <label>性别:</label>
            <span>{{ userInfo?.sex || '未知' }}</span>
          </div>
        </div>
      </div>

      <!-- 权限信息 -->
      <div class="card">
        <h2>权限信息</h2>
        <div class="permissions">
          <div class="section">
            <h3>角色列表</h3>
            <div class="tag-list">
              <span 
                v-for="role in userInfo?.roles" 
                :key="role" 
                class="tag role-tag"
              >
                {{ role }}
              </span>
              <span v-if="!userInfo?.roles?.length" class="tag empty-tag">
                暂无角色
              </span>
            </div>
          </div>
          
          <div class="section">
            <h3>权限列表</h3>
            <div class="tag-list">
              <span 
                v-for="permission in userInfo?.permissions" 
                :key="permission" 
                class="tag permission-tag"
              >
                {{ permission }}
              </span>
              <span v-if="!userInfo?.permissions?.length" class="tag empty-tag">
                暂无权限
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- SDK功能演示 -->
      <div class="card">
        <h2>SDK功能演示</h2>
        <div class="sdk-demo">
          <div class="demo-section">
            <h3>认证状态</h3>
            <div class="status-indicator" :class="{ 'authenticated': isAuthenticated }">
              {{ isAuthenticated ? '✅ 已认证' : '❌ 未认证' }}
            </div>
          </div>
          
          <div class="demo-section">
            <h3>Token信息</h3>
            <button @click="showToken" class="demo-btn">
              查看Token
            </button>
            <div v-if="tokenVisible" class="token-display">
              <pre>{{ formattedToken }}</pre>
            </div>
          </div>
          
          <div class="demo-section">
            <h3>权限检查</h3>
            <div class="permission-check">
              <input 
                v-model="checkPermission" 
                placeholder="输入权限标识" 
                class="permission-input"
              />
              <button @click="checkPermissionFunc" class="demo-btn">
                检查权限
              </button>
              <div v-if="permissionResult !== null" class="check-result">
                结果: {{ permissionResult ? '✅ 有权限' : '❌ 无权限' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import unifiedLoginSDK, { type UserInfo } from 'oauth2-login-sdk';

const router = useRouter();

const userInfo = ref<UserInfo | null>(null);
const isAuthenticated = ref(false);
const tokenVisible = ref(false);
const checkPermission = ref('');
const permissionResult = ref<boolean | null>(null);

// 获取用户信息
const loadUserInfo = async() => {
  try {
    isAuthenticated.value = unifiedLoginSDK.isAuthenticated();
    if (isAuthenticated.value) {
      userInfo.value = await unifiedLoginSDK.getUserInfo();
      console.log('👤 用户信息:', userInfo.value);
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 返回Dashboard
const goToDashboard = () => {
  console.log('🏠 返回Dashboard页面');
  router.push('/dashboard');
};

// 退出登录
const handleLogout = async () => {
  try {
    console.log('🚪 正在退出登录...');
    await unifiedLoginSDK.logout();
    // SDK会自动跳转到配置的退出页面
  } catch (error) {
    console.error('退出登录失败:', error);
  }
};

// 显示Token
const showToken = () => {
  tokenVisible.value = !tokenVisible.value;
};

// 格式化显示Token
const formattedToken = computed(() => {
  const token = unifiedLoginSDK.getToken();
  if (!token) return '无Token';
  
  // 简化显示，只显示前20位和后20位
  if (token.length > 40) {
    return `${token.substring(0, 20)}...${token.substring(token.length - 20)}`;
  }
  return token;
});

// 检查权限
const checkPermissionFunc = async () => {
  if (!checkPermission.value.trim()) return;
  
  try {
    permissionResult.value = await unifiedLoginSDK.hasPermission(checkPermission.value);
    console.log(`🔑 权限检查 "${checkPermission.value}":`, permissionResult.value);
  } catch (error) {
    console.error('权限检查失败:', error);
    permissionResult.value = false;
  }
};

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.profile-page {
  padding: 20px;
  max-width: 100%; /* 铺满全屏 */
  width: 100%;
  margin: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header h1 {
  margin: 0;
  color: #333;
}

.logout-btn {
  background: #ff4757;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: background 0.3s;
}

.logout-btn:hover {
  background: #ff2e42;
}

.back-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.back-btn:hover {
  background: #5a6fd8;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.back-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.back-btn:hover {
  background: #5a6fd8;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.card {
  background: white;
  border-radius: 8px;
  padding: 25px;
  margin-bottom: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.card h2 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.user-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 5px;
}

.info-item label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
  color: #666;
}

.permissions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.section h3 {
  margin-top: 0;
  color: #555;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

.role-tag {
  background: #e3f2fd;
  color: #1976d2;
  border: 1px solid #bbdefb;
}

.permission-tag {
  background: #e8f5e8;
  color: #388e3c;
  border: 1px solid #c8e6c9;
}

.empty-tag {
  background: #ffebee;
  color: #c62828;
  border: 1px solid #ffcdd2;
}

.sdk-demo {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.demo-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.demo-section h3 {
  margin-top: 0;
  color: #444;
}

.status-indicator {
  padding: 10px;
  border-radius: 5px;
  text-align: center;
  font-weight: bold;
}

.status-indicator.authenticated {
  background: #e8f5e8;
  color: #388e3c;
}

.demo-btn {
  background: #1976d2;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin: 10px 0;
  transition: background 0.3s;
}

.demo-btn:hover {
  background: #1565c0;
}

.token-display {
  margin-top: 10px;
  background: #2d2d2d;
  color: #f8f8f2;
  padding: 15px;
  border-radius: 5px;
  overflow-x: auto;
}

.token-display pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
}

.permission-check {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.permission-input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.check-result {
  font-weight: bold;
  padding: 8px;
  border-radius: 4px;
}

@media (min-width: 1600px) {
  .profile-page {
    max-width: 1600px;
    padding: 30px 40px;
  }
  
  .permissions {
    grid-template-columns: repeat(3, 1fr); /* 在超宽屏上显示3列 */
  }
  
  .sdk-demo {
    grid-template-columns: repeat(2, 1fr); /* 在超宽屏上显示2列 */
  }
}

@media (min-width: 1200px) and (max-width: 1599px) {
  .permissions {
    grid-template-columns: repeat(2, 1fr); /* 在大屏上显示2列 */
  }
  
  .sdk-demo {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .permissions {
    grid-template-columns: 1fr;
  }
  
  .sdk-demo {
    grid-template-columns: 1fr;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>