import {Injectable} from '@angular/core';
import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  CanActivateFn,
  Router,
  CanActivate
} from '@angular/router';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private route: Router) {
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    // 检查本地存储中是否有用户验证信息
    let userAuth = localStorage.getItem("USER_AUTH")
    console.log(userAuth)
    if (userAuth) {
      return true;
    } else {
      // 暂时存储登录前用户所在页面
      let redirectUrl = state.url;
      localStorage.setItem("REDIRECT_URL", redirectUrl);
      this.route.navigate(['user/login']);
      return false;
    }
  }
}
