import { ChangeDetectorRef, Component, Inject, Injector, OnDestroy, OnInit, Optional, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { GeneralHttpService, GeneralUtilsService, StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { ACLService } from '@delon/acl';
import { DA_SERVICE_TOKEN, ITokenService, SocialService } from '@delon/auth';
import { CacheService } from '@delon/cache';
import { SFComponent } from '@delon/form';
import { _HttpClient, MenuService, SettingsService, TitleService } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';

import * as icUtils from '../../../shared/utils/ic-utils';
import {splitStrToArr} from "../../../shared/utils/ic-utils";
import * as incontrolUtils from "../../../shared/utils/ic-utils";

@Component({
  selector: 'forget-password',
  templateUrl: './forget.password.component.html',
  styleUrls: ['./forget.password.component.less'],
  providers: [SocialService]
})
export class ForgetPasswordComponent implements OnDestroy, OnInit {
  userId = '';
  @ViewChild('baseSf', { static: false }) baseSf!: SFComponent;
  formData: any = {};

  constructor(
    fb: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    private route: ActivatedRoute,
    private menuService: MenuService,
    private settingsService: SettingsService,
    private aclService: ACLService,
    private socialService: SocialService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    public http: _HttpClient,
    public msg: NzMessageService,
    public utils: GeneralUtilsService,
    private titleService: TitleService,
    private httpUtils: GeneralHttpService,
    public srv: CacheService,
    private modal: NzModalService,
    private notification: NzNotificationService,
    private cdr: ChangeDetectorRef,
    private injector: Injector
  ) {
    this.form = fb.group({
      account: [null, [Validators.required]],
      //mobile: [null, Validators.required],
      // mail: new FormControl({ value: '', disabled: true }),
      verificationCode: [null, Validators.required],
      password: [null, [Validators.required, this.passwordValidator]],
      newPassword: [null, [Validators.required, this.passwordConsistencyValidator]]
    });
    modalSrv.closeAll();
  }

  form: FormGroup;
  error = '';
  type = 0;
  code = '';
  accountCountDown = 0;
  mailCountDown = 0;
  accountInterval$: any;
  mailInterval$: any;
  computerModel = false;

  showForgetPasswordButton = true;
  registerUrl = '/passport/login';
  loginUrl = '/passport/login';
  notifyType: any[] = [];
  fpConfig: any = {};
  loading = false;
  btnContent = 0;
  lastClickTime = 0;
  clickInterval = 1000; // 设置合适的点击间隔
  interval$: any;
  passwordVisible1 = false;
  passwordVisible2 = false;

  ngOnInit(): void {
    const queryInfos = { enabled: 'Y' };
    this.route.queryParams.subscribe((params: Params) => {
      this.account.setValue(params.account);
    });
    this.httpUtils.getLoginConfigList(queryInfos).subscribe(res => {
      if (res && res.data.length > 0) {
        const loginConfig = res.data[0];
        const config = JSON.parse(loginConfig.roption);
        if (loginConfig.logintitile) {
          this.titleService.setTitle(loginConfig.logintitile);
        }
        this.notifyType = config.showForgetPasswordType;
        this.fpConfig = config;
        this.cdr.markForCheck();
      }
    });
    const userCollection = this.srv.get('ic_userCollection', { type: 'm', mode: 'none' });
    if (!incontrolUtils.icIsNotNull(userCollection)) {
      this.httpUtils.getPostData('inControlServer/sys/usercollection/list?v=rw&source=init&_allow_anonymous=true', {}).subscribe({
        next: res => {
          if (res.data?.configList) {
            this.srv.set('ic_userCollection', res.data, { type: 'm' });
          }
        }
      });
    }
  }

  get account() {
    return this.form.controls.account;
  }

  get verificationCode() {
    return this.form.controls.verificationCode;
  }

  get password() {
    return this.form.controls.password;
  }

  get newPassword() {
    return this.form.controls.newPassword;
  }

  get mobile() {
    return this.form.controls.mobile;
  }
  get mail() {
    return this.form.controls.mail;
  }

  passwordValidator = (control: any): { [s: string]: boolean } => {
    //const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$!%*?&])[A-Za-z\d@#$!%*?&]{8,30}$/;
    const regex = /(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,30}$/;
    if (!icUtils.icIsNotNull(control.value)) {
      return { error: true, required: true };
    } else if (!regex.test(control.value)) {
      return { confirm: true, error: true };
    }
    return {};
  };

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

  submit() {
    const accountValue = this.account.value || '';
    const codeValue = this.verificationCode.value || '';
    if (!icUtils.icIsNotNull(accountValue) && !icUtils.icIsNotNull(codeValue)) {
      this.notification.error('请先输入手机号.并点击获取验证码!', '');
      return;
    }
    if (this.password.value !== this.newPassword.value) {
      this.newPassword.markAsDirty({ onlySelf: true });
      this.newPassword.updateValueAndValidity({ onlySelf: true });
      return;
    }
    let pwd = this.password.value;
    const userCollection = this.srv.get('ic_userCollection', { mode: 'none', type: 'm' });
    const globalConfig = incontrolUtils.getConfigByCode(userCollection?.configList || [], 'global_config');
    let igc = globalConfig?.configOption?.config;
    let publicKey = igc?.sqlEncodeCofig?.encodePubkey || '';
    if (icUtils.icIsNotNull(publicKey)) {
      pwd = this.RSALong(publicKey, pwd);
    }
    if (icUtils.icIsNotNull(this.fpConfig.forgetPasswordConfirmApi)) {
      this.http
        .post(this.fpConfig.forgetPasswordConfirmApi, {
          account: accountValue,
          code: codeValue,
          pwd: pwd
        })
        .subscribe(
          (res: any) => {
            if (res.code == '200') {
              this.notification.info(res.msg, '');
              this.router.navigate([this.registerUrl], {});
            }
          },
          (error: any) => {
            console.log('error', error);
          },
          () => {}
        );
    } else {
      this.notification.info('请求无法访问,请联系系统管理员', '');
    }
  }

  ngOnDestroy(): void {
    if (this.accountInterval$) {
      clearInterval(this.accountInterval$);
    }
  }

  getMail(): void {
    this.mailCountDown = 60;
    this.mailInterval$ = setInterval(() => {
      this.mailCountDown -= 1;
      if (this.mailCountDown <= 0) {
        clearInterval(this.mailInterval$);
      }
    }, 1000);
    if (!this.account.valid) {
      this.account.markAsDirty({ onlySelf: true });
      this.account.updateValueAndValidity({ onlySelf: true });
      return;
    }
    if (this.account.value.trim() == '') {
      this.notification.error('账号格式错误', '');
      return;
    }
    this.accountCountDown = 10;
    this.accountInterval$ = setInterval(() => {
      this.accountCountDown -= 1;
      if (this.accountCountDown <= 0) {
        clearInterval(this.accountInterval$);
      }
    }, 1000);
    if (icUtils.icIsNotNull(this.fpConfig.forgetPasswordSmsApi)) {
      this.http
        .post(this.fpConfig.forgetPasswordSmsApi, {
          account: this.account.value,
          sendType: this.notifyType.join(','),
          loginType: 'YD',
          smsCodeTpl: this.fpConfig.forgetPasswordSmsTplId
        })
        .subscribe({
          next: res => {
            if (`${res.code || ''}` === '200') {
              if (res.data.phone) {
                this.mobile.setValue(res.data.phone);
              } else if (res.data.mail) {
                this.mobile.setValue(res.data.mail);
              }
            } else {
              this.notification.error(res.msg, '');
            }
          },
          error: err => console.error(err),
          complete: () => {
            this.cdr.markForCheck();
          }
        });
    } else {
      this.http
        .get(`inControlServer/sys/login/get/verify/account?_allow_anonymous=true&account=${this.account.value}&sendMail=0`)
        .subscribe((res: any) => {
          if (res.code == 200) {
            this.form.patchValue({ mail: res.data.email });
          } else {
            this.notification.error('账号错误10秒后再试', '');
          }
        });
    }
  }

  getVerificationCode(): void {
    const mobileValue = this.mobile.value || '';
    const mailValue = this.mobile.value || '';
    if (!icUtils.icIsNotNull(mobileValue) && !icUtils.icIsNotNull(mailValue)) {
      this.notification.error('请先输入账号.并点击账号校验!', '');
      return;
    }
    if (!this.account.valid) {
      this.account.markAsDirty({ onlySelf: true });
      this.account.updateValueAndValidity({ onlySelf: true });
      return;
    }
    if (!this.verificationCode.valid) {
      this.verificationCode.markAsDirty({ onlySelf: true });
      this.verificationCode.updateValueAndValidity({ onlySelf: true });
      return;
    }

    this.http
      .get(`inControlServer/sys/login/get/verify/account?_allow_anonymous=true&account=${this.account.value}&sendMail=1`)
      .subscribe((res: any) => {
        if (res.code == 200) {
          this.notification.info('验证码已发送', '');
        }
      });
  }

  getCaptcha(): void {
    const accountValue = this.account.value || '';
    if (!icUtils.icIsNotNull(accountValue)) {
      this.notification.error('请输入手机号!', '');
      return;
    }
    const currentTime = Date.now();
    if (currentTime - this.lastClickTime < this.clickInterval) {
      return; // 忽略点击事件
    }
    this.lastClickTime = currentTime;

    if (icUtils.icIsNotNull(this.fpConfig.forgetPasswordSmsApi)) {
      this.http
        .post('inControlServer/qualityInspection/zhcxApi/forgetPwdSendSmsCode?_allow_anonymous=true', {
          account: accountValue
        })
        .subscribe((res: any) => {
          if (res.code == '200') {
            this.btnContent = 59;
            this.interval$ = setInterval(() => {
              this.btnContent -= 1;
              if (this.btnContent <= 0) {
                clearInterval(this.interval$);
                this.btnContent = 0;
              }
            }, 1000);
          } else {
            if (res.code == '501') {
              this.btnContent = 5;
              this.interval$ = setInterval(() => {
                this.btnContent -= 1;
                if (this.btnContent <= 0) {
                  clearInterval(this.interval$);
                  this.btnContent = 0;
                }
              }, 1000);
            }
            //this.error = res.msg;
            return;
          }
        });
    } else {
      this.notification.info('请求无法访问,请联系系统管理员', '');
    }
  }

  returnLogin() {
    this.router.navigate([this.registerUrl], { queryParams: { account: this.account.value || '' } });
  }

  RSALong(publicKey: string, value: string): string {
    const encrypt = new window.JSEncrypt();
    encrypt.setPublicKey(publicKey);
    let sqlArr = splitStrToArr(encodeURIComponent(value), 60);
    return sqlArr.map(v => encrypt.encrypt(v)).join('-_-!');
  }
}
