<script setup lang="ts">
import { computed, inject, onMounted, onUnmounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { Emitter } from 'mitt'
import { useI18n } from 'vue-i18n'
import { nanoid } from 'nanoid'
import { CloseSmall } from '@icon-park/vue-next'
import OverwriteMessageTipModal from './overwrite-message-tip-modal.vue'
import { fetchCustomEventSource } from '@/composables/useEventSource'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { UploadStatus } from '@/enums/upload-status'
import { useDialogueFile } from '@/composables/useDialogueFile'
import { TEXTTOSPEECH_WS_URL } from '@/config/base-url'
import WebSocketCtr from '@/utils/web-socket-ctr'
import { ChannelType } from '@/enums/channel'
import { useUserStore } from '@/store/modules/user'
import { smartFormTypeConverter } from '../components/smart-forms/utils/smart-forms'
import { SmartFormTypes } from '../../types'
import { SmartFormDisplayFormat } from './smart-forms/types/types'

interface Props {
  messageList: Map<string, ConversationMessageItem>
  continuousQuestionStatus: 'default' | 'close'
  answerAudioAutoPlay: boolean
  answerAudioPlaying: boolean
}

const { t } = useI18n()

const props = defineProps<Props>()

const emit = defineEmits<{
  addMessageItem: [messageId: string, value: ConversationMessageItem]
  updateSpecifyMessageItem: [messageId: string, newObj: Partial<ConversationMessageItem>]
  deleteMessageItem: [messageId: string]
  updatePageScroll: []
  clearAllMessage: []
  createContinueQuestions: [value: string]
  updateContinuousQuestionStatus: [value: 'default' | 'close']
  audioPlay: [messageItem: ConversationMessageItem, requestId?: string]
  audioPause: []
  smartFormsStatusFreezeCheck: [value: SmartFormTypes]
}>()

const personalAppConfigStore = usePersonalAppConfigStore()
const userStore = useUserStore()

const overwriteMessageTipOptions = reactive({
  title: '',
  content: '',
})

const { uploadFileList, handleLimitUpload, handleUpload, handleRemoveFile } = useDialogueFile()

const messageTipModalRef = useTemplateRef<InstanceType<typeof OverwriteMessageTipModal>>('messageTipModalRef')
const isAnswerResponseLoading = defineModel<boolean>('isAnswerResponseLoading', { required: true })

const emitter = inject<Emitter<MittEvents>>('emitter')

const inputMessageContent = ref('')
const isAnswerResponseWait = ref(false)
const currentReplyContentSentenceExtractIndex = ref(0)
const sentenceFragmentSerialNo = ref(0)
const sentenceExtractCheckEnabled = ref(false)
const assistantFullAnswerContent = ref('')
const currentAgentTimberId = ref('')
const sentenceSpeechException = ref(false)
const messageAudioLoading = ref(false)
const isSmartFormPlugins = ref(false) //  是否智能表单插件
const currentLatestMessageItemKeyMap = ref(new Map<'assistant' | 'user', string>())

let controller: AbortController | null = null

const agentId = computed(() => {
  return personalAppConfigStore.baseInfo.agentId
})

const isCreateContinueQuestions = computed(() => {
  return props.continuousQuestionStatus === 'default'
})

const isAllowClearMessage = computed(() => {
  return props.messageList.size > 0
})

const isSendBtnDisabled = computed(() => {
  return !inputMessageContent.value.trim()
})

const isInputMessageDisabled = computed(() => {
  return (
    uploadFileList.value.some((fileItem) => fileItem.status !== UploadStatus.FINISHED) ||
    !personalAppConfigStore.baseInfo.agentId
  )
})

const isEnableDocumentParse = computed(() => {
  return personalAppConfigStore.knowledgeConfig.isDocumentParsing === 'Y'
})

const isUploadFileDisabled = computed(() => {
  return uploadFileList.value.length === 1
})

// 上传文档列表
const uploadDocumentList = computed(() => {
  return uploadFileList.value.filter((fileItem) => fileItem.format === 'document')
})

// 上传图片列表
const uploadImageList = computed(() => {
  return uploadFileList.value.filter((fileItem) => fileItem.format === 'image')
})

const uploadFileIcon = (type: string) => {
  return `https://gsst-poe-sit.gz.bcebos.com/icon/${type}.svg`
}

watch(
  () => isEnableDocumentParse.value,
  () => {
    uploadFileList.value = []
  },
)

watch(
  () => uploadImageList.value.length,
  () => {
    emit('updatePageScroll')
  },
)

onUnmounted(() => {
  blockMessageResponse()
  emitter?.off('selectQuestion')
})

onMounted(() => {
  emitter?.on('selectQuestion', (featuredQuestion) => {
    inputMessageContent.value = featuredQuestion
    handleMessageSend()
  })
})

function messageItemFactory(): ConversationMessageItem {
  return {
    timestamp: Date.now(),
    role: 'user',
    textContent: '',
    isEmptyContent: false,
    isTextContentLoading: false,
    isAnswerResponseLoading: false,
    isVoiceLoading: false,
    isVoicePlaying: false,
    voiceFragmentUrlList: [],
    isVoiceEnabled: false,
    imageUrl: '',
    reasoningContent: '',
    modelName: '',
    knowledgeContentResult: [],
    dbChainSQLContent: '',
    pluginResult: {
      displayFormat: 'none',
      pluginName: '',
      pluginContent: '',
      arguments: '',
    },
  }
}

function handleInputMessageEnter(event: KeyboardEvent) {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleMessageSend()
  }
}

function handleMessageSend() {
  if (!inputMessageContent.value.trim() || isInputMessageDisabled.value) {
    return
  }

  if (isAnswerResponseWait.value || messageAudioLoading.value) {
    window.$message.warning(t('common_module.dialogue_module.do_not_operate_until_the_reply_is_complete'))
    return
  }

  if (props.answerAudioPlaying) {
    window.$message.warning(t('common_module.dialogue_module.stop_playing_and_then_operate'))
    return
  }

  const latestUserMessageKey = nanoid()
  const latestAssistantMessageKey = nanoid()
  currentLatestMessageItemKeyMap.value.set('user', latestUserMessageKey)
  currentLatestMessageItemKeyMap.value.set('assistant', latestAssistantMessageKey)

  const messages: {
    content: {
      type: string
      text: string
      image_url: {
        url: string
      }
    }[]
    role: string
  }[] = []

  emit('updateContinuousQuestionStatus', personalAppConfigStore.commConfig.continuousQuestionStatus)
  emit('addMessageItem', latestUserMessageKey, {
    ...messageItemFactory(),
    textContent: inputMessageContent.value,
    imageUrl: uploadImageList.value?.[0]?.url || '',
  })
  emit('updatePageScroll')

  props.messageList.forEach((messageItem) => {
    messages.push({
      content: [
        {
          type: 'text',
          text: messageItem.textContent,
          image_url: {
            url: '',
          },
        },
      ],
      role: messageItem.role,
    })
  })

  isAnswerResponseLoading.value = true
  isAnswerResponseWait.value = true

  currentReplyContentSentenceExtractIndex.value = 0
  sentenceFragmentSerialNo.value = 0
  sentenceExtractCheckEnabled.value = false
  assistantFullAnswerContent.value = ''
  currentAgentTimberId.value = personalAppConfigStore.voiceConfig.timbreId
  sentenceSpeechException.value = false
  messageAudioLoading.value = false
  isSmartFormPlugins.value = false

  const isVoiceEnabled = !!personalAppConfigStore.voiceConfig.timbreId

  emit('addMessageItem', latestAssistantMessageKey, {
    ...messageItemFactory(),
    role: 'assistant',
    isTextContentLoading: true,
    isAnswerResponseLoading: true,
    isVoiceLoading: true,
    isVoiceEnabled,
    modelName: personalAppConfigStore.commModelConfig.largeModel || '',
  })
  emit('updatePageScroll')

  let replyTextContent = ''
  let reasoningContent = ''

  controller = new AbortController()

  fetchCustomEventSource({
    path: '/api/rest/agentApplicationInfoRest/preview.json',
    payload: {
      agentId: agentId.value,
      fileUrls: uploadFileList.value.map((item) => item.url),
      channel: ChannelType.preview,
      messages,
    },
    controller,
    onResponse: (data) => {
      // 推理内容
      if (data.reasoningContent) {
        reasoningContent += data.reasoningContent
        emit('updateSpecifyMessageItem', latestAssistantMessageKey, { reasoningContent: reasoningContent })
        emit('updatePageScroll')
      }

      // 插件
      if (data.function && data.function.name) {
        // 表单插件，展示表单内容
        if (['travelForm'].includes(data.function.displayFormat)) {
          emit(
            'smartFormsStatusFreezeCheck',
            smartFormTypeConverter(data.function.displayFormat as SmartFormDisplayFormat),
          )

          emit('updateSpecifyMessageItem', latestAssistantMessageKey, {
            pluginResult: {
              displayFormat: data.function.displayFormat,
              pluginName: data.function.name,
              arguments: data.function.arguments,
              pluginContent: data.function.result,
            },
            smartFormInfo: {
              type: smartFormTypeConverter(data.function.displayFormat as SmartFormDisplayFormat),
              isDisabled: false,
              params: data.function.result,
            },
          })
          emit('updatePageScroll')
          isSmartFormPlugins.value = true
          return
        }

        emit('updateSpecifyMessageItem', latestAssistantMessageKey, {
          pluginResult: {
            displayFormat: data.function.displayFormat,
            pluginName: data.function.name,
            pluginContent: data.function.result,
            arguments: data.function.arguments,
          },
        })
        emit('updatePageScroll')
      }

      // 数据库
      if (data.dbChainResult && data.dbChainResult?.[0]) {
        emit('updateSpecifyMessageItem', latestAssistantMessageKey, {
          dbChainSQLContent: data.dbChainResult?.[0]?.sql || '',
        })
        return
      }

      // 知识库
      if (data.knowledgeContentResult) {
        emit('updateSpecifyMessageItem', latestAssistantMessageKey, {
          knowledgeContentResult: data.knowledgeContentResult,
        })
        return
      }

      // 回复消息
      if (data.message) {
        replyTextContent += data.message

        emit('updateSpecifyMessageItem', latestAssistantMessageKey, {
          textContent: replyTextContent,
          isTextContentLoading: false,
        })
        emit('updatePageScroll')

        assistantFullAnswerContent.value = (assistantFullAnswerContent.value + data.message).replace(
          /\^\[[\d\\[\]-]+?\]\^/g,
          '',
        )

        if (!sentenceExtractCheckEnabled.value && isVoiceEnabled && !isSmartFormPlugins.value) {
          sentenceExtract(latestAssistantMessageKey)
          sentenceExtractCheckEnabled.value = true
          messageAudioLoading.value = true
        }
      }
    },
    onRequestError: () => {
      errorMessageResponse()
    },
    onError: () => {
      errorMessageResponse()
    },
    onFinally: () => {
      emit('updateSpecifyMessageItem', latestAssistantMessageKey, {
        isEmptyContent: !replyTextContent,
        isTextContentLoading: false,
        isAnswerResponseLoading: false,
      })
      isAnswerResponseLoading.value = false
      isCreateContinueQuestions.value && emit('createContinueQuestions', replyTextContent)
      emit('updatePageScroll')
      isAnswerResponseWait.value = false
      controller = null
      userStore.fetchUpdateEquityInfo()
    },
  })

  inputMessageContent.value = ''
  uploadFileList.value = uploadFileList.value.filter((item) => item.format === 'document')
}

function errorMessageResponse() {
  emit('updateSpecifyMessageItem', currentLatestMessageItemKeyMap.value.get('assistant')!, {
    isTextContentLoading: false,
    textContent: '',
  })
  emit('deleteMessageItem', currentLatestMessageItemKeyMap.value.get('user')!)
  emit('deleteMessageItem', currentLatestMessageItemKeyMap.value.get('assistant')!)
  emit('audioPause')
  blockMessageResponse()
}

function handleClearAllMessage() {
  if (!isAllowClearMessage.value) return

  emit('clearAllMessage')
}

function blockMessageResponse() {
  controller?.abort()
  isAnswerResponseWait.value = false
  messageAudioLoading.value = false
  userStore.fetchUpdateEquityInfo()
}

function handleSelectFile(cb: () => void) {
  if (isUploadFileDisabled.value) {
    overwriteMessageTipOptions.title = t('common_module.dialogue_module.overwrite_file_tip')

    messageTipModalRef.value?.handleShowModal().then(() => {
      cb()
    })
    return
  }

  cb()
}

function sentenceExtract(messageId: string) {
  const symbolRegExp = /[。！？；.!?;~]/g
  let sentenceDraft = assistantFullAnswerContent.value
    .replace(/\s{5,}/gi, '')
    .slice(currentReplyContentSentenceExtractIndex.value)

  let matchResult = symbolRegExp.exec(sentenceDraft)

  function matchExtract() {
    const article = assistantFullAnswerContent.value.replace(/\s{5,}/gi, '')

    if (matchResult && matchResult.index && matchResult.index > 60) {
      sentenceDraft = article.slice(
        currentReplyContentSentenceExtractIndex.value,
        currentReplyContentSentenceExtractIndex.value + matchResult.index + matchResult['0'].length,
      )

      currentReplyContentSentenceExtractIndex.value += sentenceDraft.length

      ttsSocketSendText(sentenceDraft, sentenceFragmentSerialNo.value, messageId)
      sentenceFragmentSerialNo.value += 1

      if (article.length - currentReplyContentSentenceExtractIndex.value > 60) {
        sentenceDraft = article.slice(currentReplyContentSentenceExtractIndex.value)
        matchResult = symbolRegExp.exec(sentenceDraft)
        matchExtract()
      } else {
        setTimeout(() => sentenceExtract(messageId), 600)
      }
    } else if (!isAnswerResponseWait.value) {
      /* 延时避免最后回复内容没有更新全 */
      setTimeout(() => {
        sentenceDraft = article.slice(currentReplyContentSentenceExtractIndex.value)

        ttsSocketSendText(sentenceDraft, sentenceFragmentSerialNo.value, messageId)
        sentenceFragmentSerialNo.value += 1
      }, 700)
    } else {
      sentenceDraft = assistantFullAnswerContent.value
        .replace(/\s{5,}/gi, '')
        .slice(currentReplyContentSentenceExtractIndex.value)
      matchResult = symbolRegExp.exec(sentenceDraft)

      setTimeout(() => matchExtract(), 500)
    }
  }

  if (matchResult) matchExtract()
  else if (!isAnswerResponseWait.value) matchExtract()
  else setTimeout(() => sentenceExtract(messageId), 600)
}

function ttsSocketSendText(text: string, audioUrlSerialNo: number, messageId: string) {
  if (sentenceSpeechException.value) {
    return
  }

  const ttsSocketCtl = new WebSocketCtr(TEXTTOSPEECH_WS_URL)

  ttsSocketCtl.onMessage = (data: { audio: string; replyVoiceUrl: string; final: boolean }) => {
    if (data.replyVoiceUrl) {
      if (props.messageList.get(messageId)?.voiceFragmentUrlList) {
        const voiceFragmentUrlListDraft = [...props.messageList.get(messageId)!.voiceFragmentUrlList]
        voiceFragmentUrlListDraft[audioUrlSerialNo] = data.replyVoiceUrl
        messageAudioLoading.value = false

        emit('updateSpecifyMessageItem', messageId, { voiceFragmentUrlList: voiceFragmentUrlListDraft })

        if (props.answerAudioAutoPlay && audioUrlSerialNo === 0 && voiceFragmentUrlListDraft[audioUrlSerialNo]) {
          emit('audioPlay', props.messageList.get(messageId)!)
        }

        if (!props.answerAudioAutoPlay) {
          emit('updateSpecifyMessageItem', messageId, { isVoiceLoading: false })
        }
      }
    }
  }

  ttsSocketCtl.onMessageError = () => {
    emit('updateSpecifyMessageItem', messageId, { isVoiceLoading: false, voiceFragmentUrlList: [] })
    props.messageList.get(messageId)?.isVoicePlaying && emit('audioPause')
    sentenceSpeechException.value = true
    messageAudioLoading.value = false
    window.$message.error(t('common_module.unplayable_tip'))
  }

  const content = (text || '').replace(/\^\[[\d\\[\]-]+?\]\^/g, '')

  if (content && currentAgentTimberId.value) {
    ttsSocketCtl.connect(() => {
      ttsSocketCtl.send({
        codec: 'wav',
        sampleRate: 16000,
        speed: 0,
        voiceType: currentAgentTimberId.value,
        volume: 0,
        content,
      })
    })
  }
}

defineExpose({
  blockMessageResponse,
})
</script>

<template>
  <div class="mb-3 mt-5 px-5">
    <div class="flex items-end gap-2.5">
      <div class="flex-1">
        <div class="mb-1.5 flex gap-[14px]">
          <div
            v-for="uploadImageItem in uploadImageList"
            :key="uploadImageItem.id"
            class="border-inactive-border-color relative h-[66px] w-[66px] rounded-[10px] border bg-white"
            :class="{ 'border-[#F25744]!': uploadImageItem.status === UploadStatus.ERROR }"
          >
            <div
              class="absolute right-[-4px] top-[-4px] flex h-4 w-4 cursor-pointer items-center justify-center rounded-full bg-[rgba(0,0,0,0.55)] hover:opacity-80"
              @click="handleRemoveFile(uploadImageItem.id)"
            >
              <CloseSmall theme="outline" size="16" fill="#fff" />
            </div>

            <div class="flex h-full w-full items-center justify-center overflow-hidden rounded-[10px]">
              <n-spin v-show="uploadImageItem.status === UploadStatus.UPLOADING" :size="20" />

              <n-image
                v-show="uploadImageItem.status === UploadStatus.FINISHED"
                object-fit="contain"
                :src="uploadImageItem.url"
                preview-disabled
                class="h-full w-full flex-shrink-0"
              />
            </div>
          </div>
        </div>

        <ul v-show="uploadDocumentList.length > 0" class="mb-1.5 grid gap-1.5">
          <li
            v-for="uploadDocumentItem in uploadDocumentList"
            :key="uploadDocumentItem.id"
            class="group relative flex h-[42px] w-full items-center overflow-hidden rounded-[10px] border bg-white/70"
            :class="uploadDocumentItem.status === 'error' ? 'border-error-font-color' : 'border-transparent'"
          >
            <div class="flex w-full items-center justify-between px-3.5">
              <div class="flex w-full items-center overflow-hidden">
                <img :src="uploadFileIcon(uploadDocumentItem.type!)" class="h-7 w-7" />

                <div class="mx-2.5 flex flex-1 flex-col overflow-hidden">
                  <n-ellipsis>
                    {{ uploadDocumentItem.name }}
                  </n-ellipsis>
                </div>
              </div>

              <n-progress
                v-show="!['finished', 'error'].includes(uploadDocumentItem.status)"
                class="left-13.5 w-[calc(100%-78px)]! absolute bottom-0"
                type="line"
                rail-color="#F3F3F3"
                :height="4"
                :percentage="uploadDocumentItem.percentage"
                :show-indicator="false"
              />

              <div v-show="['finished', 'error'].includes(uploadDocumentItem.status)" class="hidden group-hover:block">
                <n-popover trigger="hover" placement="top-end" :show-arrow="false">
                  <template #trigger>
                    <i
                      class="iconfont icon-close cursor-pointer hover:opacity-80"
                      :class="uploadDocumentItem.status === 'error' ? 'text-error-font-color' : 'text-font-color'"
                      @click="handleRemoveFile(uploadDocumentItem.id)"
                    />
                  </template>
                  <span>{{ t('common_module.dialogue_module.cancel_associate_file_tip') }}</span>
                </n-popover>
              </div>
            </div>
          </li>
        </ul>

        <div class="relative flex-1">
          <n-input
            v-model:value="inputMessageContent"
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 5 }"
            :placeholder="t('common_module.dialogue_module.question_input_placeholder')"
            :disabled="isInputMessageDisabled"
            class="rounded-xl! shadow-[0_1px_#09122105,0_1px_1px_#09122105,0_3px_3px_#09122103,0_9px_9px_#09122103]! py-[4px] pr-[50px]"
            @keydown="handleInputMessageEnter"
          />

          <div
            class="bg-px-send-png absolute bottom-2 right-[20px] h-[24px] w-[24px]"
            :class="
              isSendBtnDisabled ||
              isAnswerResponseWait ||
              isInputMessageDisabled ||
              answerAudioPlaying ||
              messageAudioLoading
                ? 'opacity-60'
                : 'cursor-pointer'
            "
            @click="handleMessageSend"
          />
        </div>
      </div>

      <n-upload
        :show-file-list="false"
        accept=".doc, .pdf, .docx, .txt, .md, image/png, image/jpeg, image/jpg, image/webp"
        abstract
        @before-upload="handleLimitUpload"
        @change="handleUpload"
      >
        <n-upload-trigger #="{ handleClick }" abstract>
          <n-popover style="width: 210px" trigger="hover">
            <template #trigger>
              <div
                v-show="isEnableDocumentParse"
                class="h-7.5 w-7.5 hover:text-theme-color text-font-color mb-1 flex cursor-pointer items-center justify-center rounded-full bg-white"
                @click="handleSelectFile(handleClick)"
              >
                <i class="iconfont icon-upload flex h-4 w-4 items-center justify-center" />
              </div>
            </template>

            <span class="text-xs"> {{ t('common_module.dialogue_module.upload_file_limit') }} </span>
          </n-popover>
        </n-upload-trigger>
      </n-upload>

      <n-popover trigger="hover">
        <template #trigger>
          <div
            class="h-7.5 w-7.5 mb-1 flex cursor-pointer items-center justify-center rounded-full bg-white"
            @click="handleClearAllMessage"
          >
            <i
              class="iconfont icon-clear text-base leading-none"
              :class="
                isAllowClearMessage ? 'hover:text-theme-color text-font-color' : 'cursor-not-allowed text-[#b8babf]'
              "
            />
          </div>
        </template>
        <span class="text-xs">
          {{ t('common_module.dialogue_module.clear_message_popover_message') }}
        </span>
      </n-popover>
    </div>

    <div class="mt-[9px] pl-2">
      <span class="text-xs text-[#84868c]">
        {{ t('common_module.dialogue_module.generate_warning_message') }}
      </span>
    </div>
  </div>

  <OverwriteMessageTipModal ref="messageTipModalRef" :modal-options="overwriteMessageTipOptions" />
</template>
