import { Injectable } from '@angular/core';
import * as Parse from 'parse';
import { AiChatService } from './aichart.service';
import { HttpService } from './http.service';
declare const AgoraRTC: any;

@Injectable({
  providedIn: 'root',
})
export class LiveService {
  options: {
    appid: string;
    channel: string;
    token: string;
  } = {
    appid: '71d3357d920d4352b39ec8b8d26a7cb9',
    channel: '',
    token: '',
  };
  localTracks: any = {
    audioTrack: null,
    videoTrack: null,
  };
  rid?: string; //房间id(channel)
  profile?:any = localStorage.getItem('profile');
  client: any; //客户端
  company: string = '';
  UID:any
  tools: any = {
    audio:false, //是否关闭音频
    camera: false, //是否切换摄像头
    mute: false, //是否静音
  };
  constructor(private http: HttpService, private aiServ: AiChatService) {
    this.client?.leave();
    this.company = this.aiServ.company;
    this.getProfile();
  }
  async getProfile() {
    if(this.profile) return
    let queryProfile = new Parse.Query('Profile');
    queryProfile.equalTo('user', Parse.User.current()?.id);
    queryProfile.notEqualTo('isDeleted', true);
    queryProfile.equalTo('isCross', true);
    let r = await queryProfile.first();
    this.profile = r?.id
  }
  /* 初始化Agora */
  initAgora() {
    this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'h264' });
    AgoraRTC.enableLogUpload();
  }
  // 获取所有音视频设备
  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';
        });
        let selectedMicrophoneId = audioDevices[0].deviceId;
        let 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 getToken(room: Parse.Object) {
    //获取频道token记录
    if (room?.get('profile').id == this.profile) {
      this.UID = 111111
      let uid = Parse.User.current()?.id;
      if (!uid) {
        return;
      }
      let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
      let reqBody = {
        company: this.company, // this.aiSer.company,
        profile: this.profile,
        channelName: this.profile,
      };
      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 = room?.get('profile').id
      }
    } else {
      let data = await this.updateToken(room?.get('profile').id);
      this.options.token = data.token;
      this.options.channel = data.channel;
      console.log(data);
    }
  }
  /* 获取token */
  async updateToken(pid: string) {
    let sql = `select  "rtc"."objectId" as "rid","rtc"."channel", "rtc"."token",  "rtc"."expiraTime" from "RtcToken" as "rtc" where "rtc"."profile" = '${pid}' and "rtc"."expiraTime" >= now() order by "createdAt" desc limit 1`;
    let tokenData: any = await this.http.customSQL(sql);
    if (
      tokenData &&
      tokenData.code == 200 &&
      tokenData.data &&
      tokenData.data.length > 0
    ) {
      return tokenData.data[0];
    } else {
      return null;
    }
  }
  // 进入频道
  async join() {
    console.log('频道：',this.options.channel);
    let data = await Promise.all([
      this.client.join(this.options.appid, this.options.channel, this.options.token, this.UID),
      /* 创建音频和视频轨道 */
      AgoraRTC.createMicrophoneAudioTrack(),
      AgoraRTC.createCameraVideoTrack(),
    ]);
    // await this.client.setClientRole('host');
    this.localTracks.audioTrack = data[1];
    this.localTracks.videoTrack = data[2];
    let remoteEle = document.getElementById('vice-video');
    if (remoteEle) {
      remoteEle.textContent = '';
    }
    this.localTracks.videoTrack.play('vice-video'); //播放自己视频渲染
    if(this.tools['audio']){
      this.localTracks.audioTrack.setEnabled(false);
    }else{
      this.localTracks.audioTrack.setEnabled(true);
    }
    await this.client.publish(Object.values(this.localTracks));
    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-joined', (user: any) => {
      console.log(user, `${user.uid} 加入频道`);
    });
    this.client.on('user-published', async (user: any, mediaType: any) => {
      console.log('用户推流成功');
      // if (user.uid == 333333) {
      await this.client.subscribe(user, mediaType);
      // }
      let remoteEle = document.getElementById('video');
      if (remoteEle) {
        remoteEle.textContent = '';
      }
      if (mediaType === 'video') {
        user.videoTrack.play(`video`);
      }
      if (mediaType === 'audio') {
        user.audioTrack.play();
      }
    });
    this.client.on('user-unpublished', (user: any) => {
      let remoteEle = document.getElementById('video');
      if (remoteEle) {
        remoteEle.textContent = '对方离开直播间';
      }
      // if (user.uid == 333333) {
      console.log('用户取消推流');
      // }
    });
  }
  /* 停止音频推流 */
  async updatePublishedAudioTrack(){
    this.tools['audio'] = !this.tools['audio'];
    if(this.tools['audio'] && this.localTracks.audioTrack){
      await this.localTracks.audioTrack.setEnabled(false);
      console.log('停止推送音频');
    }else{
      await this.localTracks.audioTrack.setEnabled(true)
      console.log('恢复推送音频');
    }
    // await this.client.unpublish(this.localTracks.audioTrack);
    return true
  }

}
