<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios' // 确保已安装: npm install axios

// 用户信息状态
const userInfo = ref(null)
const loading = ref(false)
const error = ref('')

// 🌟 配置项（请根据你的环境修改）
const FEISHU_APP_ID = 'cli_a834fd65ed3e100e' // 替换为你的飞书 App ID
const REDIRECT_URI = 'http://122.152.216.7/business-app' // 替换为你的前端页面地址（需与飞书平台配置一致）
const BACKEND_API = 'http://122.152.216.7/admin-api' // 替换为你的后端服务地址

// 飞书 OAuth 授权链接生成
const getFeishuAuthUrl = () => {
  const scope = 'user:email,user:phone' // 根据需要调整权限
  const state = Math.random().toString(36).substr(2, 10) // 防 CSRF，建议后端生成并校验
  // 存入 localStorage 用于后续校验
  localStorage.setItem('feishu_oauth_state', state)

  return (
    'https://open.feishu.cn/open-apis/authen/v1/index?' +
    `app_id=${FEISHU_APP_ID}&` +
    `redirect_uri=${encodeURIComponent(REDIRECT_URI)}&` +
    `state=${state}&` +
    `scope=${scope}&` +
    'response_type=code'
  )
}

// 🚀 处理登录：跳转到飞书授权页
const handleLogin = () => {
  const authUrl = getFeishuAuthUrl()
  console.log('url', authUrl)
  //debugger
  window.location.href = authUrl // 跳转到飞书
}

// 🔁 处理回调：从 URL 获取 code 并发送给后端
const handleCallback = async () => {
  const urlParams = new URLSearchParams(window.location.search)
  const code = urlParams.get('code')
  const state = urlParams.get('state')
  console.log(code, state)
  debugger
  // 1. 校验 state (防 CSRF)
  const savedState = localStorage.getItem('feishu_oauth_state')
  if (!state || !savedState || state !== savedState) {
    error.value = '授权请求无效，请重试。'
    console.error('State mismatch. Possible CSRF attack.')
    return
  }

  // 清除 state
  localStorage.removeItem('feishu_oauth_state')

  if (code) {
    loading.value = true
    error.value = ''
    try {
      // 2. 将 code 发送给后端 API 换取用户信息
      const response = await axios.post(
        `${BACKEND_API}/api/auth/feishu/callback`,
        { code },
        {
          headers: {
            'Content-Type': 'application/json'
            // 如果有认证 token，可在此添加 Authorization
          }
        }
      )

      const { data } = response
      if (data.success) {
        userInfo.value = data.user
        // ✅ 登录成功，可存储 token、跳转首页等
        console.log('用户登录成功:', userInfo.value)
      } else {
        error.value = data.message || '登录失败'
      }
    } catch (err) {
      console.error('API 调用失败:', err)
      error.value = err.response?.data?.message || '网络错误，请重试'
    } finally {
      loading.value = false
    }
  }
}

// 页面加载时检查是否为回调
onMounted(() => {
  // 检查当前页面是否有 code 参数（即回调）
  const hasCode = new URLSearchParams(window.location.search).has('code')
  if (hasCode) {
    handleCallback() // 处理回调逻辑
  }
  // 否则，页面正常显示登录按钮
})

// 退出登录
const logout = () => {
  userInfo.value = null
  // 清除 token、session 等
  // router.push('/login') // 可选：跳转
}
</script>

<template>
  <div class="feishu-login-container">
    <!-- 登录状态 -->
    <div v-if="!userInfo && !loading && !error">
      <h2>欢迎登录</h2>
      <button @click="handleLogin" class="feishu-btn">
        <span>🔐 使用飞书账号登录</span>
      </button>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading">
      <p>正在登录...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error">
      <p>{{ error }}</p>
      <button @click="() => (error = '')">重试</button>
    </div>

    <!-- 用户信息 -->
    <div v-if="userInfo" class="user-info">
      <h3>🎉 登录成功！</h3>
      <img :src="userInfo.avatar" :alt="userInfo.nickname" class="avatar" />
      <p><strong>昵称:</strong> {{ userInfo.nickname }}</p>
      <p><strong>用户名:</strong> {{ userInfo.username }}</p>
      <p><strong>邮箱:</strong> {{ userInfo.email }}</p>
      <p><strong>飞书ID:</strong> {{ userInfo.uuid }}</p>
      <button @click="logout" class="logout-btn">退出登录</button>
    </div>
  </div>
</template>

<style scoped>
.feishu-login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 30px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.feishu-btn {
  background: #5d6fd8;
  color: white;
  border: none;
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 20px auto;
  transition: background 0.3s;
}

.feishu-btn:hover {
  background: #4a5bc4;
}

.loading,
.error {
  margin: 20px 0;
  padding: 15px;
  border-radius: 6px;
}

.loading {
  background: #e6f7ff;
  color: #1890ff;
}

.error {
  background: #fff1f0;
  color: #cf1322;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.error button {
  background: #cf1322;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.user-info {
  text-align: left;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
  vertical-align: middle;
}

.logout-btn {
  margin-top: 15px;
  padding: 10px 20px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}
</style>
