<template>
  <div></div>
</template>

<script setup>
import { defineEmits, computed,ref } from "vue";
import TRTC from "trtc-js-sdk";
import { useStore } from "vuex";
import { Dialog } from "@/global_components/";
import browser from "@/utils/browser";

const store = useStore();

const videoDeviceId = computed(() => store.getters["rtc/videoDeviceId"]);
const audioDeviceId = computed(() => store.getters["rtc/audioDeviceId"]);
const role = ref(browser.getURLParam("role"));

const emit = defineEmits(["switchDevice","canUseDevice"]);

const updateDevice = async () => {
  console.log("updateDevice");
  const cameraItems = await TRTC.getCameras();
  cameraItems.forEach((item) => {
    item.value = item.deviceId;
  });
  const microphoneItems = await TRTC.getMicrophones();
  microphoneItems.forEach((item) => {
    item.value = item.deviceId;
  });

  store.commit("rtc/setDeviceList", {
    cameraList: cameraItems,
    microphoneList: microphoneItems,
  });

  if (!videoDeviceId.value) {
    store.commit("rtc/setVideoDeviceId", cameraItems[0].deviceId);
  }

  if (!audioDeviceId.value) {
    store.commit("rtc/setAudioDeviceId", microphoneItems[0].deviceId);
  }
};

navigator.mediaDevices
  .getUserMedia({ audio: true, video: role.value == "customer" })
  .then((stream) => {
    stream.getTracks().forEach((track) => {
      track.stop();
    });
    updateDevice();
    emit("canUseDevice", true);
  })
  .catch((error) => {
    console.log(error,'error');
    Dialog.toast({ content: `请授权您的麦克风${role.value == "leader"?'和摄像头':''}权限`, type: "error" });
  });

navigator.mediaDevices.ondevicechange = updateDevice;

const handleDeviceChange = () => {
  emit("switchDevice", {
    videoId: store.videoDeviceId,
    audioId: store.audioDeviceId,
  });
};
</script>
