<template>
  <div class="login-page">
    <!-- Logo -->
    <div class="logo">Logo</div>
    
    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- Logo图标 -->
      <div class="card-logo">
        <div class="logo-icon">Logo</div>
      </div>
      
      <!-- 欢迎文字 -->
      <div class="welcome-text">
        <h1>欢迎来到 Logo</h1>
        <p>智创无限,灵感变现</p>
      </div>
      
      <!-- 登录标题 -->
      <div class="login-title">
        <h2>邮箱验证码登录</h2>
      </div>

      <!-- 登录表单 -->
      <div class="login-form">
        <!-- 邮箱登录 -->
        <div class="email-login">
          <!-- 邮箱输入 -->
          <div class="email-input-group">
            <el-input
              v-model="loginForm.email"
              placeholder="请输入邮箱地址"
              class="email-input"
              type="email"
            />
          </div>
          
          <!-- 验证码输入 -->
          <div class="code-input-group">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
              class="code-input"
            />
            <el-button 
              type="primary" 
              plain 
              class="get-code-btn"
              :disabled="countdown > 0"
              @click="getEmailCode"
            >
              {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
            </el-button>
          </div>
        </div>
        
        <!-- 登录按钮 -->
        <el-button
          type="primary"
          class="login-button"
          :loading="userStore.loading"
          @click="handleLogin"
        >
          {{ userStore.loading ? '登录中...' : '登陆/注册' }}
        </el-button>
        
        <!-- 协议文字 -->
        <p class="agreement-text">
          登录即表示您同意遵守用户协议和隐私政策
        </p>
        
        <!-- 测试邮箱提示 -->
        <div class="test-accounts">
          <el-divider>测试邮箱</el-divider>
          <div class="account-list">
            <div class="account-item" @click="fillTestAccount('admin@example.com', '123456')">
              <strong>管理员:</strong> admin@example.com
            </div>
            <div class="account-item" @click="fillTestAccount('13689270819@example.com', '123456')">
              <strong>普通用户:</strong> 13689270819@example.com
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const countdown = ref(0)
let countdownTimer = null

const loginType = ref('email') // 只支持邮箱登录

const loginForm = reactive({
  email: '',
  code: ''
})

// 清空表单
const clearForm = () => {
  loginForm.email = ''
  loginForm.code = ''
  // 重置倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  countdown.value = 0
}


// 快速填充测试账号
const fillTestAccount = (email, code) => {
  loginForm.email = email
  loginForm.code = code
}

// 组件挂载时设置默认测试账号
onMounted(() => {
  // 设置默认的测试邮箱
  loginForm.email = 'admin@example.com'
  // 不设置验证码，让用户手动输入
})


// 获取邮箱验证码
const getEmailCode = async () => {
  if (!loginForm.email) {
    ElMessage.warning('请先输入邮箱地址')
    return
  }
  
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(loginForm.email)) {
    ElMessage.warning('请输入正确的邮箱地址')
    return
  }
  
  try {
    // 调用后端API发送邮箱验证码
    const response = await fetch('http://localhost:8080/api/verification/email/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: loginForm.email
      })
    })
    
    const result = await response.json()
    
    if (result.success) {
      ElMessage.success('验证码已发送到您的邮箱')
      // 开始倒计时
      startCountdown()
    } else {
      ElMessage.error(result.message || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    // 开发环境：显示真实验证码
    if (process.env.NODE_ENV === 'development') {
      // 生成6位随机验证码（与后端逻辑一致）
      const randomCode = Array.from({length: 6}, () => Math.floor(Math.random() * 10)).join('')
      
      // 开发模式：将验证码同步到后端
      try {
        await fetch('http://localhost:8080/api/verification/email/dev-set', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            email: loginForm.email,
            code: randomCode
          })
        })
      } catch (syncError) {
        console.warn('同步验证码到后端失败:', syncError)
      }
      
      console.log(`📨 模拟发送邮件到: ${loginForm.email}`)
      console.log(`📝 邮件内容: 您的验证码是 ${randomCode}，有效期5分钟`)
      console.log(`📮 发信地址: dev-noreply@local.yourdomain.com`)
      console.log(`🔑 验证码: ${randomCode}`)
      ElMessage.success(`验证码已发送（开发模式）- 验证码: ${randomCode}`)
      startCountdown()
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)
}

const handleLogin = async () => {
  // 验证表单
  if (!loginForm.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(loginForm.email)) {
    ElMessage.warning('请输入正确的邮箱地址')
    return
  }
  
  if (!loginForm.code) {
    ElMessage.warning('请输入验证码')
    return
  }
  
  try {
    console.log('开始登录...')
    
    let result
    
    // 邮箱验证码登录
    try {
      const response = await fetch('http://localhost:8080/api/auth/login/email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          email: loginForm.email,
          code: loginForm.code
        })
      })
      
      const apiResult = await response.json()
      
      if (apiResult.success) {
        // 保存用户信息和token
        sessionStorage.setItem('token', apiResult.data.token)
        sessionStorage.setItem('user', JSON.stringify(apiResult.data.user))
        userStore.user = apiResult.data.user
        userStore.token = apiResult.data.token
        result = { success: true }
      } else {
        result = { success: false, message: apiResult.message }
      }
    } catch (error) {
      console.error('邮箱验证码登录失败:', error)
      // 开发环境：模拟登录成功
      if (process.env.NODE_ENV === 'development') {
        console.log('📧 开发模式：模拟邮箱验证码登录成功')
        // 模拟用户信息（自动注册新用户）
        const username = loginForm.email.split('@')[0]
        const mockUser = {
          id: Math.floor(Math.random() * 1000) + 1,
          username: username,
          email: loginForm.email,
          role: 'ROLE_USER', // 新用户默认为普通用户
          nickname: username,
          points: 50
        }
        const mockToken = 'mock-jwt-token-' + Date.now()
        
        // 保存模拟的用户信息
        sessionStorage.setItem('token', mockToken)
        sessionStorage.setItem('user', JSON.stringify(mockUser))
        userStore.user = mockUser
        userStore.token = mockToken
        
        result = { success: true }
      } else {
        result = { success: false, message: '网络错误，请稍后重试' }
      }
    }
    
    if (result.success) {
      console.log('登录成功，用户信息:', userStore.user)
      ElMessage.success('登录成功')
      
      // 等待一下确保状态更新
      await new Promise(resolve => setTimeout(resolve, 200))
      
      // 跳转到原始路径或个人主页
      const redirectPath = route.query.redirect || '/profile'
      console.log('准备跳转到:', redirectPath)
      
      // 使用replace而不是push，避免浏览器历史记录问题
      await router.replace(redirectPath)
      
      console.log('路由跳转完成')
    } else {
      ElMessage.error(result.message || '登录失败')
    }
  } catch (error) {
    console.error('Login error:', error)
    ElMessage.error('登录失败，请重试')
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  width: 100vw;
  height: 100vh;
  background: url('/images/backgrounds/login.png') center/cover no-repeat;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  margin: 0;
  padding: 0;
  z-index: 1;
}

/* 左上角Logo */
.logo {
  position: absolute;
  top: 30px;
  left: 30px;
  color: white;
  font-size: 18px;
  font-weight: 500;
  z-index: 10;
}

/* 登录卡片 */
.login-card {
  position: absolute;
  top: 50%;
  right: 10%;
  transform: translateY(-50%);
  width: 800px;
  max-width: 90vw;
  background: rgba(100, 150, 200, 0.3);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.5);
  padding: 50px;
  z-index: 10;
}

/* 卡片内Logo */
.card-logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  color: white;
  font-size: 20px;
  font-weight: 500;
}

/* 欢迎文字 */
.welcome-text {
  text-align: center;
  margin-bottom: 50px;
}

.welcome-text h1 {
  color: white;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 12px 0;
}

.welcome-text p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
  margin: 0;
}

/* 登录表单 */
.login-form {
  display: flex;
  flex-direction: column;
  gap: 25px;
}


/* 登录标题 */
.login-title {
  text-align: center;
  margin-bottom: 30px;
}

.login-title h2 {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}


/* 邮箱输入组 */
.email-input-group {
  margin-bottom: 20px;
}

.email-input {
  width: 100%;
}

.email-input :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  box-shadow: 
    inset 0 1px 0 rgba(255, 255, 255, 0.05),
    0 0 0 1px rgba(255, 255, 255, 0.05);
  height: 55px;
}

.email-input :deep(.el-input__inner) {
  color: white;
  background: transparent;
  font-size: 16px;
}

.email-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

/* 验证码输入组 */
.code-input-group {
  display: flex;
  gap: 12px;
}

.code-input {
  flex: 1;
}

.code-input :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  box-shadow: 
    inset 0 1px 0 rgba(255, 255, 255, 0.05),
    0 0 0 1px rgba(255, 255, 255, 0.05);
  height: 55px;
}

.code-input :deep(.el-input__inner) {
  color: white;
  background: transparent;
  font-size: 16px;
}

.code-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

.get-code-btn {
  background: transparent;
  border: 1px solid #409EFF;
  color: #409EFF;
  border-radius: 10px;
  padding: 0 20px;
  font-size: 16px;
  height: 55px;
  transition: all 0.3s ease;
}

.get-code-btn:hover {
  background: #409EFF;
  color: white;
}

.get-code-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 50px;
  background: #409EFF;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 16px;
  font-weight: 500;
  margin-top: 15px;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: #337ecc;
  transform: translateY(-2px);
}

.login-button:active {
  transform: translateY(0);
}

/* 协议文字 */
.agreement-text {
  text-align: center;
  color: rgba(255, 255, 255, 0.5);
  font-size: 14px;
  margin: 25px 0 0 0;
  line-height: 1.4;
}

/* 测试账号提示 */
.test-accounts {
  margin-top: 30px;
}

.test-accounts :deep(.el-divider__text) {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 15px;
}

.account-item {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  padding: 6px 12px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.03);
}

.account-item:hover {
  background: rgba(0, 0, 0, 0.4);
  transform: translateY(-1px);
}

.account-item strong {
  color: #409EFF;
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .login-card {
    right: 5%;
    width: 450px;
  }
}

@media (max-width: 768px) {
  .login-card {
    position: relative;
    top: auto;
    left: auto;
    transform: none;
    margin: 50px auto;
    width: 90%;
    max-width: 500px;
  }
  
  .logo {
    position: relative;
    top: auto;
    left: auto;
    text-align: center;
    margin-bottom: 30px;
    padding-top: 30px;
  }
}

@media (max-width: 480px) {
  .login-card {
    padding: 40px 25px;
  }
  
  .code-input-group {
    flex-direction: column;
    gap: 15px;
  }
  
}
</style>
