// src/app/pages/login.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

// 导入 Ng-Zorro-Antd 组件模块
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzMessageService } from 'ng-zorro-antd/message';
// 关键：在 standalone 组件中导入 NzIconModule
import { NzIconModule } from 'ng-zorro-antd/icon';

import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    NzFormModule,
    NzInputModule,
    NzButtonModule,
    NzCheckboxModule,
    NzIconModule // 确保此模块在此处
  ],
  templateUrl: './login.component.html', // 使用外部模板
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  // 使用 FormGroup 来管理登录表单
  loginForm!: FormGroup;
  // 控制登录按钮的加载状态
  isLoggingIn = false;

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private router: Router,
    private message: NzMessageService
  ) { }

  ngOnInit(): void {
    // 初始化登录表单，并设置验证器
    this.loginForm = this.fb.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required]],
      remember: [true] // 记住我
    });
  }

  /**
   * 提交登录表单
   */
  submitForm(): void {
    if (this.loginForm.valid) {
      this.isLoggingIn = true;
      const { username, password } = this.loginForm.value;

      this.authService.login({ username, password }).subscribe({
        next: (response) => {
          // 登录成功后，AuthService 会处理导航和消息
        },
        error: (error) => {
          // 登录失败，AuthService 会处理错误消息
        },
        complete: () => {
          this.isLoggingIn = false;
        }
      });
    } else {
      Object.values(this.loginForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
}
