import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild,
  NavigationExtras,
  CanLoad, Route
} from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  constructor(private authService: AuthService, private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

  canLoad(route: Route): boolean {
    let url = `/${route.path}`;
    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    const lifeCustomerInfo = localStorage.getItem('lifeCustomerInfo') ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
    // 如果是AGMS预览薪资单跳转进来的，不需要登录
    if (this.authService.isLoggedIn || (lifeCustomerInfo && lifeCustomerInfo['customerId'] && lifeCustomerInfo['practitionerId']) || (url.indexOf('preFlag=AGMS') >= 0 && url.indexOf('salary_detail') >= 0)) {
      return true;
    }
    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;
    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }

}
