import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import Parse from 'parse';
import { AlertController } from '../modules/ionic-standalone.modules';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  LoginPage = 'login';

  constructor(
    public router: Router,
    private alertController: AlertController,
    private authServ: AuthService,
  ) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    // 当前路由url
    let url: string = state.url;
    return this.checkLogin(url);
  }
  checkLogin(url: string): boolean {
    // 如果已登录,直接跳转当前路由 跳出该函数
    let currentUser = Parse.User.current();
    if (!currentUser?.id) {
      // 否则重定向到login页面
      this.router.navigate([this.LoginPage]);
      return false;
    }
    let p = localStorage.getItem('profile');
    let missPaths = ['/user/certification', 'tabs/home'];
    if (!missPaths.includes(url) && (!p || !JSON.parse(p)?.isCross)) {
      this.alertModal();
    }
    return true;
  }
  async alertModal() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '实名认证',
      message: '根据相关法律法规要求,请先完成实名',
      backdropDismiss: false,
      buttons: [
        {
          text: '退出',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            this.authServ.logout();
          },
        },
        {
          text: '去认证',
          handler: () => {
            this.router.navigate(['user/certification']);
          },
        },
      ],
    });
    await alert.present();
  }
}
export { CanActivate };
