<script setup>
// 重新分段弹窗：用新 max_len/overlap 对已导入文档重切
// 人工编辑过的分段会被覆盖 → 强提示 + 二次确认语义（按钮文案挑明）
import { reactive, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { rechunkDoc } from '@/api/kb'

const open = defineModel('open', { type: Boolean, default: false })
const props = defineProps({ doc: { type: Object, default: null } })
const emit = defineEmits(['done'])
const loading = ref(false)
const form = reactive({ max_len: 500, overlap: 50 })
const result = ref(null)

watch(open, (v) => { if (v) result.value = null })

async function submit() {
    if (form.overlap >= form.max_len) { message.warning('overlap 必须小于 max_len'); return }
    loading.value = true
    try {
        const res = await rechunkDoc(props.doc.id, { max_len: form.max_len, overlap: form.overlap })
        result.value = { ...res.data, max_len: form.max_len, overlap: form.overlap }
        message.success(`重切完成：${res.data?.old_count ?? '?'} 段 → ${res.data?.chunk_count ?? '?'} 段`)
        emit('done')
    } finally { loading.value = false }
}
</script>

<template>
  <a-modal v-model:open="open" :title="`重新分段：${doc?.title || ''}`" :confirm-loading="loading"
           ok-text="覆盖并重切" :ok-button-props="{ danger: true }" @ok="submit">
    <a-alert type="warning" show-icon class="!mb-4"
             message="将用文档原文按新参数重新切分，原有全部分段（含人工编辑过的内容与启停状态）会被替换" />
    <a-form layout="vertical">
      <div class="grid grid-cols-2 gap-4">
        <a-form-item label="分段长度 max_len（100~2000 字）">
          <a-input-number v-model:value="form.max_len" :min="100" :max="2000" :step="50" class="!w-full" />
        </a-form-item>
        <a-form-item label="重叠长度 overlap（0~200 字）">
          <a-input-number v-model:value="form.overlap" :min="0" :max="200" :step="10" class="!w-full" />
        </a-form-item>
      </div>
      <div class="text-xs" style="color: var(--text-3)">经验值：结构化条目类 300~500 / 长文叙述类 600~800；overlap 取 max_len 的 10% 左右</div>
    </a-form>
    <div v-if="result" class="glass p-3 mt-2 text-xs" style="color: var(--text-2)">
      完成：旧 {{ result.old_count }} 段 → 新 {{ result.chunk_count }} 段（max_len={{ result.max_len }} / overlap={{ result.overlap }}）
    </div>
  </a-modal>
</template>
