<template>
  <div class="login-container">
    <!-- 左侧标题 -->
    <div class="left-title">
      <h1 class="main-title">智慧宁夏牧场</h1>
    </div>

    <!-- 玻璃态登录卡片 -->
    <div class="glass-card">
      <div class="card-header">
        <h1 class="login-title">用户登录</h1>
      </div>

      <!-- 信息提示框 -->


      <!-- 错误提示 -->
      <div v-if="error" class="error-alert">
        <span class="error-icon">⚠️</span>
        <span class="error-message">{{ error }}</span>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 用户名输入框 -->
        <div class="input-group">
          <label class="input-label">
            <span class="required">*</span> 用户名:
          </label>
          <div class="input-wrapper">
            <span class="input-icon">👨‍💼</span>
            <input
              v-model="formState.username"
              type="text"
              class="form-input"
              placeholder="请输入用户名"
              required
            />
          </div>
        </div>

        <!-- 密码输入框 -->
        <div class="input-group">
          <label class="input-label">
            <span class="required">*</span> 密码:
          </label>
          <div class="input-wrapper">
            <span class="input-icon">🔒</span>
            <input
              v-model="formState.password"
              :type="showPassword ? 'text' : 'password'"
              class="form-input"
              placeholder="请输入密码"
              required
            />
            <button
              type="button"
              class="password-toggle"
              @click="togglePassword"
            >
              {{ showPassword ? '👁️' : '🚫' }}
            </button>
          </div>
        </div>

        <!-- 登录按钮 -->
        <button
          type="submit"
          class="login-button"
          :disabled="loading"
        >
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores';

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const error = ref('');
const showPassword = ref(false);

const formState = reactive({
  username: '',
  password: ''
});

// 切换密码显示/隐藏
const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

// 页面加载时检查token状态
onMounted(async () => {
  // 如果已有有效token，直接跳转到仪表盘
  if (userStore.token) {
    try {
      const isValid = await userStore.validateToken();
      if (isValid) {
        const redirectPath = router.currentRoute.value.query.redirect || '/dashboard';
        router.push(redirectPath);
        return;
      }
    } catch (error) {
      console.log('Token验证失败，需要重新登录');
      userStore.logout(); // 清除无效token
    }
  }
});

const handleLogin = async (values) => {
  loading.value = true;
  error.value = '';
  
  try {
    // 使用表单数据进行登录
    const username = values?.username || formState.username;
    const password = values?.password || formState.password;
    
    // 验证表单数据
    if (!username || !password) {
      error.value = '请输入用户名和密码';
      return;
    }
    
    console.log('开始登录，用户名:', username);
    
    // 使用Pinia用户存储进行登录
    const result = await userStore.login(username, password);
    
    console.log('登录结果:', result);
    
    if (result.success) {
      // 登录成功提示
      message.success(`登录成功，欢迎 ${userStore.userData.username}`);
      
      // 获取重定向路径（如果有）
      const redirectPath = router.currentRoute.value.query.redirect || '/dashboard';
      
      // 跳转到重定向路径或仪表盘页面
      router.push(redirectPath);
    } else {
      error.value = result.message || '登录失败';
    }
  } catch (e) {
    console.error('登录错误:', e);
    error.value = e.message || '登录失败，请检查网络连接和后端服务状态';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 主容器 - 图片背景 */
.login-container {
  min-height: 100vh;
  background: url('/cows.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 20px 160px 20px 20px;
  position: relative;
  overflow: hidden;
}

/* 左侧标题 */
.left-title {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 3;
  text-align: center;
}

.main-title {
  color: #ffffff;
  font-size: 48px;
  font-weight: 700;
  margin: 0 0 16px 0;
  text-shadow: 0 4px 20px rgba(0, 0, 0, 0.6);
  letter-spacing: 2px;
  line-height: 1.2;
}

.subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 20px;
  font-weight: 400;
  margin: 0;
  text-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
  letter-spacing: 1px;
  line-height: 1.4;
}

/* 玻璃态卡片 */
.glass-card {
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.4);
  box-shadow: 
    0 8px 32px 0 rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
  padding: 40px;
  width: 100%;
  max-width: 380px;
  min-width: 350px;
  position: relative;
  z-index: 2;
  transition: all 0.3s ease;
}

.glass-card:hover {
  transform: translateY(-3px);
  background: rgba(255, 255, 255, 0.35);
  box-shadow: 
    0 12px 40px 0 rgba(0, 0, 0, 0.4),
    inset 0 1px 0 rgba(255, 255, 255, 0.4);
}

/* 卡片头部 */
.card-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  color: #fff;
  font-size: 28px;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 12px rgba(0, 0, 0, 0.6);
}

/* 信息提示框 */
.info-box {
  background: rgba(255, 255, 255, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
  backdrop-filter: blur(20px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.info-text {
  color: #fff;
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
}

.info-text:first-child {
  font-weight: 600;
  margin-bottom: 8px;
}

/* 错误提示 */
.error-alert {
  background: rgba(255, 77, 79, 0.2);
  border: 1px solid rgba(255, 77, 79, 0.4);
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(10px);
}

.error-icon {
  font-size: 16px;
}

.error-message {
  color: #fff;
  font-size: 14px;
}

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

/* 输入组 */
.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-label {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.required {
  color: #ff4d4f;
  font-size: 16px;
}

/* 输入框包装器 */
.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 12px;
  font-size: 16px;
  z-index: 1;
  color: rgba(255, 255, 255, 0.7);
}

.form-input {
  width: 100%;
  height: 48px;
  background: rgba(255, 255, 255, 0.25);
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 8px;
  padding: 0 16px 0 40px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  backdrop-filter: blur(20px);
  transition: all 0.3s ease;
  outline: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.form-input::placeholder {
  color: rgba(255, 255, 255, 0.8);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.form-input:focus {
  border-color: rgba(255, 255, 255, 0.7);
  background: rgba(255, 255, 255, 0.35);
  box-shadow: 
    0 0 0 2px rgba(255, 255, 255, 0.4),
    0 4px 16px rgba(0, 0, 0, 0.3);
}

/* 密码切换按钮 */
.password-toggle {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: color 0.3s ease;
  z-index: 1;
}

.password-toggle:hover {
  color: rgba(255, 255, 255, 1);
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 48px;
  background: linear-gradient(90deg, #4CAF50 0%, #45a049 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(76, 175, 80, 0.4);
}

.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-button:hover::before {
  left: 100%;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(76, 175, 80, 0.6);
}

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

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 加载动画 */
.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    justify-content: center;
    padding: 20px;
  }
  
  .left-title {
    position: relative;
    top: auto;
    left: auto;
    text-align: center;
    margin-bottom: 30px;
  }
  
  .main-title {
    font-size: 36px;
  }
  
  .subtitle {
    font-size: 16px;
  }
  
  .glass-card {
    max-width: 100%;
    min-width: auto;
    padding: 30px 20px;
    margin: 0 10px;
  }
}

@media (max-width: 480px) {
  .glass-card {
    padding: 30px 20px;
    margin: 0 10px;
  }
  
  .login-title {
    font-size: 24px;
  }
  
  .form-input {
    height: 44px;
  }
  
  .login-button {
    height: 44px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .glass-card {
    background: rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .form-input {
    background: rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
  
  .form-input:focus {
    background: rgba(0, 0, 0, 0.3);
    border-color: rgba(255, 255, 255, 0.4);
  }
}
</style>