<script setup lang="ts">
import { computed, h } from 'vue'
import { NSwitch } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import { useDebounceFn } from '@vueuse/core'
import CustomModal from '@/components/custom-modal/custom-modal.vue'
import { QAKnowledgeChunkKeyItem } from '../../../types'

interface Props {
  kdId: number
  knowledgeChunkKeyList: QAKnowledgeChunkKeyItem[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  updateKnowledgeChunkIndex: [chunkKeyItem: QAKnowledgeChunkKeyItem]
  confirm: []
}>()

const { t } = useI18n()

const isShow = defineModel<boolean>('isShow', { required: true })

const isHasChunkIndex = computed(() => {
  return props.knowledgeChunkKeyList.some((item) => item.isIndex === 'Y')
})

const chunkIndexColumns = createChunkIndexColumns()

function createChunkIndexColumns() {
  return [
    {
      title: () => t('personal_space_module.knowledge_module.field_name'),
      key: 'structName',
      render: (row: QAKnowledgeChunkKeyItem) => {
        return row.structName || '-'
      },
    },
    {
      title: () => t('personal_space_module.knowledge_module.setting_index'),
      key: 'isIndex',
      render: (row: QAKnowledgeChunkKeyItem) => {
        return h(
          NSwitch,
          {
            value: row.isIndex === 'Y',
            size: 'small',
            onUpdateValue: () => handleKnowledgeTableAction(row),
          },
          {},
        )
      },
    },
  ]
}

const handleKnowledgeTableAction = useDebounceFn((chunkKeyItem: QAKnowledgeChunkKeyItem) => {
  chunkKeyItem.isIndex = chunkKeyItem.isIndex === 'Y' ? 'N' : 'Y'

  if (!isHasChunkIndex.value) {
    chunkKeyItem.isIndex = chunkKeyItem.isIndex === 'Y' ? 'N' : 'Y'
    window.$message.warning(t('personal_space_module.knowledge_module.select_at_least_one_field_as_the_index'))
    return
  }

  emit('updateKnowledgeChunkIndex', chunkKeyItem)
}, 500)
</script>

<template>
  <CustomModal
    v-model:is-show="isShow"
    :title="t('personal_space_module.knowledge_module.setting_index')"
    :width="644"
    @confirm="emit('confirm')"
  >
    <template #content>
      <p class="text-gray-font-color mb-2.5">
        {{ t('personal_space_module.knowledge_module.setting_index_desc') }}
      </p>

      <n-data-table
        :single-line="false"
        :columns="chunkIndexColumns"
        :data="knowledgeChunkKeyList"
        :max-height="300"
        class="mb-4"
      />
    </template>

    <template #footer></template>
  </CustomModal>
</template>
