import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonButtons, IonContent, IonHeader, IonTitle, IonToolbar,IonBackButton, IonItem, IonLabel, IonButton } from '@ionic/angular/standalone';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { UserService } from '.././services/user.service';
import { AlertController } from '@ionic/angular';


@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  standalone: true,
  imports: [IonContent, IonHeader, IonTitle, IonToolbar, CommonModule, 
    FormsModule,IonButtons,IonBackButton,IonItem,IonLabel,IonButton,ReactiveFormsModule]
})
export class LoginPage implements OnInit {
  loginForm: FormGroup;
  loginError: string = '';

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private userService: UserService,
    private alertController: AlertController
  ) {
    this.loginForm = this.formBuilder.group({
      phone: ['', [Validators.required, Validators.pattern('^1[3-9]\\d{9}$')]],
      password: ['', [Validators.required, Validators.minLength(8)]]
    });
  }

  ngOnInit() {}

  async onSubmit() {
    if (this.loginForm.valid) {
      try {
        const result = await this.userService.login(this.loginForm.value).toPromise();
        if (result.success) {
          this.router.navigate(['/tabs/tab4']);
        } else {
          this.loginError = '手机号或密码错误';
          await this.showErrorAlert('登录失败', '手机号或密码错误');
        }
      } catch (error) {
        console.error('Login error:', error);
        this.loginError = '登录失败，请稍后重试';
        await this.showErrorAlert('登录失败', '请稍后重试');
      }
    }
  }

  async showErrorAlert(header: string, message: string) {
    const alert = await this.alertController.create({
      header,
      message,
      buttons: ['确定']
    });
    await alert.present();
  }

  clearError() {
    this.loginError = '';
  }
} 