<script setup lang="ts">
import { computed, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { CheckOne, Down } from '@icon-park/vue-next'
import CustomLoading from '../custom-loading.vue'
import MusicWavesLoading from '../music-waves-loading.vue'
import MarkdownRender from '@/components/markdown-render/markdown-render.vue'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'

interface Props {
  role: 'user' | 'assistant'
  messageItem: ConversationMessageItem
  agentApplicationConfig: PersonalAppConfigState
}

const { t } = useI18n()

const props = defineProps<Props>()

const emit = defineEmits<{
  audioPlay: []
  audioPause: []
}>()

const markdownRenderRef = useTemplateRef<InstanceType<typeof MarkdownRender>>('markdownRenderRef')

const isShowReasoningContent = ref(true)

const timbreEnabled = computed(() => {
  return !!props.agentApplicationConfig.voiceConfig.timbreId
})

const isShowAudioControl = computed(() => {
  return props.role === 'assistant' && !props.messageItem.isVoiceLoading && timbreEnabled.value
})

const isPlayableAudio = computed(() => {
  return isShowAudioControl.value && !!props.messageItem.voiceFragmentUrlList.length
})

const isShowVoiceLoading = computed(() => {
  return (
    props.role === 'assistant' &&
    (props.messageItem.isAnswerResponseLoading || (props.messageItem.isVoiceLoading && timbreEnabled.value))
  )
})

const isDeepSeekR1 = computed(() => {
  return props.agentApplicationConfig.commModelConfig.largeModel === 'DeepSeek'
})

function handleAudioControl() {
  if (!isPlayableAudio.value) {
    return
  }

  if (props.messageItem.isVoicePlaying) {
    emit('audioPause')
  } else {
    emit('audioPlay')
  }
}

function handleShowReasoningContentSwitch() {
  isShowReasoningContent.value = !isShowReasoningContent.value
}
</script>

<template>
  <div
    class="mb-[15px] flex flex-row-reverse last:mb-0"
    :class="[role === 'assistant' ? 'justify-end' : 'justify-start']"
  >
    <div class="flex w-full flex-col overflow-x-auto" :class="[role === 'user' ? 'items-end' : 'items-start']">
      <!-- 大模型深度思考 -->
      <template v-if="role === 'assistant' && isDeepSeekR1">
        <div class="my-[7px] select-none text-[12px]">
          <div class="inline-flex cursor-pointer" @click="handleShowReasoningContentSwitch">
            <span v-if="messageItem.isTextContentLoading" class="mr-[6px]">
              {{ t('common_module.deep_thinking', { modelName: agentApplicationConfig.commModelConfig.largeModel }) }}
            </span>
            <span v-else class="mr-[6px]">
              {{ t('common_module.have_thought_deeply') }}
            </span>
            <Down
              theme="outline"
              :size="18"
              fill="#333"
              :stroke-width="3"
              class="transition-[rotate] duration-100 ease-linear"
              :class="{ '-rotate-180': isShowReasoningContent }"
            />
          </div>
        </div>

        <n-collapse-transition :show="isShowReasoningContent">
          <div
            v-if="messageItem.reasoningContent"
            class="my-[10px] border-l-[1px] border-solid border-l-[#ccc] px-[13px] py-[8px]"
          >
            <MarkdownRender
              ref="markdownRenderRef"
              :raw-text-content="
                messageItem.reasoningContent
                  ? messageItem.reasoningContent
                  : t('common_module.dialogue_module.empty_message_content')
              "
              color="#999"
              :font-size="'12px'"
            />
          </div>
        </n-collapse-transition>
      </template>

      <!-- 模型内容 -->
      <div class="flex min-w-[80px] max-w-full flex-col">
        <div
          class="w-full flex-wrap rounded-xl border px-4 px-[12px] py-[11px]"
          :class="[
            { 'rounded-tr-none border-[#DCDEFF] bg-[#DCDEFF] text-white': role === 'user' },
            { 'rounded-tl-none border-[#e8e9eb] bg-white text-[#333]': role === 'assistant' },
          ]"
        >
          <img
            v-show="role === 'user' && messageItem.imageUrl"
            :src="messageItem.imageUrl"
            class="max-h-[120px]! mb-[11px] rounded-[10px] object-contain"
          />

          <div
            v-show="role === 'assistant' && messageItem.pluginName"
            class="mb-[8px] flex items-center gap-[5px] font-['Microsoft_YaHei_UI'] text-[#999]"
          >
            <div
              v-show="messageItem.isTextContentLoading"
              class="bg-px-plugin_loading-gif h-[14px] w-[14px] bg-contain bg-center bg-no-repeat"
            />
            <CheckOne v-show="!messageItem.isTextContentLoading" theme="outline" :class="'14'" fill="#40bd23" />

            <span class="text-[12px] leading-5">
              {{
                messageItem.isTextContentLoading
                  ? t('common_module.plugin_in_progress', { pluginName: messageItem.pluginName })
                  : t('common_module.plugin_executed_successfully', { pluginName: messageItem.pluginName })
              }}
            </span>
          </div>

          <div v-if="messageItem.isTextContentLoading" class="py-1.5 pl-4">
            <CustomLoading :active-color="'#000DFF'" />
          </div>

          <div v-else>
            <p class="break-all">
              <MarkdownRender
                ref="markdownRenderRef"
                :raw-text-content="
                  messageItem.isEmptyContent
                    ? t('common_module.dialogue_module.empty_message_content')
                    : messageItem.textContent
                "
                :color="'#333'"
                :font-size="'12px'"
              />
            </p>

            <div v-show="isShowVoiceLoading || messageItem.isAnswerResponseLoading" class="mb-[5px] mt-4 px-4">
              <CustomLoading :active-color="'#000DFF'" />
            </div>
          </div>

          <!-- 移动端语音播放 -->
          <div v-show="isShowAudioControl" class="mt-[13px] flex items-center gap-2">
            <div
              class="h-[18px] w-[18px] cursor-pointer"
              :class="messageItem.isVoicePlaying ? 'bg-svg-pause' : 'bg-svg-play'"
              @click="handleAudioControl"
            />

            <MusicWavesLoading v-show="messageItem.isVoicePlaying && isPlayableAudio" bar-bg-color="#333" />

            <n-popover style="max-width: 310px">
              <template #trigger>
                <span v-show="!isPlayableAudio" class="text-[12px]"> {{ t('common_module.unplayable') }} </span>
              </template>
              {{ t('common_module.unplayable_tip') }}
            </n-popover>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
