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

type QAKnowledgeChunkStructItem = QAKnowledgeChunkKeyItem & { content: string }

interface Props {
  btnLoading: boolean
  knowledgeChunkKeyList: QAKnowledgeChunkKeyItem[]
  currentChunkItem: QAKnowledgeChunkContentItem
}

const emit = defineEmits<{
  confirm: [chunkRelationId: string, chunkStructInfo: QAKnowledgeChunkInfoItem[]]
}>()

const props = defineProps<Props>()

const { t } = useI18n()

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

const knowledgeChunkFormRef = ref<FormInst | null>(null)
const chunkStructList = ref<QAKnowledgeChunkStructItem[]>([])

const chunkStructRules = {
  content: {
    required: true,
    trigger: 'blur',
    message: t('personal_space_module.knowledge_module.please_enter_the_content'),
  },
}

const dataTableScrollX = computed(() => {
  return props.knowledgeChunkKeyList.length * 215
})

const currentWordCount = computed(() => {
  return chunkStructList.value.reduce((acc, cur) => {
    return acc + cur.content.length
  }, 0)
})

const isExceedWordCount = computed(() => {
  return currentWordCount.value > 3000
})

watch(
  () => isShow.value,
  (newVal) => {
    if (newVal) {
      const map = new Map(
        props.currentChunkItem.chunkInfo.map((chunkInfoItem) => [chunkInfoItem.structId, chunkInfoItem]),
      )

      chunkStructList.value = props.knowledgeChunkKeyList.map((chunkKeyItem) => ({
        ...chunkKeyItem,
        content: map.get(chunkKeyItem.structId)?.content || '',
      }))
    }
  },
)

function handleAddKnowledgeChunk() {
  knowledgeChunkFormRef.value?.validate((valid) => {
    if (!valid) {
      const newChunkStructInfo = chunkStructList.value.map((chunkItem) => {
        const { structId, content } = chunkItem
        return {
          structId,
          content,
        }
      })
      emit('confirm', props.currentChunkItem.chunkRelationId, newChunkStructInfo)
    }
  })
}
</script>

<template>
  <CustomModal
    v-model:is-show="isShow"
    :title="t('personal_space_module.knowledge_module.edit_QA_data')"
    :btn-loading="btnLoading"
    :width="1340"
    :height="502"
    @confirm="handleAddKnowledgeChunk"
  >
    <template #content>
      <p class="text-gray-font-color mb-2.5">
        {{ t('personal_space_module.knowledge_module.limit_max_chunk_content_length', { count: currentWordCount }) }}
      </p>

      <n-scrollbar x-scrollable>
        <n-form
          ref="knowledgeChunkFormRef"
          :inline="true"
          :model="{ chunkStructList }"
          :rules="chunkStructRules"
          :style="{ width: dataTableScrollX + 'px' }"
          class="rounded-theme"
        >
          <n-form-item
            v-for="(chunkItem, index) in chunkStructList"
            :key="chunkItem.structId"
            class="qa-knowledge-chunk-key w-[215px]! box-border border-collapse overflow-hidden border border-r-0 border-[#e5e7eb] first:rounded-l-[10px] last:rounded-r-[10px] last:border-r"
            :path="`chunkStructList[${index}].content`"
            :show-require-mark="false"
            feedback-class="px-3!"
            :rule="chunkItem.isIndex === 'Y' ? chunkStructRules.content : []"
          >
            <template #label>
              <div class="flex h-12 w-full flex-shrink-0 items-center border-b border-[#e5e7eb] bg-[#f7f7fa] px-3">
                <span v-show="chunkItem.isIndex === 'Y'" class="mr-1 text-base text-[#d03050]">*</span>
                <n-ellipsis :tooltip="{ width: '200px' }">
                  {{ chunkItem.structName || '--' }}
                </n-ellipsis>
                <span
                  v-show="chunkItem.isIndex === 'Y'"
                  class="border-theme-color text-theme-color rounded-theme ml-[10px] flex-shrink-0 border px-[11px] py-[2px] text-xs"
                >
                  {{ t('personal_space_module.knowledge_module.index') }}
                </span>
              </div>
            </template>
            <div class="flex w-full flex-shrink-0 p-0">
              <n-input
                v-model:value="chunkItem.content"
                type="textarea"
                :placeholder="t('personal_space_module.knowledge_module.please_enter_the_content')"
                class="chunk-content-input h-[228px]"
                :autosize="{
                  minRows: 10,
                  maxRows: 10,
                }"
                :maxlength="850"
              />
            </div>
          </n-form-item>
        </n-form>
      </n-scrollbar>

      <p v-show="isExceedWordCount" class="mt-2 text-[#D03050]">
        {{ t('personal_space_module.knowledge_module.exceed_max_chunk_content_length') }}
      </p>
    </template>
  </CustomModal>
</template>

<style lang="scss" scoped>
:deep(.qa-knowledge-chunk-key.n-form-item) {
  flex-shrink: 0;
  width: 215px;
  margin-right: 0 !important;

  .n-form-item-label__text {
    width: 100%;
  }

  .n-form-item-label {
    padding: 0;
  }
}

:deep(.chunk-content-input.n-input--textarea) {
  --n-border: none !important;
  --n-border-focus: none !important;
  --n-border-hover: none !important;
  --n-box-shadow-focus: none !important;
}
</style>
