import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NavController } from '@ionic/angular';
import {
  IonButton,
  IonContent,
  IonHeader,
  IonInput,
  IonTitle,
  IonToolbar,
} from '@ionic/angular/standalone';
import { Router } from '@angular/router';
import { CloudUser } from 'src/lib/cyxncloud';
import { User } from 'src/app/tab4/tab4.page';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page.page.html',
  styleUrls: ['./login-page.page.scss'],
  standalone: true,
  imports: [
    IonContent,
    IonHeader,
    IonTitle,
    IonToolbar,
    CommonModule,
    FormsModule,
    IonButton,
    IonInput,
  ],
})
export class LoginPagePage implements OnInit {
  username: string = '';
  password: string = '';
  is_login: boolean = false;
  currentUser: CloudUser | null = null;
  user: User = {
    avatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
    username: '请登录',
    age: 0,
    sex: '-',
    email: '-',
    phoneNumber: '-',
    height: 0,
    weight: 0,
    fans: 0,
    likes: 0,
  };

  constructor(private navCtrl: NavController, private router: Router) {}

  navigateTo(path: string) {
    this.router.navigate([`/${path}`]);
  }

  userInputUsername(ev: any) {
    this.username = ev.detail.value;
  }
  userInputPassword(ev: any) {
    this.password = ev.detail.value;
  }
  async login() {
    if (this.username && this.password) {
      console.log('用户名:', this.username, '密码:', this.password);
      this.is_login = true;
      let user = new CloudUser();
      this.currentUser = await user.login(this.username, this.password);

      if (this.currentUser) {
        this.user.avatar = this.currentUser.data.avatar;
        this.user.username = this.currentUser.data.username;
        this.user.age = this.currentUser.data.age;
        this.user.sex = this.currentUser.data.sex;
        this.user.email = this.currentUser.data.email;
        this.user.phoneNumber = this.currentUser.data.phoneNumber;
        this.user.height = this.currentUser.data.height;
        this.user.weight = this.currentUser.data.weight;
        this.user.fans = this.currentUser.data.fans;
        this.user.likes = this.currentUser.data.likes;
        localStorage.setItem('userData', JSON.stringify(this.currentUser.data));
        localStorage.setItem('is_login', 'true');
        console.log('登录成功');
        this.router.navigate([`/tabs/tab4`]);
      }
    }
  }

  navigateToRegister() {
    this.navCtrl.navigateForward('/register');
  }

  ngOnInit() {}
}
