<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 AssociatedDatabaseModal from './associated-database-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'
import { fetchGetDataListByIds } from '@/apis/database'
import { DatabaseItemInterface } from '@/views/personal-space/personal-database/type'

const { t } = useI18n()

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

const isShowAssociatedKnowledgeModel = ref(false)
const knowledgeConfigExpandedNames = ref<string[]>([])
const selectKnowledgeList = ref<KnowledgeItem[]>([])
const hoverKdId = ref(0)
const isShowAgentKnowledgeSettingModal = ref(false)
const isShowAssociatedDatabaseModal = ref(false)
const selectDatabaseList = ref<DatabaseItemInterface[]>([])
const hoverDBId = 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.push('knowledge')
    }
  },
  { once: true, immediate: true },
)

watch(
  () => databaseConfig.value.ids,
  async (newDBIds) => {
    if (newDBIds?.length > 0) {
      await handleGetDatabaseListByIds()

      if (selectDatabaseList.value.length !== newDBIds.length) {
        databaseConfig.value.ids = []
        selectDatabaseList.value.forEach((databaseItem) => {
          databaseConfig.value.ids.push(databaseItem.id)
        })
      }
      databaseConfig.value.ids?.length && knowledgeConfigExpandedNames.value.push('database')
    }
  },
  { once: true, immediate: true },
)

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

const isHoverDatabaseItem = computed(() => (dbId: number) => {
  return hoverDBId.value === dbId
})

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.includes('knowledge') && knowledgeConfigExpandedNames.value.push('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'))
}

async function handleGetDatabaseListByIds() {
  if (!databaseConfig.value?.ids?.length) return

  const res = await fetchGetDataListByIds<DatabaseItemInterface[]>(databaseConfig.value.ids)

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

async function handleCloseAssociatedDatabaseModal() {
  if (!databaseConfig.value?.ids?.length) {
    selectDatabaseList.value = []
    return
  }

  !knowledgeConfigExpandedNames.value.includes('database') && knowledgeConfigExpandedNames.value.push('database')
  handleGetDatabaseListByIds()
}

function handleMouseoverDatabaseItem(dbId: number) {
  hoverDBId.value = dbId
}

function handleMouseleaveDatabaseItem() {
  hoverDBId.value = 0
}

function handleToDatabaseDetail(dbId: number) {
  const url = `${window.location.origin}/fe/personal-space/database/table/${dbId}`
  window.open(url, '_blank')
}

function handleDeleteDatabaseItem(dbId: number) {
  databaseConfig.value.ids = databaseConfig.value.ids.filter((id) => id !== dbId)
  selectDatabaseList.value = selectDatabaseList.value.filter((item) => item.id !== dbId)
}
</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 :title="t('common_module.database')" name="database" 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="isShowAssociatedDatabaseModal = true"
                />
              </template>
              {{ t('personal_space_module.database_module.add_database') }}
            </NTooltip>
          </template>

          <ul>
            <li
              v-for="databaseItem in selectDatabaseList"
              :key="databaseItem.id"
              class="rounded-theme flex cursor-pointer justify-between gap-2 border border-[#f2f5f9] px-3 py-1.5 hover:bg-[#f2f5f9]"
              @mouseover="handleMouseoverDatabaseItem(databaseItem.id)"
              @mouseleave="handleMouseleaveDatabaseItem"
              @click="handleToDatabaseDetail(databaseItem.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/v1/icon/direct-db.svg')] bg-contain bg-no-repeat"
                />
                <n-ellipsis class="flex-1">
                  <span class="text-xs">{{ databaseItem.title }}</span>
                  <template #tooltip>
                    <div class="max-w-[500px]">
                      <span class="text-xs"> {{ databaseItem.title }}</span>
                    </div>
                  </template>
                </n-ellipsis>
              </div>

              <n-tooltip placement="top">
                <template #trigger>
                  <div v-show="isHoverDatabaseItem(databaseItem.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="handleDeleteDatabaseItem(databaseItem.id)"
                    />
                  </div>
                </template>
                <span>{{ t('common_module.remove') }}</span>
              </n-tooltip>
            </li>
          </ul>

          <span v-show="!selectDatabaseList.length" class="text-xs text-[#84868c]">
            {{
              t('personal_space_module.agent_module.agent_setting_module.agent_config_module.associated_database_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"
  />

  <AssociatedDatabaseModal
    v-model:show-modal="isShowAssociatedDatabaseModal"
    v-model:db-ids="databaseConfig.ids"
    @close="handleCloseAssociatedDatabaseModal"
  />
</template>
