import {Component} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ValidationErrors,
  Validators
} from '@angular/forms';
import {Observable, Observer} from 'rxjs';
import Parse from "parse";
import {Router} from "@angular/router";
import {HttpClient, HttpParams} from "@angular/common/http";
import * as url from "url";

(Parse as any).serverURL = "https://web2023.fmode.cn/parse";
// https://web2023.fmode.cn/s0210490/api/user/login
Parse.initialize("dev")


// const userQuery = new Parse.Query("LjUser");


@Component({
  selector: 'app-page-register',
  templateUrl: './page-register.component.html',
  styleUrls: ['./page-register.component.scss']
})
export class PageRegisterComponent {
  validateForm: FormGroup;

  // await user.set({
  //                  account: this.validateForm.controls['account'].value,
  //                  age: this.age,
  //                  password: this.validateForm.controls['password'].value,
  //                  skills: this.validateForm.controls['comment'].value,
  //                  email: this.validateForm.controls['email'].value,
  //                  stuno: userId,
  //                  availableBalance: '2.00',
  //                })
  async submitForm() {
    // const url_stuno = 'https://web2023.fmode.cn/s0210490/api/user/stuno';
    // let stuno: string = '';
    //
    // try {
    //   const result = await this.http.get<{ stuno: string }>(url_stuno).toPromise();
    //   if (result && result.stuno) {
    //     stuno = result.stuno;
    //   } else {
    //     throw new Error('Invalid result');
    //   }
    // } catch (error) {
    //   console.error('Error fetching stuno:', error);
    //   return;
    // }
    //
    // const url = 'https://web2023.fmode.cn/s0210490/api/user/register';
    //
    // function generateRandomString(): string {
    //   const characters: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    //   let randomString: string = '';
    //
    //   for (let i: number = 0; i < 10; i++) {
    //     const randomIndex: number = Math.floor(Math.random() * characters.length);
    //     randomString += characters.charAt(randomIndex);
    //   }
    //
    //   return randomString;
    // }

    // console.log(stuno)

    const params = {
      account: this.validateForm.controls['account'].value,
      birthday: this.validateForm.controls['datePicker'].value,
      password: this.validateForm.controls['password'].value,
      email: this.validateForm.controls['email'].value,
      skills: this.validateForm.controls['comment'].value,
      availableBalance: '2.00',
      // stuno: stuno,
      // objectId: generateRandomString()
    };
    const user = new Parse.User();
    user.setUsername(params.account);
    user.setPassword(params.password);
    user.setEmail(params.email);
    user.set("age", this.age.toString())
    user.set("isFirstRegister", "1")
    user.set("availableBalance", '2.00')
    user.set("skills", params.skills)
    try {
      let isRegister = await user.signUp();
      if (isRegister?.id) {
        alert("注册成功");
        this.router.navigate(['user/login'])
      }

    } catch (error: any) {
      alert(error.code + " " + error.message)
    }

    // if (stuno) {
    //   try {
    //     const isAccount = await this.http.put(url, params).toPromise();
    //     if (isAccount) {
    //       localStorage.setItem("USER_AUTH", JSON.stringify(params));
    //     }
    //   } catch (error) {
    //     console.error('Error registering user:', error);
    //   }
    // }
  }


  validateConfirmPassword(): void {
    setTimeout(() => this.validateForm.controls['confirm'].updateValueAndValidity());
  }

  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
  // accountValidator = (control: FormControl) => {
  //   const query = new Parse.Query("_User");
  //   query.equalTo("username", control.value);
  //
  //   return new Observable((observer: Observer<ValidationErrors | null>) => {
  //     query.find({
  //       success: (result: any) => {
  //         if (result.count() > 0) {
  //           observer.next(null);
  //         } else {
  //           observer.next({error: true, duplicated: true});
  //         }
  //         observer.complete();
  //       },
  //       error: (error: any) => {
  //         observer.error(error);
  //       }
  //     });
  //   });
  // };

  // this.http.get(url, {params}).subscribe(
  //   (isAccount) => {
  //     setTimeout(() => {
  //       if (!isAccount) {
  //         observer.next({error: true, duplicated: true});
  //       } else {
  //         observer.next(null);
  //       }
  //       observer.complete();
  //     }, 1000);
  //   },
  //   (error) => {
  //     console.error(error);
  //     observer.error(error);
  //   }
  // );


  //判断当前年龄是否在18-60之间
  selectedDate!: Date;
  age!: number;

  calculateAge(): boolean {
    this.selectedDate = new Date(this.validateForm.controls['datePicker'].value);
    const currentDate = new Date();
    this.age = currentDate.getFullYear() - this.selectedDate.getFullYear();

    return this.age > 18 && this.age < 60;
  }


  ageValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {error: true, required: true};
    } else if (!this.calculateAge()) {
      return {datePicker: true, error: true};
    }
    return {};
  };

  //电子邮件提示
  emailOptions: string[] = ['@qq.com', '@gmail.com', '@outlook.com', '@yahoo.com'];
  filteredEmails: string[] = [];
  emailValue: string;

  filterEmails(): void {
    const emailControl = this.validateForm.get('email');
    if (emailControl) {
      const emailValue = emailControl.value;
      this.filteredEmails = this.emailOptions.filter(option => option.includes(emailValue));
    }
  }


  constructor(private fb: FormBuilder,
              private router: Router,
              private http: HttpClient) {
    this.validateForm = this.fb.group({
      account: ['', [Validators.required,],],
      // this.accountValidator
      // Validators.pattern('^[0-9]{6,12}$')],]
      email: ['', [Validators.required]],
      // Validators.email,
      password: ['', [Validators.required,],],
      // this.passwordValidator
      confirm: ['', [this.confirmValidator]],
      comment: ['', [Validators.required]],
      datePicker: ['', [this.ageValidator]],
    });
    this.emailValue = '';

  }

  //密码检测和判断是否相同逻辑
  passwordValidator(control: FormControl): { [key: string]: boolean } | null {
    const password = control.value;

    // 检查密码是否包含字母和数字的混合
    const hasLetter = /[a-zA-Z]/.test(password);
    const hasNumber = /\d/.test(password);
    const isValid = hasLetter && hasNumber;

    // 检查密码长度是否在6到10位之间
    const isLengthValid = password.length >= 6 && password.length <= 10;

    if (!isValid || !isLengthValid) {
      return {'invalidPassword': true};
    }

    return null;
  }

  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {error: true, required: true};
    } else if (control.value !== this.validateForm.controls['password'].value) {
      return {confirm: true, error: true};
    }
    return {};
  };
}
