<script setup lang="ts">
import { computed, provide, readonly, useTemplateRef } from 'vue'
import { CheckOne } from '@icon-park/vue-next'
import type { MessageItemInterface } from '../types'
import { useUserStore } from '@/store/modules/user'
import MessageBubbleLoading from './message-bubble-loading.vue'
import { useI18n } from 'vue-i18n'
import { copyToClip } from '@/utils/copy'
import { throttle } from 'lodash-es'
import MarkdownRender from '@/components/markdown-render/markdown-render.vue'
// import ExecuteCodeRender from '@/components/execute-code-render/execute-code-render.vue'
import SmartForms from './smart-forms/index.vue'
import AuthorInfo from './author-info.vue'

interface Props {
  messageItem: MessageItemInterface
  messageItemId: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  contentedit: [content: string]
}>()

const { t } = useI18n()
const userStore = useUserStore()

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

provide('messageItemId', props.messageItemId)

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

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

const avatarUrl = computed(() => {
  return isAgentMessage.value ? props.messageItem.avatar || agentDefaultAvatarUrl.url : userStore.userInfo.avatarUrl
})

const messageAuthor = computed(() => {
  return isAgentMessage.value ? props.messageItem.name || 'AI助理' : userStore.userInfo.nickName
})

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

const handleContentCopy = throttle(
  () => {
    copyToClip(props.messageItem.content).then(() => {
      window.$message.success(t('common_module.copy_success_message'))
    })
  },
  1000,
  { leading: true, trailing: false },
)

const handleContentEdit = throttle(
  () => {
    if (markdownRenderRef.value) {
      const content = markdownRenderRef.value.getRenderTextContent()

      emit('contentedit', content)
    }
  },
  1000,
  { leading: true, trailing: false },
)
</script>

<template>
  <div class="mb-[20px] last:mb-0">
    <div class="flex">
      <img class="h-[36px] w-[36px] rounded-[6px] object-cover" :src="avatarUrl" alt="Avatar" />

      <div v-if="true" class="ml-[11px] overflow-hidden">
        <AuthorInfo :is-agent-message="isAgentMessage" :message-item="messageItem" :message-author="messageAuthor" />

        <div
          class="box-content min-h-[21px] min-w-[10px] max-w-full rounded-[10px] border border-[#9EA3FF] bg-[#777EF9] px-[15px] py-[14px] text-justify"
          :class="{
            '!bg-[#fff]': isAgentMessage,
            '!min-w-[80px]': messageItem.isAnswerLoading,
          }"
        >
          <img
            v-show="!isAgentMessage && messageItem.imageUrl"
            :src="messageItem.imageUrl"
            class="max-h-[120px]! mb-[14px] rounded-[10px] object-contain"
          />
          <div
            v-if="messageItem.isAnswerLoading && !messageItem.content"
            class="flex h-[21px] items-center justify-center"
          >
            <MessageBubbleLoading :active-color="currentBubbleTextColor" />
          </div>
          <template v-else>
            <!-- <ExecuteCodeRender
              title="数据库问答执行成功"
              :raw-text-content="`\`\`\`SQL\nSELECT type, channel, total_points, usage_count, users_count, data_date SELECT type, channel, total_points, usage_count, users_count, data_date SELECT type, channel, total_points, usage_count, users_count, data_date SELECT type, channel, total_points, usage_count, users_count, data_date \`\`\``"
            /> -->

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

            <div v-if="messageItem.isAnswerLoading" class="ml-[15px] pt-[12px]">
              <MessageBubbleLoading active-color="#fff" width="5px" />
            </div>
          </template>
        </div>

        <div
          v-show="isAgentMessage && messageItem.content && !messageItem.isAnswerLoading"
          class="py-[10px] pr-[14px] text-end"
        >
          <i
            class="iconfont icon-fuzhi hover:text-theme-color mr-[14px] transform cursor-pointer text-[14px]"
            @click="handleContentCopy"
          ></i>
          <i
            class="iconfont icon-edit-document hover:text-theme-color transform cursor-pointer text-[14px]"
            @click="handleContentEdit"
          ></i>
        </div>

        <div
          v-show="isAgentMessage && messageItem.pluginName"
          class="mt-[7px] flex items-center gap-[5px] font-['Microsoft_YaHei_UI'] text-[#999]"
        >
          <div
            v-show="!messageItem.content"
            class="bg-px-plugin_loading-gif h-[14px] w-[14px] bg-contain bg-center bg-no-repeat"
          />
          <CheckOne v-show="messageItem.content" theme="outline" size="16" fill="#40bd23" />

          <span class="leading-5">
            {{
              !messageItem.content
                ? t('common_module.plugin_in_progress', { pluginName: messageItem.pluginName })
                : t('common_module.plugin_executed_successfully', { pluginName: messageItem.pluginName })
            }}
          </span>
        </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: #192338 !important;
  }
}
</style>
