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

@Component({
  selector: 'app-register-page',
  templateUrl: './register-page.page.html',
  styleUrls: ['./register-page.page.scss'],
  standalone: true,
  imports: [
    IonContent,
    IonHeader,
    IonTitle,
    IonToolbar,
    CommonModule,
    FormsModule,
    IonButton,
    IonInput,
    IonAlert,
  ],
})
export class RegisterPagePage implements OnInit {
  username: string = '';
  password: string = '';
  confirmPassword: string = '';
  alertButtons = ['确认'];
  header: string = '';
  errormsg: string = '';
  alertClass: string = '';

  constructor(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;
  }
  userInputConfirmPassword(ev: any) {
    this.confirmPassword = ev.detail.value;
  }

  checkPassword(): boolean {
    // 正则表达式
    const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]{3,}$/; // 用户名：至少3个字符，支持字母、数字、下划线和汉字
    const passwordRegex = /^[a-zA-Z0-9]{8,}$/; // 密码：至少8个字符，只支持字母、数字

    // 1. 检查用户名、密码和确认密码是否为空
    if (!this.username || !this.password || !this.confirmPassword) {
      this.header = '错误信息';
      this.errormsg = '用户名或密码为空';
      return false;
    }

    // 2. 检查用户名是否符合正则
    if (!usernameRegex.test(this.username)) {
      this.header = '错误信息';
      this.errormsg =
        '用户名必须至少包含 3 个字符，且只能包含字母、数字或下划线';
      return false;
    }

    // 3. 检查密码是否符合正则
    if (!passwordRegex.test(this.password)) {
      this.header = '错误信息';
      this.errormsg = '密码必须至少包含 8 个字符，且只能包含字母和数字';
      return false;
    }

    // 4. 检查密码与确认密码是否一致
    if (this.password !== this.confirmPassword) {
      this.header = '错误信息';
      this.errormsg = '前后密码不一致';
      return false;
    }

    // 5. 如果所有验证通过
    this.header = '提示信息';
    this.errormsg = 'ok';
    return true;
  }

  async register() {
    let flag = this.checkPassword();

    if (flag) {
      let user = new CloudUser();
      let res = await user.register(this.username, this.password);
      console.log(res);
    }
  }
  ngOnInit() {}
}
