import { Injectable } from '@angular/core';
import { FmodeParse, FmodeObject } from 'fmode-ng/parse';

const Parse = FmodeParse.with('nova');

/**
 * 全局 Profile 服务
 *
 * 用途：
 * 1. 统一管理当前登录用户的 Profile 信息
 * 2. 支持从 localStorage 缓存读取
 * 3. 支持企微授权自动同步
 * 4. 提供全局单例访问
 */
@Injectable({
  providedIn: 'root'
})
export class ProfileService {
  private currentProfile: FmodeObject | null = null;
  private profileCache: Map<string, FmodeObject> = new Map();

  constructor() {}

  /**
   * 获取当前 Profile
   *
   * 逻辑优先级:
   * 1. 内存缓存
   * 2. localStorage 的 "Parse/ProfileId"
   * 3. 企微授权同步
   *
   * @param cid 公司ID，用于企微授权（可选）
   * @param forceRefresh 强制刷新，默认 false
   * @returns Profile 对象或 null
   */
  async getCurrentProfile(cid?: string, forceRefresh = false): Promise<FmodeObject | null> {
    try {
      // 1. 检查内存缓存
      if (!forceRefresh && this.currentProfile) {
        return this.currentProfile;
      }

      // 2. 尝试从 localStorage 加载
      const profileId = localStorage.getItem('Parse/ProfileId');
      if (profileId) {
        // 检查缓存
        if (!forceRefresh && this.profileCache.has(profileId)) {
          this.currentProfile = this.profileCache.get(profileId)!;
          return this.currentProfile;
        }

        // 从数据库加载
        try {
          const query = new Parse.Query('Profile');
          this.currentProfile = await query.get(profileId);
          this.profileCache.set(profileId, this.currentProfile);
          return this.currentProfile;
        } catch (err) {
          console.warn('Failed to load Profile from localStorage:', err);
          // 清除无效的 profileId
          localStorage.removeItem('Parse/ProfileId');
        }
      }

      // 3. 如果提供了 cid，尝试通过企微授权获取
      if (cid) {
        const profile = await this.syncFromWxwork(cid);
        if (profile) {
          this.currentProfile = profile;
          // 缓存到 localStorage
          profile?.id&&localStorage.setItem('Parse/ProfileId', profile.id);
          profile?.id&&this.profileCache.set(profile.id, profile);
          return profile;
        }
      }

      return null;
    } catch (error) {
      console.error('Failed to get current profile:', error);
      return null;
    }
  }

  /**
   * 通过企微授权同步 Profile
   *
   * @param cid 公司ID
   * @returns Profile 对象或 null
   */
  private async syncFromWxwork(cid: string): Promise<FmodeObject | null> {
    try {
      // 动态导入 WxworkAuth
      const { WxworkAuth } = await import('fmode-ng/core');
      const wxAuth = new WxworkAuth({ cid, appId: 'crm' });

      // 获取用户信息并同步
      const { profile } = await wxAuth.authenticateAndLogin();

      return profile;
    } catch (error) {
      console.error('Failed to sync profile from Wxwork:', error);
      return null;
    }
  }

  /**
   * 根据 profileId 获取 Profile
   *
   * @param profileId Profile ID
   * @param useCache 是否使用缓存，默认 true
   * @returns Profile 对象或 null
   */
  async getProfileById(profileId: string, useCache = true): Promise<FmodeObject | null> {
    try {
      // 检查缓存
      if (useCache && this.profileCache.has(profileId)) {
        return this.profileCache.get(profileId)!;
      }

      // 从数据库加载
      const query = new Parse.Query('Profile');
      const profile = await query.get(profileId);

      // 更新缓存
      this.profileCache.set(profileId, profile);

      return profile;
    } catch (error) {
      console.error('Failed to get profile by id:', error);
      return null;
    }
  }

  /**
   * 设置当前 Profile
   *
   * @param profile Profile 对象
   */
  setCurrentProfile(profile: FmodeObject): void {
    this.currentProfile = profile;
    if(profile?.id){
      this.profileCache.set(profile.id, profile);
      localStorage.setItem('Parse/ProfileId', profile.id);
    }
  }

  /**
   * 清除当前 Profile 缓存
   */
  clearCurrentProfile(): void {
    this.currentProfile = null;
    localStorage.removeItem('Parse/ProfileId');
  }

  /**
   * 清除所有缓存
   */
  clearCache(): void {
    this.currentProfile = null;
    this.profileCache.clear();
    localStorage.removeItem('Parse/ProfileId');
  }

  /**
   * 获取公司所有员工
   *
   * @param companyId 公司ID
   * @param roleName 角色名称（可选）
   * @returns Profile 列表
   */
  async getCompanyProfiles(companyId: string, roleName?: string): Promise<FmodeObject[]> {
    try {
      const query = new Parse.Query('Profile');
      query.equalTo('company', companyId);
      query.notEqualTo('isDeleted', true);

      if (roleName) {
        query.equalTo('roleName', roleName);
      }

      query.ascending('name');
      query.limit(1000);

      return await query.find();
    } catch (error) {
      console.error('Failed to get company profiles:', error);
      return [];
    }
  }
}
