<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { Search } from '@icon-park/vue-next'
import { usePagination } from '@/composables/usePagination.ts'
import CustomModal from '@/components/custom-modal/custom-modal.vue'
import { fetchCreateKnowledge, fetchGetKnowledgeList } from '@/apis/knowledge'
import { KnowledgeDocumentItem, KnowledgeItem } from '@/views/personal-space/personal-knowledge/types'
import { TrainStatus } from '@/views/personal-space/personal-knowledge/types.d'
import { formatDateTime } from '@/utils/date-formatter'
import CreateKnowledgeModal, {
  KnowledgeFormDataInterface,
} from '@/views/personal-space/personal-knowledge/components/create-knowledge-modal.vue'

interface Props {
  isShowModal: boolean
  btnLoading: boolean
  modalTitle: string
}

interface Emits {
  (e: 'update:isShowModal', value: boolean): void
  (e: 'close'): void
}

const { t } = useI18n()

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

const router = useRouter()

const { paginationData } = usePagination()

const props = defineProps<Props>()

const emit = defineEmits<Emits>()

const searchKnowledgeInputValue = ref('')
const knowledgeListLoading = ref(false)
const isSearchEmptyList = ref(false)
const knowledgeList = ref<KnowledgeItem[]>([])

const showCreateKnowledgeModal = ref(false)
const createKnowledgeBtnLoading = ref(false)

const showModal = computed({
  get() {
    return props.isShowModal
  },
  set(value: boolean) {
    emit('update:isShowModal', value)
  },
})

const documentIcon = (documentName: string) => {
  const type = documentName.split('.')?.pop()?.toLowerCase()
  return type ? `https://gsst-poe-sit.gz.bcebos.com/icon/${type}.svg` : ''
}

const documentNameListText = computed(() => (documentInfos: KnowledgeDocumentItem[]) => {
  let documentNameListText = ''

  if (Array.isArray(documentInfos)) {
    documentInfos.forEach((knowledgeDocumentItem) => {
      if (knowledgeDocumentItem.documentName) {
        documentNameListText += `${knowledgeDocumentItem.documentName}、`
      }
    })
    return documentNameListText.slice(0, -1)
  } else {
    return '---'
  }
})

const isAddedKdId = computed(() => (kdId: number) => {
  return knowledgeIds.value.includes(kdId)
})

const addKdIdBtnDisabled = computed(() => {
  return knowledgeIds.value.length >= 5
})

const emptyKnowledgeListText = computed(() => {
  return isSearchEmptyList.value ? t('common_module.search_empty_data') : t('common_module.empty_data')
})

watch(
  () => props.isShowModal,
  (newVal) => {
    newVal && handleGetKnowledgeList()
  },
)

async function handleGetKnowledgeList() {
  paginationData.pageSize = 999999
  knowledgeListLoading.value = true

  const res = await fetchGetKnowledgeList<KnowledgeItem[]>(TrainStatus.COMPLETE, searchKnowledgeInputValue.value, {
    pagingInfo: paginationData,
  })

  if (res.code === 0) {
    knowledgeList.value = res.data
    paginationData.totalRows = res.pagingInfo?.totalRows || 0
    paginationData.totalPages = res.pagingInfo?.totalPages || 0
    isSearchEmptyList.value = !!searchKnowledgeInputValue.value && paginationData.totalRows === 0
    knowledgeListLoading.value = false
  }
}

function handleAddKnowledgeId(kdId: number, knowledgeName: string) {
  knowledgeIds.value.push(kdId)
  window.$message.success(
    t('personal_space_module.agent_module.agent_setting_module.agent_config_module.add_knowledge_successfully', [
      knowledgeName,
    ]),
  )
}

function handleDeleteKnowledgeId(kdId: number, knowledgeName: string) {
  knowledgeIds.value = knowledgeIds.value.filter((id) => id !== kdId)
  window.$message.success(
    t('personal_space_module.agent_module.agent_setting_module.agent_config_module.remove_knowledge_successfully', [
      knowledgeName,
    ]),
  )
}

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

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

async function handleCreateKnowledgeNextStep(createKnowledgeData: KnowledgeFormDataInterface) {
  createKnowledgeBtnLoading.value = true

  const res = await fetchCreateKnowledge<{ id: number }>({
    knowledgeName: createKnowledgeData.knowledgeName,
    desc: createKnowledgeData.knowledgeDesc,
  })

  if (res.code === 0) {
    router.push({
      name: 'UploadKnowledge',
      params: {
        id: res.data.id,
        type: createKnowledgeData.knowledgeType + '-' + createKnowledgeData.knowledgeImportType,
      },
    })

    showCreateKnowledgeModal.value = false
    createKnowledgeBtnLoading.value = false
  }
}
</script>

<template>
  <CustomModal
    v-model:is-show="showModal"
    :title="modalTitle"
    :width="690"
    :height="675"
    :content-style="{ padding: '0 12px 24px' }"
    @close="emit('close')"
  >
    <template #content>
      <div class="flex w-full justify-end px-3">
        <div class="gap-4.5 flex items-center">
          <i
            class="iconfont icon-huanyihuan text-gray-font-color hover:text-font-color cursor-pointer"
            @click="handleGetKnowledgeList"
          />

          <NInput
            v-model:value="searchKnowledgeInputValue"
            :placeholder="t('personal_space_module.knowledge_module.search_knowledge_placeholder')"
            class="w-[214px]!"
            @keyup.enter="handleGetKnowledgeList"
          >
            <template #suffix>
              <Search theme="outline" size="16" fill="#999" class="cursor-pointer" @click="handleGetKnowledgeList" />
            </template>
          </NInput>

          <NButton type="primary" @click="showCreateKnowledgeModal = true">
            {{ t('personal_space_module.knowledge_module.create_knowledge_modal_title') }}
          </NButton>
        </div>
      </div>

      <n-virtual-list
        v-show="!knowledgeListLoading"
        class="mt-[18px] max-h-[533px] w-full pl-3"
        :item-size="136"
        :items="knowledgeList"
        key-field="id"
        items-style="padding-right: 12px;"
      >
        <template #default="{ item }">
          <div
            :key="item.id"
            class="border-inactive-border-color hover:border-theme-color mb-4.5 flex h-[118px] w-full cursor-pointer items-center gap-4 rounded-[10px] border px-4 py-3.5"
            @click="handleToKnowledgeDocument(item.id)"
          >
            <div class="flex flex-1 flex-col overflow-hidden">
              <div class="flex flex-1">
                <div
                  class="mt-[3px] h-9 w-9 flex-shrink-0 bg-[url(https://gsst-poe-sit.gz.bcebos.com/data/20241106/1730873304749.png)] bg-contain"
                />

                <div class="ml-3.5 flex flex-col items-start overflow-hidden">
                  <n-ellipsis class="flex-1">
                    <span class="font-600">{{ item.knowledgeName }}</span>
                  </n-ellipsis>

                  <span class="text-gray-font-color mt-1 line-clamp-1 h-4 break-all text-xs">
                    {{ documentNameListText(item.documentInfos) }}
                  </span>

                  <div class="mt-3 flex items-center gap-4">
                    <span
                      v-show="!item.documentInfos?.length"
                      class="text-gray-font-color rounded-theme inline-block cursor-not-allowed bg-[#F7F7FA] px-2.5 py-[5px] text-[12px] leading-4"
                    >
                      {{ t('common_module.no_file') }}
                    </span>

                    <n-popover placement="bottom" content-style="padding: 16px 8px;" scrollable>
                      <template #trigger>
                        <span
                          v-show="item.documentInfos?.length"
                          class="text-theme-color rounded-theme inline-block cursor-pointer bg-[#F7F7FA] px-2.5 py-[5px] text-[12px] leading-4 hover:opacity-80"
                        >
                          {{ t('common_module.view_file') }}
                        </span>
                      </template>
                      <div>
                        <p class="text-gray-font-color h-5 px-4 text-[12px] leading-5">
                          {{
                            t(
                              'common_module.total_file',
                              { count: item.documentInfos.length },
                              item.documentInfos.length,
                            )
                          }}
                        </p>

                        <n-scrollbar class="max-h-[200px] px-4">
                          <ul class="min-w-[300px]">
                            <li
                              v-for="documentItem in item.documentInfos"
                              :key="documentItem.kdId"
                              class="text-font-color flex h-[50px] cursor-pointer items-center gap-2.5 border-b border-[#F4F4F4] text-xs hover:opacity-80"
                              @click="handleToDocumentDetail(item.id, documentItem.kdId)"
                            >
                              <img :src="documentIcon(documentItem.documentName)" class="h-5.5 w-5.5" />
                              <n-ellipsis class="max-w-[400px]">
                                <span>{{ documentItem.documentName }}</span>
                              </n-ellipsis>
                            </li>
                          </ul>
                        </n-scrollbar>
                      </div>
                    </n-popover>

                    <span class="text-gray-font-color text-[12px]">
                      {{ t('common_module.created_time') }}:
                      {{ formatDateTime(item.createdTime, 'YYYY-MM-DD') || '--' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <n-button
              v-show="!isAddedKdId(item.id)"
              class="min-w-17!"
              :bordered="addKdIdBtnDisabled"
              :type="addKdIdBtnDisabled ? '' : 'primary'"
              :disabled="addKdIdBtnDisabled"
              @click.stop="handleAddKnowledgeId(item.id, item.knowledgeName)"
            >
              {{ t('common_module.add') }}
            </n-button>

            <n-button
              v-show="isAddedKdId(item.id)"
              class="min-w-17!"
              type="error"
              ghost
              @click.stop="handleDeleteKnowledgeId(item.id, item.knowledgeName)"
            >
              {{ t('common_module.remove') }}
            </n-button>
          </div>
        </template>
      </n-virtual-list>

      <div v-show="knowledgeListLoading" class="px-3">
        <n-skeleton v-for="i in 4" :key="i" :height="118" :sharp="false" size="medium" class="mt-4.5" />
      </div>

      <div
        v-show="!knowledgeListLoading && knowledgeList.length === 0"
        class="flex h-[533px] items-center justify-center"
      >
        <div class="flex flex-col items-center justify-center">
          <div
            class="mb-5 h-[68px] w-[68px]"
            :class="isSearchEmptyList ? 'bg-px-search_empty_list-png' : 'bg-px-empty_list-png'"
          />
          <p class="text-gray-font-color select-none">{{ emptyKnowledgeListText }}</p>
        </div>
      </div>
    </template>

    <template #footer />
  </CustomModal>

  <CreateKnowledgeModal
    v-model:is-show-modal="showCreateKnowledgeModal"
    :btn-loading="createKnowledgeBtnLoading"
    @confirm="handleCreateKnowledgeNextStep"
  />
</template>
