<script setup lang="ts">
import { nextTick, onMounted, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'

interface Props {
  contentResultItem: KnowledgeContentResultItem
}

defineProps<Props>()

const { t } = useI18n()

const knowledgeContentRef = useTemplateRef('knowledgeContentRef')

const isContentExceed = ref(false)
const isExpandContent = ref(false)

const ELLIPSIS_HIGHT = 100

onMounted(() => {
  nextTick(() => {
    if (knowledgeContentRef.value) {
      isContentExceed.value = knowledgeContentRef.value?.offsetHeight > ELLIPSIS_HIGHT
    }
  })
})

function handleClickExpand() {
  isExpandContent.value = !isExpandContent.value
}
</script>

<template>
  <div
    class="rounded-theme border bg-white px-[15px] py-4"
    :class="isExpandContent ? 'border-theme-color' : 'border-inactive-border-color'"
  >
    <div class="flex-center text-gray-font-color font-family-medium flex-shrink-0 justify-between gap-[10px]">
      <div class="flex flex-1 items-center gap-[5px]">
        <span class="flex-shrink-0">
          {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.from_knowledge_base') }}:
        </span>
        <n-ellipsis class="w-full!">
          {{ contentResultItem.knowledgeName }}
        </n-ellipsis>
      </div>

      <div class="flex flex-shrink-0 items-center gap-[5px]">
        <span>{{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.score') }}:</span>

        <span>{{ (Math.floor(contentResultItem.score * 100) / 100).toFixed(2) }}</span>
      </div>
    </div>

    <div class="text-font-color relative mt-3 leading-4">
      <span
        ref="knowledgeContentRef"
        class="whitespace-pre-wrap break-all leading-4"
        :class="isContentExceed && !isExpandContent ? `line-clamp-6 max-h-[100px] overflow-y-hidden` : ''"
      >
        {{ contentResultItem.content }}
      </span>

      <div
        v-show="isContentExceed"
        class="text-gray-font-color flex-center mt-4 h-[16px] w-[72px] cursor-pointer gap-[5px] bg-white pr-2 leading-4 hover:text-[rgba(153,153,153,0.8)]"
        :class="isExpandContent ? 'ml-auto items-baseline' : 'flex w-full justify-end'"
        @click="handleClickExpand"
      >
        <span class="inline-block leading-4">
          {{ isExpandContent ? t('common_module.fold') : t('common_module.unfold') }}
        </span>
        <i
          class="iconfont icon-left rotate-270 text-center text-xs leading-4"
          :class="{ '!rotate-90': isExpandContent }"
        />
      </div>
    </div>
  </div>
</template>
