<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 AgentKnowledgeSettingModal, { KnowledgeConfigType } from './agent-knowledge-setting-modal.vue'
import { KnowledgeItem } from '@/views/personal-space/personal-knowledge/types'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { KnowledgeTypeIcon } from '@/enums/knowledge'

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)
const isShowAgentKnowledgeSettingModal = ref(false)

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'
}

function handleUpdateKnowledgeConfig(newKnowledgeConfig: KnowledgeConfigType) {
  knowledgeConfig.value = { ...knowledgeConfig.value, ...newKnowledgeConfig }
  isShowAgentKnowledgeSettingModal.value = false
  window.$message.success(t('common_module.save_success_message'))
}
</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>
            <div
              class="text-theme-color mr-2 cursor-pointer border-r pr-3 text-xs hover:opacity-80"
              @click="isShowAgentKnowledgeSettingModal = true"
            >
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.advanced_setting') }}
            </div>

            <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-contain bg-no-repeat"
                  :style="{ backgroundImage: `url(${KnowledgeTypeIcon[knowledgeItem.knowledgeType]})` }"
                />

                <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>

              <n-tooltip placement="top">
                <template #trigger>
                  <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>
                </template>
                <span>{{ t('common_module.remove') }}</span>
              </n-tooltip>
            </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"
  />

  <AgentKnowledgeSettingModal
    v-model:is-show-modal="isShowAgentKnowledgeSettingModal"
    @confirm="handleUpdateKnowledgeConfig"
  />
</template>
