<template>
  <div :class="remoteClass" v-show="item.isVideoAvailable">
    <TRTCPlayer
      :id="playRegionDomId"
      ref="player"
      :stream-id="playRegionDomId"
      class="stream"
    />
  </div>
</template>

<script lang="ts">
export default {
  options: {
    virtualHost: true,
  },
};
</script>

<script lang="ts" setup>
import { onMounted, ref, onUnmounted, computed, watch } from '../../../../../adapter-vue';
import { TUICallKitServer, StoreName, NAME, TUIStore, AudioPlayBackDevice } from '../../../../../TUICallService/index';
import TRTCPlayer from '@tencentcloud/trtc-component-uniapp/src/components/TRTCPlayer.vue';

const player = ref();

const playerList = ref(TUIStore.getData(StoreName.CALL, NAME.PLAYER));
const remoteUserInfoList = ref(TUIStore.getData(StoreName.CALL, NAME.REMOTE_USER_INFO_LIST));
const callStatus = ref(TUIStore.getData(StoreName.CALL, NAME.CALL_STATUS));
const soundMode = ref(TUIStore.getData(StoreName.CALL, NAME.IS_EAR_PHONE) ? AudioPlayBackDevice.EAR : AudioPlayBackDevice.SPEAKER);
const props = defineProps({
  remoteClass: {
    type: String,
    required: true,
  },
  domId: {
    type: String,
  },
});

const handlePlayerListChange = (value) => {
  playerList.value = JSON.parse(JSON.stringify(value));
};

const handleRemoteUserInfoListChange = (value) => {
  remoteUserInfoList.value = JSON.parse(JSON.stringify(value));
};


const item = computed(() => remoteUserInfoList.value?.find((remoteUser) => remoteUser?.userId === props.domId));

const playRegionDomId = computed(() => `${item.value.userId}_0`);

const handleCallStatusChange = (value) => {
  callStatus.value = value;
};

const handEarPhoneChange = (value) => {
  soundMode.value = value ? AudioPlayBackDevice.EAR : AudioPlayBackDevice.SPEAKER;
};

const watchOptions = {
  [NAME.PLAYER]: handlePlayerListChange,
  [NAME.REMOTE_USER_INFO_LIST]: handleRemoteUserInfoListChange,
  [NAME.CALL_STATUS]: handleCallStatusChange,
  [NAME.IS_EAR_PHONE]: handEarPhoneChange,
};

onMounted(() => {
  TUIStore.watch(StoreName.CALL, watchOptions, { notifyRangeWhenWatch: NAME.MYSELF });
  watch(() => props.domId, async(val) => {
    if(val) {
      await player.value.setTRTCStreamId(playRegionDomId.value);
    }
  }, {
    immediate: true
  })
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CALL, watchOptions);
});

function playerStateChange(e: any) {
  TUICallKitServer._tuiCallEngine._playerStateChange(e);
}

function playerFullscreenChange(e: any) {
  // TUICallKitServer._tuiCallEngine._playNetStatus(e);
}

function playNetStatus(e: any) {
  TUICallKitServer._tuiCallEngine._playNetStatus(e);
}

function playerAudioVolumeNotify(e: any) {
  TUICallKitServer._tuiCallEngine._playerAudioVolumeNotify(e);
}
</script>

<style lang="scss" src="./style/index.scss" scoped></style>
