<script setup lang="ts">
import { computed, h, nextTick, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { SelectOption } from 'naive-ui'
import { useVModel } from '@vueuse/core'
import { useElementSize } from '@vueuse/core'
import { useSystemLanguageStore } from '@/store/modules/system-language'
import { MultiModelDialogueItem, MessageItemInterface } from '../types'
import ModelSetting from './model-setting.vue'
import MessageList from './message-list.vue'
import HitKnowledgeContent from './hit-knowledge-content.vue'

interface Props {
  modelDialogueItem: MultiModelDialogueItem
  modelListOptions: SelectOption[]
  totalNum: number
  isCurrent: boolean
  modelDialogueId: number
}

const { t } = useI18n()

const props = defineProps<Props>()

const emit = defineEmits<{
  removeModelDialogueItem: [id: string]
  updateConfig: [modelDialogueItem: MultiModelDialogueItem]
  replaceConfig: [modelDialogueItem: MultiModelDialogueItem]
  resetConversation: []
  updateMessageItem: [messageId: string, messageItem: Partial<MessageItemInterface>, index: number]
}>()

const systemLanguageStore = useSystemLanguageStore()

const modelConfig = useVModel(props, 'modelDialogueItem', emit)

const messageListRef = useTemplateRef<InstanceType<typeof MessageList>>('messageListRef')

const modelDialogueRef = ref<HTMLElement | null>(null)

const { height } = useElementSize(modelDialogueRef)

const isNotShowBackBottomBtn = computed(() => {
  return messageListRef.value?.isNotShowBackBottomBtn || false
})

defineExpose({
  scrollToBottom,
  isNotShowBackBottomBtn,
})

const isShowModelConfigMenu = ref(false)

const allMoreOptions = [
  {
    label: () => h('span', {}, t('multi_model_dialogue_module.remove_dialogue')),
    key: 'remove',
  },
  {
    label: () => h('span', {}, t('multi_model_dialogue_module.one_click_configuration')),
    key: 'replace-config',
  },
]

const currentMoreOptions = computed(() => {
  let currentOptions = allMoreOptions

  if (!props.modelDialogueItem.modelNickName) {
    currentOptions = currentOptions.filter((item) => item.key !== 'replace-config')
  }

  if (props.totalNum <= 2) {
    currentOptions = currentOptions.filter((item) => item.key !== 'remove')
  }

  return currentOptions
})

const isEnLanguage = computed(() => {
  return systemLanguageStore.currentLanguageInfo.key === 'en'
})

watch(
  () => props.modelDialogueItem.messageList.size,
  (newVal) => {
    newVal && (isShowKnowledgeContentResult.value = false)
  },
)

// 选择更多操作
function handleSelectMoreOption(key: string) {
  switch (key) {
    case 'remove':
      emit('removeModelDialogueItem', props.modelDialogueItem.id)
      break
    case 'replace-config':
      window.$message.ctWarning('', t('multi_model_dialogue_module.replace_configuration_tip')).then(() => {
        emit('replaceConfig', props.modelDialogueItem)
      })
      break
  }
}

// 是否显示配置菜单
function handleUpdateModelConfigShow(isShow: boolean) {
  isShowModelConfigMenu.value = isShow
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    messageListRef.value?.scrollToBottom()
  })
}

const isShowKnowledgeContentResult = ref(false)
const currentKnowledgeContentResult = ref<KnowledgeContentResultItem[]>([])

function handleShowKnowledgeResult(knowledgeContentResult: KnowledgeContentResultItem[]) {
  isShowKnowledgeContentResult.value = true
  currentKnowledgeContentResult.value = knowledgeContentResult
}

function handleUpdateSpecifyMessageItem(messageId: string, messageItem: Partial<MessageItemInterface>) {
  emit('updateMessageItem', messageId, messageItem, props.modelDialogueId)
}
</script>

<template>
  <div
    :id="modelDialogueItem.id"
    ref="modelDialogueRef"
    class="border-inactive-border-color relative flex flex-col overflow-hidden border-r px-6 last-of-type:border-none"
  >
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-5">
        <n-popover
          :key="modelConfig.id"
          placement="bottom-start"
          trigger="click"
          :show-arrow="false"
          :flip="false"
          style="border-radius: 10px; box-shadow: 0 4px 13px 0 hsla(0deg, 0%, 0%, 0.08)"
          :class="isEnLanguage ? 'w-[440px]' : 'w-[386px]'"
          @update:show="handleUpdateModelConfigShow"
        >
          <template #trigger>
            <n-button class="w-[145px]! !h-[34px] !rounded-[10px] !p-0">
              <div class="w-[145px]! box-border flex items-center justify-between px-[12px]">
                <div v-if="modelDialogueItem.modelNickName" class="flex flex-1 items-center overflow-hidden">
                  <div
                    class="mr-[5px] h-[16px] w-[16px] rounded-full bg-cover"
                    :style="{ backgroundImage: `url(${modelDialogueItem.icon})` }"
                  />
                  <div class="text-font-color flex-1 truncate text-start text-[14px]">
                    {{ modelDialogueItem.modelNickName }}
                  </div>
                </div>

                <div v-else class="text-gray-font-color">{{ t('multi_model_dialogue_module.select_model') }}</div>

                <i
                  class="iconfont icon-left rotate-270 text-[10px] transition-[rotate] duration-300 ease-in-out"
                  :class="{ '!rotate-90': isShowModelConfigMenu }"
                />
              </div>
            </n-button>
          </template>

          <ModelSetting
            v-model:model-config="modelConfig"
            :model-list-options="modelListOptions"
            :is-current="isCurrent"
            @update-config="(modelConfig) => emit('updateConfig', modelConfig)"
            @reset-conversation="emit('resetConversation')"
          />
        </n-popover>

        <div
          v-show="isCurrent"
          class="text-error-font-color font-600 select-none rounded-[10px] bg-[#FFF6F1] px-7 py-2.5 text-[13px] leading-none"
        >
          {{ t('common_module.currently') }}
        </div>
      </div>

      <n-dropdown
        v-if="currentMoreOptions.length"
        trigger="hover"
        :options="currentMoreOptions"
        placement="left-start"
        class="rounded-[10px]!"
        @select="handleSelectMoreOption"
      >
        <div
          v-show="!isCurrent"
          class="hover:bg-background-color flex h-6 w-6 cursor-pointer items-center justify-center rounded-full"
        >
          <i class="iconfont icon-more text-[20px]" />
        </div>
      </n-dropdown>
    </div>

    <div v-if="!modelDialogueItem.modelNickName" class="flex flex-1 flex-col items-center justify-center">
      <div class="h-13 w-13 bg-px-empty_model-png mb-3" />
      <span class="text-font-color select-none">{{ t('multi_model_dialogue_module.please_select_model') }}</span>
    </div>

    <MessageList
      v-else
      ref="messageListRef"
      :message-list="modelDialogueItem.messageList"
      @show-knowledge-result="handleShowKnowledgeResult"
      @update-specify-message-item="handleUpdateSpecifyMessageItem"
    />

    <HitKnowledgeContent
      v-model:is-show="isShowKnowledgeContentResult"
      :drawer-to-ref="`#${modelDialogueItem.id}`"
      :max-height="height"
      :knowledge-content-result="currentKnowledgeContentResult"
    />
  </div>
</template>

<style lang="scss" scoped>
:deep(.model-config-input-number .n-input__input-el) {
  text-align: center !important;
}

:deep(.agent-system-input .n-input-wrapper) {
  resize: none !important;
}
</style>
