import { Component } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Md5 } from 'ts-md5';
import { CommonNzModule } from '../../common.nz.module';
import { AuthService } from '../../services/auth.service';
import { SettingService } from '../../services/setting.service';
import { StorageService } from '../../services/storage.service';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.less',
})
export class LoginComponent {
  validateForm!: UntypedFormGroup;
  loading = false;
  displayPassword = false;
  constructor(
    private fb: UntypedFormBuilder,
    private readonly auth: AuthService,
    private readonly storage: StorageService,
    private readonly setting: SettingService,
    private readonly message: NzMessageService,
    private readonly router: Router
  ) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [false],
    });
    this.initUserInfo();
  }
  initUserInfo() {
    const username = this.storage.getString('username');
    const password = this.storage.getString('password');
    const remember = this.storage.getBoolean('remember');
    if (username !== undefined && password !== undefined) {
      this.validateForm.setValue({
        userName: username,
        password: password,
        remember: remember || false,
      });
    }
  }
  async submitForm() {
    if (this.loading) return;
    if (!this.validateForm.valid) {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      return;
    }
    this.loading = true;
    const username = this.validateForm.get('userName')?.value;
    let password = this.validateForm.get('password')?.value;
    const remember = this.validateForm.get('remember')?.value;
    const resp = await this.auth
      .login({ username, password: Md5.hashStr(password) })
      .catch(e => {
        this.message.error('用户名或密码错误');
        throw e;
      })
      .finally(() => {
        this.loading = false;
      });
    if (remember) {
      this.storage.setString('username', username);
      this.storage.setString('password', password);
      this.storage.setBoolean('remember', remember);
    } else {
      // this.storage.remove('username');
      // this.storage.remove('password');
      this.storage.remove('remember');
    }
    // this.storage.setNumber('id', resp.changePassword);
    this.storage.addUser({
      id: username,
      name: username,
      password: password,
    });
    this.storage.token = resp.token;
    await this.afterLogin();
  }
  private async afterLogin() {
    this.setting.init();
    const { url } = this.router;
    const l = new URL(location.origin + url);
    const form = l.searchParams.get('from');
    const nvUrl = form ? form : '/manager/workbench/my';
    location.replace(nvUrl);
  }
}
