import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import * as Parse from 'parse';
import {
  IonicModule,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { AiChatService } from '../../../services/aichart.service';
import { HttpService } from '../../../services/http.service';
declare const AgoraRTC: any;

@Component({
  selector: 'app-live',
  templateUrl: './live.component.html',
  styleUrls: ['./live.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule],
})
export class LiveComponent implements OnInit {
  profile?: Parse.Object;
  rid?: string;
  room?: Parse.Object;
  client: any; //客户端
  options: {
    appid: string;
    channel: string;
    uid: string | undefined;
    token: string;
  } = {
    appid: '',
    channel: '',
    uid: '',
    token: '',
  };
  localTracks: any = {
    audioTrack: null,
    videoTrack: null,
  };
  constructor(
    public toastController: ToastController,
    private loadingCtrl: LoadingController,
    private activateRoute: ActivatedRoute,
    private aiSer: AiChatService,
    private http: HttpService
  ) {}

  ngOnInit() {
    this.client = AgoraRTC.createClient({ mode: 'live', codec: 'h264' });
    AgoraRTC.enableLogUpload();
    this.getDevices();
    this.activateRoute.paramMap.subscribe(async (params) => {
      let rid: any = params.get('rid');
      this.rid = rid;
      if (!this.rid) {
        return;
      }
      this.getRoom();
    });
  }
  // 获取所有音视频设备
  getDevices() {
    AgoraRTC.getDevices()
      .then((devices: any) => {
        const audioDevices = devices.filter(function (device: any) {
          return device.kind === 'audioinput';
        });
        const videoDevices = devices.filter(function (device: any) {
          return device.kind === 'videoinput';
        });

        var selectedMicrophoneId = audioDevices[0].deviceId;
        var selectedCameraId = videoDevices[0].deviceId;
        return Promise.all([
          AgoraRTC.createCameraVideoTrack({ cameraId: selectedCameraId }),
          AgoraRTC.createMicrophoneAudioTrack({
            microphoneId: selectedMicrophoneId,
          }),
        ]);
      })
      .then((tracks: any) => {
        console.log('createCameraVideoTrack', tracks);
      })
      .catch((err: any) => {
        console.log(err);
      });
  }
  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('objectId', this.rid);
    query.notEqualTo('isDeleted', true);
    query.include('user');
    this.room = await query.first();
    let queryProfile = new Parse.Query('Profile');
    queryProfile.equalTo('user', this.room?.get('user').id);
    queryProfile.notEqualTo('isDeleted', true);
    this.profile = await queryProfile.first();
    this.getToken()
  }
  async getToken() {
    let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
    let reqBody = {
      company:'9aMy8gAuey',// this.aiSer.company,
      profile: this.profile?.id,
      channelName: this.profile?.id,
      // department: localStorage.getItem('department'),
      // exam: localStorage.getItem('exam'),
    };
    let data: any = await this.http.httpRequst(baseurl, reqBody,'POST');
    console.log(data);
    if (data.code == 200) {
      (this.options.token = data.data.token),
        (this.options.appid = data.data.appid),
        (this.options.channel = this.profile?.id ?? ''),
        (this.options.uid = this.profile?.id);
      // await this.join();
    }
  }
  // 进入频道
  async join() {
    let data = await Promise.all([
      // join the channel
      this.client.join(
        this.options.appid,
        this.options.channel,
        this.options.token,
        111111
      ),

      // create local tracks, using microphone and camera
      AgoraRTC.createMicrophoneAudioTrack(),
      AgoraRTC.createCameraVideoTrack(),
    ]);
    await this.client.setClientRole('host');
    this.localTracks.audioTrack = data[1];
    this.localTracks.videoTrack = data[2];
    this.localTracks.videoTrack.play('video');
    let publish = await this.client.publish(Object.values(this.localTracks));

    // getCurrentFrameData 获取当前渲染的视频帧数据。
    // 订阅监考端音视频
    this.client.on('user-published', async (user: any, mediaType: any) => {
      console.log('user-published');
      await this.client.subscribe(user, mediaType);
      if (mediaType == 'audio' && user.uid != 333333) {
        console.log(mediaType, user);
        //远端老师发出语音对话提示
        // this.createBasicNotification('请注意，监考老师已向你发出语音通话！', 'info', '语音通话提示')
        const remoteAudioTrack = user.audioTrack;
        remoteAudioTrack.setVolume(100);
        remoteAudioTrack.play();
      }
    });
    // 查询远端用户是否存在小程序端用户
    this.joinReady();
  }
  async joinReady() {
    console.log(this.client.remoteUsers);
    let wxRemoteUsers = this.client.remoteUsers.find((item: any) => {
      if (item.uid && item._video_added_) {
        return item;
      }
    });
    console.log(wxRemoteUsers);
    this.client.on('user-published', async (user: any, mediaType: any) => {
      if (user.uid == 333333) {
        await this.client.subscribe(user, mediaType);
        console.log('用户推流成功');
      }
    });
    this.client.on('user-unpublished', (user: any) => {
      if (user.uid == 333333) {
        console.log('用户取消推流');
      }
    });
  }
}
