import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { login } from 'src/app/service/api'; // 引入 login 方法

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage {
  loginForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private router: Router
  ) {
    this.loginForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
    });
  }
  // 登录提交
  async onSubmit() { 
    if (this.loginForm.valid) {
      const formData = this.loginForm.value;
      try {
        const response = await login(formData); // 调用后端 API 进行登录
        if (response.success) {
          localStorage.setItem('userToken', response.token);// 存储用户 Token
          localStorage.setItem('user', JSON.stringify(response.data)); // 存储用户数据
          localStorage.removeItem('guest'); // 移除游客标志
          console.log('用户登录成功，数据已存储');
          this.router.navigate(['/tabs/tab1']); // 跳转到目标页面
        } else {
          alert('登录失败，请检查账号和密码！');
        }
      } catch (error) {
        console.error('登录请求失败：', error);
        alert('登录请求失败，请稍后再试！');
      }
    } else {
      alert('请填写完整的表单！');
    }
  }
  // 游客登录
  guestLogin() {
    console.log('游客登录');
    // 清除可能存在的用户登录数据
    localStorage.removeItem('user');
    localStorage.setItem('guest', 'true'); // 标记为游客身份
    this.router.navigate(['/tabs/tab1']); // 跳转到首页
  }
  // 注册逻辑
  register() {
    console.log('立即注册');
    this.router.navigate(['/register']); // 跳转到注册页面
  }
}
  
