import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

// 用户信息接口
export interface UserInfo {
  id: string;
  name: string;
  avatar: string;
  roles: string[];
  permissions?: string[];
  lastLogin?: string;
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  // 用户登录状态的BehaviorSubject
  private currentUserSubject: BehaviorSubject<UserInfo | null>;
  public currentUser: Observable<UserInfo | null>;

  constructor() {
    // 为了解决权限问题，我们简化实现，直接创建一个具有所有角色的用户
    const mockUser: UserInfo = {
      id: '1',
      name: '超级管理员',
      avatar: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjQ0NGRkNDIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxMy4zMzMzMzMzMzMzMzMzMzQiIGZvbnQtd2VpZ2h0PSJib2lkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjNTU1NTU1IiBkeT0iMC4zZW0iPkFETUlOPC90ZXh0Pjwvc3ZnPg==',
      roles: ['admin', 'user', 'teamLead'],
      permissions: ['view-all', 'edit-all', 'delete-all'],
      lastLogin: new Date().toISOString()
    };
    
    // 直接使用这个用户，不读取本地存储
    this.currentUserSubject = new BehaviorSubject<UserInfo | null>(mockUser);
    this.currentUser = this.currentUserSubject.asObservable();
  }

  // 获取当前用户信息
  public get currentUserValue(): UserInfo | null {
    return this.currentUserSubject.value;
  }

  // 检查用户是否已登录
  isLoggedIn(): boolean {
    return this.currentUserValue !== null;
  }

  // 获取用户角色
  getUserRoles(): string[] {
    return this.currentUserValue?.roles || [];
  }

  // 检查用户是否具有指定角色
  hasRole(role: string): boolean {
    return this.getUserRoles().includes(role);
  }

  // 检查用户是否具有管理员角色
  isAdmin(): boolean {
    return this.hasRole('admin');
  }

  // 登录方法
  login(username: string, password: string): Observable<boolean> {
    // 在实际应用中，这里会调用后端API进行身份验证
    // 这里使用模拟数据
    return new Observable<boolean>(observer => {
      // 模拟API延迟
      setTimeout(() => {
        // 模拟成功登录
        // 实际应用中，这里会根据后端返回的用户信息设置currentUser
        const mockUser: UserInfo = {
          id: '1',
          name: '超级管理员',
          avatar: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjQ0NGRkNDIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxMy4zMzMzMzMzMzMzMzMzMzQiIGZvbnQtd2VpZ2h0PSJib2lkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjNTU1NTU1IiBkeT0iMC4zZW0iPkFETUlOPC90ZXh0Pjwvc3ZnPg==',
          roles: ['admin', 'user', 'teamLead'],
          permissions: ['view-all', 'edit-all', 'delete-all'],
          lastLogin: new Date().toISOString()
        };

        // 更新用户状态
        this.currentUserSubject.next(mockUser);
        observer.next(true);
        observer.complete();
      }, 1000);
    });
  }

  // 登出方法
  logout(): void {
    // 更新用户状态为null
    this.currentUserSubject.next(null);
  }

  // 更新用户信息
  updateUserInfo(userInfo: Partial<UserInfo>): void {
    const currentUser = this.currentUserValue;
    if (currentUser) {
      const updatedUser = { ...currentUser, ...userInfo };
      this.currentUserSubject.next(updatedUser);
    }
  }

  // 检查用户是否有权限执行某个操作
  hasPermission(permission: string): boolean {
    return this.currentUserValue?.permissions?.includes(permission) || false;
  }
}