<script setup lang="ts">
import { fetchBaiduDigitalPeopleToken } from '@/apis/agent-application'
import { checkPlayUnMute } from '@/utils/check-play-unmute'
import type DHIframe from '@bddh/starling-dhiframe'
import { computed, onMounted, onUnmounted, ref, useTemplateRef, watch, watchEffect } from 'vue'
import { useI18n } from 'vue-i18n'

interface Props {
  agentId: string
  digitalhumanConfig: {
    appId: string
    figureId: string
    appKey: string
    enable: string
    timbreId: string
  }
  dhIframe: DHIframe
}

const props = defineProps<Props>()

const { t } = useI18n()
const digitalHumanIframeRef = useTemplateRef<HTMLIFrameElement>('digitalHumanIframeRef')

const token = ref('')
const digitalHumanLoading = ref(true)
const digitalHumanLoadError = ref(false)
const dhIframeMessageSubscription = ref(false)
const videoIsMuted = ref(false)
const serviceIsBusy = ref(false)
const serviceDisconnection = ref(false)
const showTimeoutTip = ref(false)

const iframeSrc = computed(() => {
  return `https://open.xiling.baidu.com/cloud/react?mode=inline&token=${token.value}&figureId=${props.digitalhumanConfig.figureId}&initMode=noAudio&showLogo=false&autoChromaKey=true&cameraId=0&resolutionWidth=1080&resolutionHeight=1920&cp-inactiveDisconnectSec=600&cp-autoAnimoji=true&cp-preAlertSec=10&textAssist=false&showMessage=false&debug=false`
})

const onDigitalHumanMessage = (msg: any) => {
  if (msg.origin === 'https://open.xiling.baidu.com') {
    const { type, content } = msg.data

    switch (type) {
      case 'rtcState':
        {
          const { action, body } = content

          if (action === 'remotevideoon' && body) {
            digitalHumanLoading.value = false
          }

          if (action === 'localVideoMuted' && body) {
            videoIsMuted.value = true
          }
        }
        break
      case 'msg': {
        const { action, code } = content

        if (action === 'DISCONNECT_ALERT') {
          showTimeoutTip.value = true
        } else if (action === 'TIMEOUT_EXIT') {
          digitalHumanIframeRef.value && digitalHumanIframeRef.value.remove()
          serviceDisconnection.value = true

          digitalHumanLoadError.value = true
        }

        if (code === 1004 || code === 3001) {
          serviceIsBusy.value = true
          digitalHumanLoadError.value = true
        }
        break
      }
      default:
        break
    }
  }
}

watchEffect(() => {
  if (props.agentId) {
    getBaiduDigitalPeopleToken(props.agentId)
  }
})

watch(
  () => props.dhIframe,
  (newDhIframe) => {
    if (newDhIframe && !dhIframeMessageSubscription.value) {
      newDhIframe.registerMessageReceived(onDigitalHumanMessage)

      dhIframeMessageSubscription.value = true
    }
  },
  { immediate: true },
)

onMounted(() => {
  checkPlayUnMute().then((res) => {
    videoIsMuted.value = !res
  })
})

onUnmounted(() => {
  props.dhIframe && props.dhIframe.removeMessageReceived(onDigitalHumanMessage)
})

function getBaiduDigitalPeopleToken(agentId: string) {
  fetchBaiduDigitalPeopleToken<string>(agentId).then((res) => {
    if (res.code !== 0) return null

    token.value = res.data
  })
}

// function handleUnmute() {
//   if (videoIsMuted.value) {
//     props.dhIframe?.sendCommand({
//       subType: 'muteAudio',
//       subContent: false,
//     })
//   }

//   videoIsMuted.value = false
// }
</script>

<template>
  <div class="relative flex h-full flex-1 items-end justify-center">
    <div class="relative h-[90%] w-[60%]">
      <div v-show="digitalHumanLoading" class="flex-center flex h-full w-full">
        <div class="flex -translate-y-full flex-col justify-center">
          <n-spin size="large" />
          <div class="mt-[20px]">{{ t('digital_human_module.digital_human_loading_tip') }}...</div>
        </div>
      </div>
      <iframe
        v-show="!digitalHumanLoading"
        id="digital-human-iframe"
        ref="digitalHumanIframeRef"
        class="h-full w-full"
        :src="iframeSrc"
        allow="autoplay"
      />

      <!-- <div
        v-if="!digitalHumanLoading && videoIsMuted && !digitalHumanLoadError"
        class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-pointer select-none text-[16px] text-[#e74c3c]"
        @click="handleUnmute"
      >
        取消静音
      </div> -->
    </div>

    <template v-if="digitalHumanLoadError">
      <div
        v-if="serviceIsBusy"
        class="absolute left-1/2 top-1/3 -translate-x-1/2 -translate-y-1/2 cursor-pointer select-none text-[16px] text-[#e74c3c]"
      >
        {{ t('digital_human_module.more_users_tip') }}
      </div>
      <div
        v-else-if="serviceDisconnection"
        class="absolute left-1/2 top-1/3 -translate-x-1/2 -translate-y-1/2 cursor-pointer select-none text-[16px] text-[#e74c3c]"
      >
        {{ t('digital_human_module.timed_out') }}
      </div>
    </template>
  </div>
</template>
