import { Injectable } from '@angular/core';
import { MessageService } from './message.service';
import * as Parse from 'parse';
import { AiChatService } from './aichart.service';
@Injectable({
  providedIn: 'root',
})
export class ConnectTaskService {
  anchorChannelName?: string;
  msChannelName: string = 'user_connect_room'; // 主播在线上报频道
  onlineUserList = new Set(); // 在线用户列表
  isSubscribe: boolean = false;

  constructor(private msgSer: MessageService, private aiSer: AiChatService) {}

  async init() {
    // 初始化消息服务,所有用户静默登录
    await this.msgSer.initRTM();
    await this.anchorOnline();
    this.getOnlieUserList(this.msChannelName, 'MESSAGE');
    this.conncetChannels();
  }
  reset() {
    this.onlineUserList = new Set();
    this.isSubscribe = false;
  }
  /* 主播上线 */
  async anchorOnline() {
    let profile;
    try {
      profile = JSON.parse(localStorage.getItem('profile') || '');
    } catch (err) {
      console.log('profile err', err);
    }
    const uid = Parse.User.current()?.id!;
    let nowChannes = await this.getWhereNow(uid);
    console.log('用户已订阅频道：', nowChannes);
    await this.msgSer.setConnectState(uid, 'ONLINE'); //主播开启并订阅自己的聊天频道
    if (profile?.identyType == 'anchor' && !this.isSubscribe) {
      // if (!nowChannes.includes(this.msChannelName)) {
      console.log('订阅成功');
      /* 主播订阅主播频道 */
      await this.msgSer.subscribeMessage(this.msChannelName);
      // }
      // if (!nowChannes.includes(uid)) {
      await this.msgSer.subscribeMessage(uid, {
        //开启并订阅自己的聊天频道
        message: true,
        presence: true,
      });
      // }
      this.isSubscribe = true;
    }else{
      await this.msgSer.subscribeMessage(uid, {
        //开启自己聊天频道用来接受招呼消息
        message: true,
        // presence: true,
      });
    }
  }

  /* 订阅好友频道 */
  async conncetChannels() {
    let uid: any = Parse.User.current()?.id;
    let resultFriends = await this.aiSer.getFriends(uid);
    resultFriends?.data?.forEach(async (item: any) => {
      let channelName = item.channel;
      await this.msgSer.subscribeMessage(
        channelName,
        {
          message: true,
        },
        item.deadline
      );
    });
  }
  /* 获取用户当前所在频道 */
  async getWhereNow(userId: string): Promise<Array<string>> {
    let channes: Array<string> = [];
    try {
      const whereNowResult = await this.msgSer.rtmClient.presence.whereNow(
        userId
      );
      const { channels, totalChannel } = whereNowResult;
      channels.forEach((channelInfo: any) => {
        const { channelName, channelType } = channelInfo;
        channes.push(channelName);
      });
      return channes;
    } catch (status: any) {
      const { operation, reason, errorCode } = status;
      console.error(
        `${operation} failed, the error code is ${errorCode}, because of: ${reason}.`
      );
      return [];
    }
  }

  /* 获取状态 */
  async getState(uid: string, channelName: string, channelType?: string) {
    try {
      const result = await this.msgSer.rtmClient.presence.getState(
        uid,
        channelName,
        channelType ?? 'MESSAGE'
      );
      const { states, userId, statesCount } = result; // Tony 的临时状态
      console.log(`${userId}用户状态：${states.Mode}`);
      // console.log(result);
      return states.Mode;
    } catch (status: any) {
      const { operation, reason, errorCode } = status;
      console.log(
        `${operation} failed, ErrorCode: ${errorCode}, because of: ${reason}.`
      );
      return 'OFFLINE';
    }
  }

  /* 获取在线用户列表 */
  async getOnlieUserList(
    channelName: string,
    page?: string,
    channelType?: string
  ) {
    if (!channelType && this.onlineUserList.size) return;
    const options: any = {
      includedUserId: true,
      includedState: true,
    };
    if (page) options.page = page;
    try {
      const result = await this.msgSer?.rtmClient?.presence?.whoNow(
        channelName,
        channelType ?? 'MESSAGE',
        options
      );
      // console.log(result);
      // 如果 nextPage 存在，下一次调用 whoNow 时，需将 nextPage 的值填入 whoNowOptions 的 page 字段

      let totalOccupancy = result?.totalOccupancy;
      let occupants = result?.occupants;
      let nextPage = result?.nextPage;
      occupants?.forEach((userInfo: any) => {
        const { states, userId, statesCount } = userInfo;
        this.onlineUserList.add(userId);
      });
      console.log('获取在线用户列表：', this.onlineUserList);
      if (nextPage) this.getOnlieUserList(channelName, nextPage, channelType);
    } catch (status: any) {
      // const { operation, reason, errorCode } = status;
      console.error('getOnlieUserList err', status);
      // console.error(
      //   `${operation} failed, ErrorCode: ${errorCode}, due to: ${reason}.`
      // );
    }
  }
}
