// argora
import AgoraRTC, { IAgoraRTCClient, ILocalAudioTrack, ILocalVideoTrack } from 'agora-rtc-sdk-ng';
import { useRtcStore } from '/@/store/modules/rtc';
export type AgoraClient = IAgoraRTCClient;
export { ILocalAudioTrack, ILocalVideoTrack } from 'agora-rtc-sdk-ng';
// import { useRtcSdk } from './useTRTC';
import { ref } from 'vue';
import { muteVideoLeader } from './useTRTC';

export const localAudioTrack = ref<ILocalAudioTrack | null>();
export const localVideoTrack = ref<ILocalVideoTrack | null>();
export let localClient: IAgoraRTCClient;

export const isHasCamera = ref(false);
export const isHasMicrophone = ref(false);
const userID = ref('');
const roomID = ref('');
const CamID = ref('');
export const createAgoraClient = async (
  sdkAppId: string,
  roomId: string,
  sign: string,
  userId: string,
): Promise<IAgoraRTCClient> => {
  const rtcStore = useRtcStore();
  // const { muteVideoLeader } = useRtcSdk();
  userID.value = userId;
  roomID.value = roomId;
  CamID.value = `camera_box_${userID.value}`;
  const isOK = AgoraRTC.checkSystemRequirements();
  if (!isOK) {
    console.log('当前不支持');
  }

  AgoraRTC.enableLogUpload();
  // 将日志输出级别设置为 INFO
  AgoraRTC.setLogLevel(1);

  // const role = rtcStore.role === 'leader' ? 'audience' : 'audience';
  const client: IAgoraRTCClient = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' });
  // client.setClientRole('host');
  localClient = client;

  if (!userID.value) {
    console.error('加入时不能没没有UserID');
    return Promise.reject();
  }
  const uid = await client.join(String(sdkAppId), roomId, sign, userID.value);

  console.warn('rtc-client', uid, client);

  client.on('volume-indicator', function (result) {
    result.forEach(function (volume, index) {
      console.warn(`${index} UID ${volume.uid} Level ${volume.level}`);
    });
  });
  client.on('exception', (error) => {
    console.error('sdk error', error);
  });

  client.on('user-joined', (user) => {
    console.warn('userJoin', user);
  });
  client.on('user-info-updated', (user) => {
    console.log('userJoin', user);
  });
  //取消订阅
  client.on('user-unpublished', async (user, mediaType) => {
    if (mediaType === 'audio') {
      console.error('unpublished-audio', user);
    }
    if (mediaType === 'video') {
      //暂时只有leader有video
      const remoteVideoEl = document.getElementById(`cameraRemoteBox`);
      if (remoteVideoEl) {
        remoteVideoEl.style.display = 'none';
      }
    }
  });
  //发布订阅
  localClient.on('user-published', async (user, mediaType) => {
    console.warn('远程音视频-published', user, mediaType);
    await localClient.subscribe(user, mediaType);
    if (mediaType === 'video') {
      const remoteVideoEl = document.getElementById(`cameraRemoteBox`);
      if (user.videoTrack && user.hasVideo && remoteVideoEl) {
        remoteVideoEl.style.display = 'block';
        console.warn(`收到远程视频-->当前用ID${user.uid}`);
        user.videoTrack.play(remoteVideoEl);
      }
    }
    if (mediaType === 'audio') {
      console.warn(`收到远程音频-->当前用ID${user.uid}`);
      const remoteAudioTrack = user.audioTrack;
      remoteAudioTrack?.play();
    }
  });

  try {
    isHasCamera.value = (await AgoraRTC.getCameras()).length > 0;
    isHasMicrophone.value = (await AgoraRTC.getMicrophones()).length > 0;

    if (isHasCamera.value) {
      localVideoTrack.value = await AgoraRTC.createCameraVideoTrack();
      localVideoTrack.value.setEncoderConfiguration('120p');
    }
  } catch (error) {
    console.error('error', error);
  }

  console.warn('isHasCamera', isHasCamera.value);
  console.warn('isHasMicrophone', isHasMicrophone.value);

  if (rtcStore.role === 'leader') {
    if (isHasCamera.value && localVideoTrack.value) {
      rtcStore.setHasCamera();

      const localVideoEl = document.getElementById(CamID.value);
      if (localVideoEl) {
        try {
          console.warn('播放本地rtc-localVideoTrack', localVideoEl);
          localVideoTrack.value.play(localVideoEl);
        } catch (error) {
          console.error('error', error);
        }
      }
      //主持人有相机的
      console.warn('有VID leader发布流');
      await client.publish(localVideoTrack.value);
      localVideoTrack.value.setMuted(true);
    }
  }

  // if (isHasMicrophone.value) {
  //   await publishLockAudioTrack(true);
  //   console.warn('所有人有MIC静音和发布', localAudioTrack.value?.isPlaying);
  // }
  //默认头闭摄像头
  muteVideoLeader.value = true;
  rtcStore.setIsRTCJoined(true);

  return client;
};

const publishLockAudioTrack = async () => {
  if (localAudioTrack.value) {
    await localClient.unpublish(localAudioTrack.value);
    localAudioTrack.value = null;
  }
  localAudioTrack.value = await AgoraRTC.createMicrophoneAudioTrack();
  if (localAudioTrack.value) {
    await localClient.publish([localAudioTrack.value]);
  }
};
const unPublishLockAudioTrack = async () => {
  if (localAudioTrack.value) {
    await localClient.unpublish([localAudioTrack.value]);
    localAudioTrack.value = null;
  }
};

export const muteVideo = async () => {
  //通用开音方法
  console.error('关cam');
  if (isHasCamera.value) {
    if (localVideoTrack.value) {
      await localClient.unpublish([localVideoTrack.value]);
    }
  }
};

export const unMuteVideo = async () => {
  console.error('开cam');
  if (isHasCamera.value) {
    if (localVideoTrack.value) {
      await localClient.unpublish(localVideoTrack.value);
      localAudioTrack.value = null;
    }
    localVideoTrack.value = await AgoraRTC.createCameraVideoTrack();
    localVideoTrack.value.setEncoderConfiguration('120p');
    if (localVideoTrack.value) {
      await localClient.publish([localVideoTrack.value]);
      const localVideoEl = document.getElementById(CamID.value);
      if (localVideoEl) {
        try {
          console.warn('播放本地rtc-localVideoTrack', localVideoEl);
          localVideoTrack.value.play(localVideoEl);
        } catch (error) {
          console.error('error', error);
        }
      }
    }
  }
};

export const mutedAudio = () => {
  //通用禁音方法
  if (isHasMicrophone.value) {
    console.error('有MIC关MIC');
    unPublishLockAudioTrack();
  }
};
export const unMutedAudio = async () => {
  //通用开音方法
  if (isHasMicrophone.value) {
    // 开MIC要重新发布
    console.error('有MIC开MIC');
    publishLockAudioTrack();
  }
};

export const switchToFrontCam = async () => {
  if (localVideoTrack.value) {
    localVideoTrack.value.close();
    await localClient.unpublish(localVideoTrack.value);
  }
  localVideoTrack.value = null;
  localVideoTrack.value = await AgoraRTC.createCameraVideoTrack({
    facingMode: 'user',
  });
  const localVideoEl = document.getElementById(CamID.value);
  if (localVideoEl) {
    localVideoTrack.value.play(localVideoEl);
  }
  await localClient.publish(localVideoTrack.value);
};

export const switchToBackCam = async () => {
  if (localVideoTrack.value) {
    await localClient.unpublish(localVideoTrack.value);
    localVideoTrack.value = await AgoraRTC.createCameraVideoTrack({
      facingMode: 'environment',
    });
    const localVideoEl = document.getElementById(CamID.value);
    if (localVideoEl) {
      localVideoTrack.value.play(localVideoEl);
    }
    await localClient.publish(localVideoTrack.value);
  }
};
export const cleanAll = () => {
  // AgoraRTC.removeAllListeners();
};
