import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import { textbookServer } from '../../services/textbook';
import Parse from 'parse';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  LoginPage = 'external/404';
  constructor(private tbookSer: textbookServer, private router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return this.checkLogin();
  }
  async checkLogin(): Promise<boolean> {
    const currentUrl = window.location.href;
    return await new Promise((resolve) => {
      fetch(
        'https://audit.hep.com.cn/common-shenhe-api/api/public/index/search/bookPath_cache_check',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ path: currentUrl }), // 传递当前URL
        }
      )
        .then((response) => response.json())
        .then((data) => {
          console.log(data.data);
          if (data.data.rs == 0) {
            window.location.href =
              'https://audit.hep.com.cn/admin/401?noGoBack=0';
            this.router.navigate([this.LoginPage]);
            resolve(false);
            // fetch('https://145.tbook.com.cn/api/textbook/review/token', {
            //   method: 'POST',
            //   headers: {
            //     'Content-Type': 'application/json',
            //   },
            // })
            //   .then((response) => response.json())
            //   .then(async (res) => {
            //     console.log(res);
            //   });
          } else {
            if (!Parse.User.current()?.id) {
              Parse.Cloud.run('reviewToken')
                .then((res) => {
                  console.log(res);
                  Parse.User.become(
                    res?.token || 'r:3494b9dca7a5de2b8394e48e2e51c490'
                  )
                    .then((user) => resolve(true))
                    .catch((err) => {
                      console.error(err);
                      window.location.href =
                        'https://audit.hep.com.cn/admin/401?noGoBack=0';
                      resolve(false);
                    });
                })
                .catch((err) => {
                  console.error('获取token失败:', err);
                  resolve(false);
                  this.router.navigate([this.LoginPage]);
                });
            } else {
              resolve(true);
            }
          }
        })
        .catch((error) => {
          console.error('Error:', error); // 处理错误
          window.location.href =
            'https://audit.hep.com.cn/admin/401?noGoBack=0';
          resolve(false);
        });
    });
  }
}
export { CanActivate };
