import { Component, OnInit, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { NzMessageService } from "ng-zorro-antd/message";
import { NzModalService } from "ng-zorro-antd/modal";
import { Router, RouterModule } from "@angular/router";
import { catchError } from "rxjs/operators";
import { textbookServer } from "../../../services/textbook";
import { AuthServr } from "../../../services/auth.service";
import Parse from "parse";
import { CommonCompModule } from '../common.modules'

@Component({
  selector: 'app-reset-password',
  standalone: true,
  imports: [CommonCompModule,RouterModule],
  templateUrl: './reset-password.component.html',
  styleUrl: './reset-password.component.scss'
})
export class ResetPasswordComponent {
  @ViewChild("codelogin") codelogin: any; //本地校验码绘画
  company: string = "";

  mobile: string = "";
  password: string = "";
  code: string = ""; //验证码
  localCodeNum: string = ""; //用户填写验证码
  drawCode: Array<string> = []; //本地生成验证码（短信验证码登录）

  passwordVisible: boolean = false;
  buttonText = "获取验证码";
  isConfirm: boolean = false; //点击注册

  constructor(
    private http: HttpClient,
    private msg: NzMessageService,
    private modal: NzModalService,
    private router: Router,
    private loginServr: AuthServr,
    public tbookSer: textbookServer
  ) {
    this.company = this.tbookSer.company;
    console.log(this.company);
    console.log(this.router.url);
  }

  
  ngOnInit() {}

  codeDown: boolean = false;
  //添加倒计时开始和结束的判断
  isCountingdown = false;
  startCountdown() {
    let a = /^1[3456789]\d{9}$/;
    if (!String(this.mobile).match(a)) {
      this.msg.error("请填写正确手机号");
      return;
    }
    let str = this.drawCode.join("");
    if (this.localCodeNum.toLowerCase() != str.toLowerCase()) {
      this.msg.error("验证码不正确");
      return;
    }
    if (this.codeDown) 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.company,
        mobile: this.mobile,
      })
      .pipe(
        catchError(async (e) => {
          // 显示报错
          console.log(e);
          this.msg.create("error", e.error.mess || "验证码获取失败");
          this.codeDown = false;
          return;
        })
      )
      .subscribe((res: any) => {
        console.log(res);
        this.codelogin.updateDrawCode();
        if(res){
          this.msg.success("发送成功");
          this.isCountingdown = true;
          this.time();
        }
        this.codeDown = false;
      });
  }
  /* 倒计时 */
  time() {
    this.isCountingdown = true;
    this.buttonText = `${this.loginServr.resetcountdown}秒`;
    const timer = setInterval(() => {
      this.loginServr.resetcountdown--;
      this.buttonText = `${this.loginServr.resetcountdown}秒`;
      if (this.loginServr.resetcountdown === 0) {
        clearInterval(timer);
        this.buttonText = "重新发送";
        this.isCountingdown = false;
      }
    }, 1000);
  }
  onRegister() {
    if (!this.tbookSer.authMobile(this.mobile)) {
      this.msg.error("请填写正确的手机号");
      return;
    }
    if (!this.code.trim()) {
      this.msg.error("请填写短信验证码");
      return;
    }
    if (this.password.trim().length < 8) {
      this.msg.error("请填写正确的密码");
      return;
    }
    if (this.isConfirm) return;
    this.isConfirm;
    let host =
      (Parse as any).serverURL?.split("parse")?.[0] ||
      "https://server.fmode.cn/";

    this.http
      .post(host + "/api/auth/reset_password", {
        company: this.company,
        mobile: this.mobile,
        code: this.code,
        password: this.password,
      })
      .pipe(
        catchError(async (e) => {
          // 显示报错
          console.log(e);
          this.msg.create("error", "修改失败：" + e.error?.mess);
          this.isConfirm = false;
          return;
        })
      )
      .subscribe((res: any) => {
        console.log(res);
        this.isConfirm = false;
        if (res) {
          this.modal.success({
            nzTitle: "密码重置成功",
            nzContent: "密码已重置，直接登录？",
            nzCancelText: "取消",
            nzOnOk: () => {
              // this.loginServr
              //   .login(this.mobile, this.password, this.company)
              //   .then((data) => {
              //     console.log(data);
              //     this.router.navigate(["developer/app-list"]);
              //   })
              //   .catch((err) => {
              //     console.log(err);
              //     this.msg.error(err.message);
              //   });
            },
          });
        }
      });
  }
}
