import { Component, Inject } from "@angular/core";
import { Router } from "@angular/router";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { SocialService, ITokenService, DA_SERVICE_TOKEN } from "@delon/auth";
import { HttpClient } from "@angular/common/http";
import { catchError } from "rxjs/operators";
import { of } from "rxjs";
import { StartupService } from "../../service/startup.service";

@Component({
  selector: "passport-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.less"],
  providers: [SocialService]
})
export class UserLoginComponent {
  type = 0;
  form: FormGroup;
  error = "";
  constructor(
    fb: FormBuilder,
    private router: Router,
    private socialService: SocialService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    private http: HttpClient
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(4)]],
      password: [null, Validators.required]
    });
    // modalSrv.closeAll();
  }

  // #region fields

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

  // #endregion

  submit() {
    document.cookie = "";
    this.error = "";
    console.log(this.form.value);
    // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验

    this.http
      .post(
        `asset/a/login?__ajax=true&username=${this.userName.value}&password=${
          this.password.value
        }&mobileLogin=true`,
        {}
      )
      .pipe(
        // 接收其他拦截器后产生的异常消息
        catchError(err => {
          console.log(err);
          return of();
        })
      )
      .subscribe(
        (res: any) => {
          if (res.success !== true) {
            this.error = res.msg;
            return;
          }
          // 清空路由复用信息
          // this.reuseTabService.clear();
          // 设置用户Token信息
          res.body.token = res.body.JSESSIONID;
          this.tokenService.set(res.body);
          // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
          this.startupSrv.load().then(() => {
            let url = this.tokenService.referrer!.url || "/";
            if (url.includes("/passport")) url = "/";
            this.router.navigateByUrl(url);
          });
        },
        error => {
          console.log(error);
        }
      );
  }
}
