<script setup lang="ts">
import { computed, provide, readonly, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Down } from '@icon-park/vue-next'
import type { MessageItemInterface } from '../types'
import MarkdownRender from '@/components/markdown-render/markdown-render.vue'
import ExecuteCodeRender from '@/components/execute-code-render/execute-code-render.vue'
import ExecutePluginRender from '@/components/execute-plugin-render/execute-plugin-render.vue'
import MessageBubbleLoading from './message-bubble-loading.vue'
import SmartForms from './smart-forms/index.vue'

interface Props {
  messageItem: MessageItemInterface
  messageItemId: string
}

const props = defineProps<Props>()

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

const { t } = useI18n()

provide('messageItemId', props.messageItemId)

const isShowReasoningContent = ref(true)

const agentAvatarUrl = readonly({ url: 'https://gsst-poe-sit.gz.bcebos.com/icon/agent-avatar.png' })

const displaySmartFormsList = readonly(['travelForm'])

const isAgentMessage = computed(() => {
  return props.messageItem.role === 'assistant'
})

const currentBubbleTextColor = computed(() => {
  return isAgentMessage.value ? '#192338' : '#fff'
})

const messageAuthor = computed(() => {
  return props.messageItem.nickName
})

const isShowSmartForms = computed(() => {
  if (props.messageItem?.pluginResult?.displayFormat) {
    return displaySmartFormsList.includes(props.messageItem?.pluginResult?.displayFormat)
  }
  return false
})

const assistantAvatarUrl = computed(() => {
  return props.messageItem.avatar || agentAvatarUrl.url
})

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

<template>
  <div class="mb-[20px] last:mb-0">
    <div class="flex">
      <img
        class="h-[36px] w-[36px] flex-shrink-0 rounded-full object-cover"
        :src="isAgentMessage ? assistantAvatarUrl : props.messageItem.avatar"
        alt="Avatar"
      />

      <div v-if="!isShowSmartForms" class="ml-[11px] flex flex-col items-start overflow-hidden">
        <!-- DeepSeek深度思考 -->
        <template v-if="isAgentMessage && messageItem.nickName === 'DeepSeek'">
          <div class="mb-[7px] select-none text-[14px]">
            <div class="inline-flex cursor-pointer" @click="handleShowReasoningContentSwitch">
              <span v-if="messageItem.isTextContentLoading" class="mr-[6px]">
                {{ t('common_module.deep_thinking', { modelName: messageItem.nickName }) }}
              </span>
              <span v-else class="mr-[6px]">{{ t('common_module.have_thought_deeply') }}</span>
              <Down
                theme="outline"
                size="21"
                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-show="messageItem.reasoningContent"
              class="my-[14px] border-l-[1px] border-solid border-l-[#ccc] p-[13px]"
            >
              <MarkdownRender
                :raw-text-content="
                  messageItem.reasoningContent
                    ? messageItem.reasoningContent
                    : t('common_module.dialogue_module.empty_message_content')
                "
                color="#999"
              />
            </div>
          </n-collapse-transition>
        </template>
        <div v-else class="mb-[7px] line-clamp-1 break-all text-[12px] text-[#999]">
          {{ props.messageItem.nickName }}
        </div>

        <div class="flex min-w-[40px] max-w-full flex-col items-start overflow-hidden">
          <div
            class="min-h-[21px] w-full flex-wrap rounded-[10px] border border-[#9EA3FF] px-[15px] py-[12px] text-justify"
            :class="{
              'bg-[#777EF9]': !isAgentMessage,
              'text-[#fff]': !isAgentMessage,
              '!min-w-[80px]': messageItem.isTextContentLoading,
            }"
          >
            <img
              v-show="!isAgentMessage && messageItem.imageUrl"
              :src="messageItem.imageUrl"
              class="max-h-[120px]! mb-[12px] rounded-[10px] object-contain"
            />

            <!-- 插件返回结果 -->
            <div v-show="isAgentMessage && messageItem?.pluginResult?.pluginName" class="mb-[11px] w-full">
              <ExecutePluginRender
                :display-format="messageItem.pluginResult?.displayFormat || 'none'"
                :name="messageItem.pluginResult?.pluginName!"
                :content="messageItem.pluginResult?.pluginContent!"
                :arguments="messageItem.pluginResult?.arguments!"
                :plugin-loading="messageItem.isTextContentLoading"
              />
            </div>

            <div v-if="messageItem.isTextContentLoading" class="flex px-4 py-[7.5px]">
              <MessageBubbleLoading :active-color="currentBubbleTextColor" />
            </div>

            <div v-else>
              <!-- 数据库问答结果 -->
              <div v-show="messageItem.dbChainSQLContent" class="mb-[10px] w-full">
                <ExecuteCodeRender
                  :title="t('common_module.database_QA_executed_successfully')"
                  :raw-text-content="messageItem.dbChainSQLContent"
                />
              </div>

              <MarkdownRender
                :raw-text-content="
                  messageItem.content ? messageItem.content : t('common_module.dialogue_module.empty_message_content')
                "
                :color="currentBubbleTextColor"
              />

              <div
                v-show="isAgentMessage && messageItem.isAnswerResponseLoading"
                class="mt-2.5 flex h-[21px] w-[30px] items-center justify-center"
              >
                <MessageBubbleLoading :active-color="currentBubbleTextColor" />
              </div>
            </div>
          </div>

          <div class="flex justify-between py-[2px]">
            <div
              v-show="isAgentMessage && messageItem.knowledgeContentResult.length"
              class="flex-center rounded-theme h-8 cursor-pointer gap-[5px] px-[14px] font-['Microsoft_YaHei_UI'] text-[#0B7DFF] hover:opacity-80"
              @click="emit('showKnowledgeResult')"
            >
              <i class="iconfont icon-knowledge" />
              <span>{{ t('common_module.knowledge') }}</span>
            </div>
          </div>
        </div>
      </div>

      <SmartForms
        v-else
        :message-item="messageItem"
        :message-author="messageAuthor"
        :is-agent-message="isAgentMessage"
        :current-bubble-text-color="currentBubbleTextColor"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.markdown-render-container .markdown-render-inner) {
  table {
    color: #fff !important;
  }
}
</style>
