<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Plus, RightOne } from '@icon-park/vue-next'
import { fetchGetKnowledgeListByKdIds } from '@/apis/knowledge'
import AssociatedKnowledgeModal from './associated-knowledge-modal.vue'
import { KnowledgeItem } from '@/views/personal-space/personal-knowledge/types'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'

const { t } = useI18n()

const knowledgeConfig = defineModel<PersonalAppConfigState['knowledgeConfig']>('knowledgeConfig', { required: true })

const isShowAssociatedKnowledgeModel = ref(false)
const knowledgeConfigExpandedNames = ref<string[]>([])
const selectKnowledgeList = ref<KnowledgeItem[]>([])
const hoverKdId = ref(0)

watch(
  () => knowledgeConfig.value.knowledgeIds,
  async (newKdIds) => {
    if (newKdIds.length > 0) {
      await handleGetKnowledgeListByIds()

      if (selectKnowledgeList.value.length !== newKdIds.length) {
        knowledgeConfig.value.knowledgeIds = []
        selectKnowledgeList.value.forEach((knowledgeItem) => {
          knowledgeConfig.value.knowledgeIds.push(knowledgeItem.id)
        })
      }
      knowledgeConfig.value.knowledgeIds.length && (knowledgeConfigExpandedNames.value = ['knowledge'])
    }
  },
  { once: true, immediate: true },
)

const isHoverKnowledgeItem = computed(() => (kdId: number) => {
  return hoverKdId.value === kdId
})

const isOpenDocumentParsing = computed(() => knowledgeConfig.value.isDocumentParsing === 'Y')

async function handleGetKnowledgeListByIds() {
  const res = await fetchGetKnowledgeListByKdIds<KnowledgeItem[]>(knowledgeConfig.value.knowledgeIds)

  if (res.code === 0) {
    selectKnowledgeList.value = res.data
  }
}

function handleShowAssociatedKnowledgeModel() {
  isShowAssociatedKnowledgeModel.value = true
}

function handleUpdateKnowledgeConfigExpandedNames(expandedNames: string[]) {
  knowledgeConfigExpandedNames.value = expandedNames
}

function handleMouseoverKnowledgeItem(kdId: number) {
  hoverKdId.value = kdId
}

function handleMouseleaveKnowledgeItem() {
  hoverKdId.value = 0
}

function handleToKnowledgeDocument(kdId: number) {
  const url = `${window.location.origin}/fe/knowledge/document/${kdId}`
  window.open(url, '_blank')
}

function handleDeleteKnowledgeItem(kdId: number) {
  knowledgeConfig.value.knowledgeIds = knowledgeConfig.value.knowledgeIds.filter((id) => id !== kdId)
  selectKnowledgeList.value = selectKnowledgeList.value.filter((item) => item.id !== kdId)
}

function handleCloseAssociatedKnowledgeModal() {
  if (!knowledgeConfig.value.knowledgeIds.length) {
    selectKnowledgeList.value = []
    return
  }

  knowledgeConfigExpandedNames.value = ['knowledge']
  handleGetKnowledgeListByIds()
}

function handleUpdateDocumentParsing(value: boolean) {
  knowledgeConfig.value.isDocumentParsing = value ? 'Y' : 'N'
}
</script>

<template>
  <section class="border-b border-[#e8e9eb] px-5">
    <div class="pt-4">
      <h2 class="mb-3 text-[#84868c]">
        {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.knowledge') }}
      </h2>

      <NCollapse
        :expanded-names="knowledgeConfigExpandedNames"
        :trigger-areas="['main', 'arrow']"
        @update:expanded-names="handleUpdateKnowledgeConfigExpandedNames"
      >
        <template #arrow>
          <RightOne theme="filled" size="17" fill="#333" :stroke-width="3" />
        </template>

        <NCollapseItem
          :title="t('personal_space_module.agent_module.agent_setting_module.agent_config_module.knowledge_base')"
          name="knowledge"
          class="my-[13px]!"
        >
          <template #header-extra>
            <NTooltip trigger="hover">
              <template #trigger>
                <Plus
                  theme="outline"
                  size="22"
                  :stroke-width="3"
                  class="text-theme-color cursor-pointer"
                  @click="handleShowAssociatedKnowledgeModel"
                />
              </template>
              {{ t('common_module.add_knowledge') }}
            </NTooltip>
          </template>

          <ul v-show="selectKnowledgeList.length" class="flex flex-col gap-2">
            <li
              v-for="knowledgeItem in selectKnowledgeList"
              :key="knowledgeItem.id"
              class="rounded-theme flex cursor-pointer justify-between gap-2 border border-[#f2f5f9] px-3 py-1.5 hover:bg-[#f2f5f9]"
              @mouseover="handleMouseoverKnowledgeItem(knowledgeItem.id)"
              @mouseleave="handleMouseleaveKnowledgeItem"
              @click="handleToKnowledgeDocument(knowledgeItem.id)"
            >
              <div class="flex items-center gap-2 overflow-hidden">
                <div
                  class="h-6 w-6 bg-[url(https://gsst-poe-sit.gz.bcebos.com/data/20241012/1728700558225.png)] bg-contain bg-no-repeat"
                />

                <n-ellipsis class="flex-1">
                  <span class="text-xs">{{ knowledgeItem.knowledgeName }}</span>
                  <template #tooltip>
                    <div class="max-w-[500px]">
                      <span class="text-xs"> {{ knowledgeItem.knowledgeName }}</span>
                    </div>
                  </template>
                </n-ellipsis>
              </div>

              <div v-show="isHoverKnowledgeItem(knowledgeItem.id)" class="flex items-center justify-center">
                <i
                  class="hover:text-error-font-color text-font-color iconfont icon-reduce cursor-pointer outline-none"
                  @click.stop="handleDeleteKnowledgeItem(knowledgeItem.id)"
                />
              </div>
            </li>
          </ul>

          <span v-show="!knowledgeConfig.knowledgeIds.length" class="text-xs text-[#84868c]">
            {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.knowledge_base_desc') }}
          </span>
        </NCollapseItem>

        <NCollapseItem name="uploadFile" class="my-[13px]!">
          <template #header>
            <span class="mr-[5px] min-w-[60px]">
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.upload_file') }}
            </span>
          </template>

          <template #header-extra>
            <n-switch :value="isOpenDocumentParsing" size="small" @update:value="handleUpdateDocumentParsing">
              <template #checked> {{ t('common_module.open') }} </template>
              <template #unchecked> {{ t('common_module.close') }} </template>
            </n-switch>
          </template>

          <div>
            <div class="text-xs text-[#84868c]">
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.upload_file_desc') }}
            </div>
            <div class="flex flex-1 flex-wrap items-center gap-[12px] overflow-hidden"></div>
          </div>
        </NCollapseItem>
      </NCollapse>
    </div>
  </section>

  <AssociatedKnowledgeModal
    v-model:is-show-modal="isShowAssociatedKnowledgeModel"
    v-model:knowledge-ids="knowledgeConfig.knowledgeIds"
    :btn-loading="false"
    :modal-title="t('common_module.add_knowledge')"
    @close="handleCloseAssociatedKnowledgeModal"
  />
</template>
