import { HttpClient } from '@angular/common/http';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormUtils } from 'src/app/lib/utils/form-utils';

@Component({
  selector: 'admin-login',
  template: `
    <form #form nz-form [formGroup]="validateForm"  class="login-form shadow-sm p-4 pt-5 bg-white rounded" (ngSubmit)="submitForm()">
      <h4 class="mb-4 text-right text-secondary" i18n>登陆</h4>
      <nz-form-item>
        <nz-form-control i18n-nzErrorTip nzErrorTip="输入格式正确的用户名">
          <nz-input-group nzPrefixIcon="user">
            <input type="text" nz-input formControlName="username" i18n-placeholder placeholder="用户名" />
          </nz-input-group>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control i18n-nzErrorTip nzErrorTip="输入正确格式的密码">
          <nz-input-group nzPrefixIcon="lock">
            <input type="password" nz-input formControlName="password" i18n-placeholder placeholder="密码" />
          </nz-input-group>
        </nz-form-control>
      </nz-form-item>

      <button nz-button class="login-form-button login-form-margin" [nzType]="'primary'" i18n>登陆</button>

      <p class="text-center" >
        <a href="http://beian.miit.gov.cn/" class="text-center">京ICP备18057264号-1</a>
      </p>
    </form>
  `,
  styles: [
    `
    :host {
      display: flex;
      width:100vw;
      height:100vh;
      flex-direction:column;
      align-items:center;
      justify-content: space-evenly;
      background-color:#f9f9f9;
    }

      .login-form {
        min-width: 400px;
        background:white;
      }

      .login-form-margin {
        margin-bottom: 16px;
      }

      .login-form-forgot {
        float: right;
      }

      .login-form-button {
        width: 100%;
      }

      @keyframes shake {
        0% { margin-left: 0rem; }
        25% { margin-left: 0.5rem; }
        75% { margin-left: -0.5rem; }
        100% { margin-left: 0rem; }
      }

      .error-shake
      {
        animation: shake 0.2s ease-in-out 0s 2;
      }
    `
  ],
  animations : [

  ]
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;

  @ViewChild('form') form : ElementRef;

  return : string;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient, 
    private router : Router,
    private message : NzMessageService,
    private activatedRoute : ActivatedRoute,
    ) { 
      this.return = this.activatedRoute.snapshot.queryParams['return'] || '';

    }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      'username': [
        '',
        [Validators.required, Validators.pattern(/^[a-zA-Z0-9_\.]{5,}$/)]
      ],
      'password': [
        '',
        [Validators.required, Validators.minLength(6)]
      ]
    });
  }


  submitForm(): void {
    if (this.validateForm.valid) {
      let data = this.validateForm.value;
      data.password = data.password.trim();
      this.signIn(data)
        .subscribe((res: any) => {
          console.log('res', res);
          this.message.success($localize`登陆成功!`);
          setTimeout(() => {
            this.router.navigateByUrl(this.return);
          }, 500)
        }, (err) => {
          this.shake();
          this.message.warning(err.error?.message || err.message);
        })
    } else {
      this.shake();
      FormUtils.markAsDirty(this.validateForm);
    }
  }

  shake() {
    let el = this.form?.nativeElement as HTMLElement;
    el?.classList.remove('error-shake');
    void el?.offsetWidth; //trigger reflow
    el?.classList.add('error-shake');
  }


  signIn(data) {
    return this.http.post('/napi/web/auth/sign-in', data);
  }



}
