<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { FormInst, FormRules } from 'naive-ui'
import { Help } from '@icon-park/vue-next'
import { SegmentationConfigInterface } from '../../types'

interface Emit {
  (e: 'prev'): void
  (e: 'next', value: SegmentationConfigInterface): void
}

const { t } = useI18n()

const emit = defineEmits<Emit>()

const segmentationConfig = ref<SegmentationConfigInterface>(defaultSegmentationConfig())

const segmentationConfigFormRef = ref<FormInst | null>(null)

const segmentationConfigRules: FormRules = {
  punctuations: [
    {
      required: true,
      message: t('personal_space_module.knowledge_module.upload_document_module.please_select_segment_identifier'),
      trigger: ['blur', 'change'],
      type: 'array',
    },
  ],
  chunkSize: [
    {
      type: 'number',
      required: true,
      message: t('personal_space_module.knowledge_module.upload_document_module.please_input_segment_word_number'),
      trigger: 'blur',
    },
  ],
  repetitionRate: [
    {
      type: 'number',
      required: true,
      message: t(
        'personal_space_module.knowledge_module.upload_document_module.please_input_segment_overlap_word_proportion',
      ),
      trigger: 'blur',
    },
  ],
}

const punctuationOptions = [
  { label: t('personal_space_module.knowledge_module.divide_by_word_count'), value: 'by_word' },
  { label: t('personal_space_module.knowledge_module.Chinese_comma'), value: '，' },
  { label: t('personal_space_module.knowledge_module.Chinese_period'), value: '。' },
  { label: t('personal_space_module.knowledge_module.Chinese_question_mark'), value: '？' },
  { label: t('personal_space_module.knowledge_module.Chinese_exclamation_mark'), value: '！' },
  { label: t('personal_space_module.knowledge_module.English_period'), value: '.' },
  { label: t('personal_space_module.knowledge_module.English_exclamation_mark'), value: '!' },
  { label: t('personal_space_module.knowledge_module.ellipsis'), value: '......' },
]

const isDefaultSegmentation = computed(() => {
  return segmentationConfig.value.segmentationType === 'DEFAULT'
})

function defaultSegmentationConfig(): SegmentationConfigInterface {
  return {
    segmentationType: 'DEFAULT',
    chunkSize: 300,
    scrapSize: 80,
    repetitionRate: 5,
    relationInfo: [],
    regex: '',
    punctuations: [],
  }
}

function handleUpdatePunctuations(checkedValue: string[]) {
  if (checkedValue.at(-1) === 'by_word') {
    segmentationConfig.value.punctuations = ['by_word']
    segmentationConfig.value.segmentationType = 'NUMBER_Of_WORDS'
  } else {
    segmentationConfig.value.punctuations = checkedValue.filter((item) => item !== 'by_word')
    segmentationConfig.value.segmentationType = 'IDENTIFIER'
  }
}

function handleClickSegmentationType(segmentationType: 'DEFAULT' | 'IDENTIFIER') {
  if (segmentationType === 'IDENTIFIER' && segmentationConfig.value.segmentationType === 'NUMBER_Of_WORDS') {
    return
  }

  if (segmentationType === 'DEFAULT') {
    segmentationConfig.value = defaultSegmentationConfig()
    segmentationConfigFormRef.value?.restoreValidation()
    return
  }

  segmentationConfig.value.segmentationType = segmentationType
}

function handlePrev() {
  emit('prev')
}

function handleNext() {
  segmentationConfigFormRef.value &&
    segmentationConfigFormRef.value?.validate((errors) => {
      if (!errors) {
        emit('next', segmentationConfig.value)
      }
    })

  !segmentationConfigFormRef.value && emit('next', segmentationConfig.value)
}
</script>

<template>
  <div>
    <div class="flex flex-col gap-[18px]">
      <div
        class="hover:border-theme-color flex w-full cursor-pointer flex-col justify-between rounded-[10px] border bg-white px-6 py-5"
        :class="isDefaultSegmentation ? 'border-theme-color' : ''"
        @click="handleClickSegmentationType('DEFAULT')"
      >
        <span class="text-font-color mb-[7.5px]">
          {{ t('personal_space_module.knowledge_module.upload_document_module.default_segment_setting_title') }}
        </span>
        <span class="text-gray-font-color text-[13px]">
          {{ t('personal_space_module.knowledge_module.upload_document_module.default_segment_setting_desc') }}
        </span>
      </div>

      <div
        class="hover:border-theme-color flex w-full cursor-pointer flex-col justify-between rounded-[10px] border bg-white px-6 py-5"
        :class="!isDefaultSegmentation ? 'border-theme-color' : ''"
        @click="handleClickSegmentationType('IDENTIFIER')"
      >
        <span class="text-font-color mb-[7.5px]">{{ t('common_module.custom') }}</span>
        <span class="text-gray-font-color text-[13px]">
          {{ t('personal_space_module.knowledge_module.upload_document_module.custom_segment_setting_desc') }}
        </span>

        <div v-show="!isDefaultSegmentation" class="border-inactive-border-color mb-[18px] mt-[7px] border-b" />

        <div v-if="!isDefaultSegmentation">
          <n-form ref="segmentationConfigFormRef" :model="segmentationConfig" :rules="segmentationConfigRules">
            <n-form-item path="punctuations">
              <template #label>
                <div class="flex items-center gap-[5px]">
                  <span class="text-font-color">
                    {{ t('personal_space_module.knowledge_module.upload_document_module.segment_identifier') }}
                  </span>
                  <n-popover trigger="hover" class="max-w-[300px]">
                    <template #trigger>
                      <Help theme="outline" size="15" fill="#333" :stroke-width="3" class="mt-[2px] cursor-pointer" />
                    </template>
                    <span>
                      {{ t('personal_space_module.knowledge_module.upload_document_module.segment_identifier_tip') }}
                    </span>
                  </n-popover>
                </div>
              </template>

              <n-select
                v-model:value="segmentationConfig.punctuations"
                :options="punctuationOptions"
                multiple
                max-tag-count="responsive"
                :placeholder="
                  t('personal_space_module.knowledge_module.upload_document_module.please_select_segment_identifier')
                "
                @update:value="handleUpdatePunctuations"
              />
            </n-form-item>

            <n-form-item path="chunkSize">
              <template #label>
                <div class="flex items-center gap-[5px]">
                  <span class="text-font-color">
                    {{
                      t('personal_space_module.knowledge_module.upload_document_module.segment_maximum_number_of_words')
                    }}
                  </span>
                  <n-popover trigger="hover" class="max-w-[300px]">
                    <template #trigger>
                      <Help theme="outline" size="15" fill="#333" :stroke-width="3" class="mt-[2px] cursor-pointer" />
                    </template>
                    <span>
                      {{
                        t(
                          'personal_space_module.knowledge_module.upload_document_module.segment_maximum_number_of_words_tip',
                        )
                      }}
                    </span>
                  </n-popover>
                </div>
              </template>

              <n-input-number
                v-model:value="segmentationConfig.chunkSize"
                :min="0"
                :max="1000"
                :show-button="false"
                :placeholder="
                  t('personal_space_module.knowledge_module.upload_document_module.please_input_segment_word_number')
                "
                class="w-full"
              />
            </n-form-item>

            <n-form-item path="repetitionRate">
              <template #label>
                <div class="flex items-center gap-[5px]">
                  <span class="text-font-color">
                    {{
                      t('personal_space_module.knowledge_module.upload_document_module.segment_overlap_word_proportion')
                    }}
                  </span>
                  <n-popover trigger="hover" class="max-w-[300px]">
                    <template #trigger>
                      <Help theme="outline" size="15" fill="#333" :stroke-width="3" class="mt-[2px] cursor-pointer" />
                    </template>
                    <span>
                      {{
                        t(
                          'personal_space_module.knowledge_module.upload_document_module.segment_overlap_word_proportion_tip',
                        )
                      }}
                    </span>
                  </n-popover>
                </div>
              </template>

              <n-input-number
                v-model:value="segmentationConfig.repetitionRate"
                :min="0"
                :max="25"
                :show-button="false"
                :placeholder="
                  t(
                    'personal_space_module.knowledge_module.upload_document_module.please_input_segment_overlap_word_proportion',
                  )
                "
                class="w-full"
              >
                <template #suffix>
                  <span class="mr-[-8px] rounded-r-[5px] border px-3.5">%</span>
                </template>
              </n-input-number>
            </n-form-item>
          </n-form>
        </div>
      </div>
    </div>

    <div class="mt-14 flex justify-end">
      <NButton @click="handlePrev">{{ t('common_module.prev_btn_text') }}</NButton>
      <NButton type="primary" class="ml-5!" :bordered="false" @click="handleNext">
        {{ t('common_module.next_btn_text') }}
      </NButton>
    </div>
  </div>
</template>
