import { Component, ViewChild,OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from "@angular/common/http";
import { Router } from '@angular/router';
import { catchError } from "rxjs/operators";
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
  ValidatorFn,
  AbstractControl,
} from '@angular/forms';
import { CommonCompModule } from '../common.modules';
import { textbookServer } from '../../../services/textbook';
import { AuthServr } from '../../../services/auth.service';
import { CaptchaComponent } from '../../../app/captcha/captcha.component';
import Parse from "parse";
import { NzMessageService } from 'ng-zorro-antd/message';
import { ParseAuthing } from './parse-authing';
import { NzModalService } from 'ng-zorro-antd/modal';
@Component({
  selector: 'app-register',
  standalone: true,
  imports: [ReactiveFormsModule, CommonCompModule,CaptchaComponent],
  templateUrl: './register.component.html',
  styleUrl: './register.component.scss'
})
export class RegisterComponent implements OnInit{
  @ViewChild("codelogin") codelogin: any; 
  @ViewChild("codeloginSign") codeloginSign: any; 

  ngOnInit(){
    let parseAuthing = new ParseAuthing({
      // 监听事件:登陆成功后,返回用户信息
      login:(user,authClient)=>{
        console.log(user,authClient)
        this.authServr.profileVerify(this.modal)
      }
    });
    parseAuthing.initLoginModal();
  }
  code:string = '' //本地生成验证码

  active:number = 0
  validateForm: FormGroup<{
    userName: FormControl<string>;
    password: FormControl<string>;
    code: FormControl<string>;
    checked: FormControl<boolean>;
  }> = this.fb.group({
    userName: ['', [Validators.required]],
    password: ['', [Validators.required]],
    code: ['', [Validators.required]],
    checked: [false]
  });
  //校验手机号
  confirmationValidator: ValidatorFn = (control: AbstractControl): { [s: string]: boolean } => {
    let a = /^1[3456789]\d{9}$/;
    if (!control.value || !String(control.value).match(a)) {
      return { required: true };
    }
    return {};
  };

  validateFormPhone: FormGroup<{
    phoneNumber: FormControl<string>;
    code: FormControl<string>;
    checkCode:FormControl<string>;
    checked: FormControl<boolean>;
  }> = this.fb.group({
    phoneNumber: ['', [Validators.required, this.confirmationValidator]],
    code: ['', [Validators.required]],
    checkCode: ['', [Validators.required]],
    checked: [false]
  });

  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    public router: Router,
    private authServr: AuthServr,
    private message: NzMessageService,
    private http: HttpClient,
    private modal: NzModalService,
  ) {
    Parse?.User?.logOut()
  }


  onChangeCode(e:any){
    let { code } = e
    this.code = code
  }

  submitForm(type:string): void {
    console.log(this.code);
    if(type == 'account'){//登录
      if (this.validateForm.valid) {
        let {userName, password, code, checked } = this.validateForm.value
        console.log(userName, password, code);
        if(this.code.toLowerCase() != code?.toLowerCase()){
          this.message.warning('验证码错误')
          return
        }else if(!checked){
          this.message.warning('请勾选隐私协议与服务条款')
          return
        }
        // this.authServr.login(userName, password, this.tbookSer.company).then(()=>{
        //   this.codelogin.updateDrawCode();
        // }) .catch(err=>{
        //   console.warn(err);
        //   this.message.error(err?.message || '登录失败')
        // })
      } else {
        this.message.warning('填写信息不正确')
        Object.values(this.validateForm.controls).forEach((control) => {
          if (control.invalid) {
            control.markAsDirty();
            control.updateValueAndValidity({ onlySelf: true });
          }
        });
      }
    }else{//手机号登录/注册
      console.log(this.validateFormPhone.value);
      if (this.validateFormPhone.valid) {
        let {phoneNumber, code } = this.validateFormPhone.value
        console.log(phoneNumber, code);
        if(this.code.toLowerCase() != code?.toLowerCase()){
          this.message.warning('验证码错误')
          return
        }
        this.authServr.register(phoneNumber, code, this.tbookSer.company).then(()=>{
          this.codeloginSign.updateDrawCode();
        }).catch((err) => {
          console.warn(err);
          this.message.error(err?.message || '登录失败')
        });
      } else {
        this.message.warning('填写信息不正确')
        Object.values(this.validateFormPhone.controls).forEach((control) => {
          if (control.invalid) {
            control.markAsDirty();
            control.updateValueAndValidity({ onlySelf: true });
          }
        });
      }
    }

  }

  onChange(e: any) {
    console.log(e);
    this.active = e.index
    this.validateForm.reset()
    this.validateFormPhone.reset()
    this.codelogin.updateDrawCode();
    this.codeloginSign.updateDrawCode();
  }

  goUrl(path: string) {
    this.router.navigate([
      path,
      {
        // type: this.currentProfile.type,
      },
    ]);
  }

  buttonText = "获取验证码";
  //添加倒计时开始和结束的判断
  isCountingdown = false;
  /* 获取验证码 */
  codeDown: boolean = false;
  startCountdown() {
    let a = /^1[3456789]\d{9}$/;
    let { phoneNumber, code } = this.validateFormPhone.value
    console.log(phoneNumber);
    if (!String(phoneNumber).match(a)) {
      this.message.error("请填写正确手机号");
      return;
    }
    if (code?.toLowerCase() != this.code.toLowerCase()) {
      this.message.error("验证码不正确");
      return;
    }
    if (this.codeDown || this.isCountingdown) return;
    this.codeDown = true;
    let host =
      (Parse as any).serverURL?.split("parse")?.[0] ||
      "https://server.fmode.cn/";

    this.http
      .post(host + "api/apig/message", {
        company: this.tbookSer.company,
        mobile: phoneNumber,
      })
      .pipe(
        catchError(async (e) => {
          // 显示报错
          console.log(e);
          this.message.create("error", e.error.mess || "验证码获取失败");
          this.codeDown = false;
          this.isCountingdown = false;
          return;
        })
      )
      .subscribe((res: any) => {
        console.log(res);
        if(res){
          this.message.success("发送成功");
          this.isCountingdown = true;
          this.time();
        }
        this.codeloginSign.updateDrawCode();
        this.codeDown = false;
      });
  }
  /* 倒计时 */
  time() {
    this.isCountingdown = true;
    this.buttonText = `${this.authServr.countdown}秒`;
    const timer = setInterval(() => {
      this.authServr.countdown--;
      this.buttonText = `${this.authServr.countdown}秒`;
      if (this.authServr.countdown === 0) {
        clearInterval(timer);
        this.buttonText = "重新发送";
        this.isCountingdown = false;
      }
    }, 1000);
  }


}
