<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { FormInst } from 'naive-ui'
import CustomModal from '@/components/custom-modal/custom-modal.vue'
import { KnowledgeChunkItem } from '../knowledge-type'

interface Props {
  isShowModal: boolean
  btnLoading: boolean
  chunkItem: KnowledgeChunkItem
}

interface Emits {
  (e: 'update:isShowModal', value: boolean): void
  (e: 'confirm', chunkContent: string, chunkSort: number): void
}

const { t } = useI18n()

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const defaultKnowledgeChunkData: KnowledgeChunkItem = {
  knowledgeId: '',
  chunkContent: '',
  chunkRelationId: '',
  chunkSort: 0,
  isOpen: 'Y',
}
const knowledgeChunkFormRef = ref<FormInst | null>(null)
const knowledgeChunkData = ref<KnowledgeChunkItem>({ ...defaultKnowledgeChunkData })

const knowledgeChunkRules = {
  chunkContent: [
    {
      required: true,
      message: () => t('personal_space_module.knowledge_module.knowledge_chunk_content_input_rule'),
      trigger: 'blur',
    },
  ],
}

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

const isDisabledConfirmBtn = computed(() => {
  return !knowledgeChunkData.value.chunkContent
})

watch(
  () => showModal.value,
  (newVal) => {
    newVal && (knowledgeChunkData.value = JSON.parse(JSON.stringify(props.chunkItem)))
  },
)

function handleConfirm() {
  knowledgeChunkFormRef.value?.validate((valid) => {
    if (!valid) {
      const { chunkContent, chunkSort } = knowledgeChunkData.value
      emit('confirm', chunkContent, chunkSort)
    }
  })
}
</script>

<template>
  <CustomModal
    v-model:is-show="showModal"
    :title="t('personal_space_module.knowledge_module.add_knowledge_chunk_modal_title')"
    :width="808"
    :height="710"
    :btn-disabled="isDisabledConfirmBtn"
    :btn-loading="btnLoading"
    @confirm="handleConfirm"
  >
    <template #content>
      <n-form
        ref="knowledgeChunkFormRef"
        :model="knowledgeChunkData"
        :rules="knowledgeChunkRules"
        :label-width="100"
        label-placement="top"
      >
        <n-form-item :show-label="false" path="chunkContent">
          <n-input
            v-model:value="knowledgeChunkData.chunkContent"
            type="textarea"
            :placeholder="t('personal_space_module.knowledge_module.knowledge_chunk_content_input_placeholder')"
            :rows="23"
            :maxlength="1200"
            show-count
          />
        </n-form-item>
      </n-form>
    </template>
  </CustomModal>
</template>
