<template>
  <el-dialog v-model="visible" title="创建知识库" width="800px" :close-on-click-modal="!loading" :close-on-press-escape="!loading" @close="handleClose">
    <Form :schema="formSchemas" v-if="visible"  :model="formData" ref="formRef"  @register="register"/>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { FormSchema } from '@/types/form';
import {Form} from '@/components/Form'
import { useForm } from '@/hooks/web/useForm';
import { ref } from 'vue';
import { KnowledgeApi } from '@/api/new-ai/knowledge';
import { ElMessage } from 'element-plus';

const { register, methods, elFormRef } = useForm();
const visible = ref(false);
const loading = ref(false);
const formRef = ref();
const formData = ref({})
const emits = defineEmits(['reload'])
const handleSubmit = async () => {
 
  try {
    await elFormRef.value?.validate()
    const data = await methods.getFormData();
    loading.value = true;
    await KnowledgeApi.createKnowledge(data).finally(() => loading.value = false);
    ElMessage.success('创建成功');
    handleClose();
    emits('reload');
  } catch (error) {
    console.error('创建失败:', error);
    ElMessage.error('创建失败');
  } finally {
    loading.value = false;
  }
};

const handleClose = () => {
  visible.value = false;
  nextTick(() => {
    formRef.value?.clearForm()
    formRef.value?.setSchema([])
  })
};

const formSchemas = computed(() => [
  {
    field: 'name',
    component: 'Input',
    label: '知识库名称',
    componentProps: {
      placeholder: '请输入知识库名称',
    },
    formItemProps: {
      rules: [{ required: true, message: '请输入知识库名称', trigger: ['blur'] }],
    }
  },
  {
    field: 'embedStoreId',
    label: '向量数据库',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '请选择关联向量数据库', trigger: ['blur'] }],
    }
  },
  {
    field: 'embedModelId',
    label: '向量模型',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '请选择关联向量模型', trigger: ['blur'] }],
    }
  },
  {
    field: 'des',
    component: 'Input',
    label: '知识库描述',
    componentProps: {
      placeholder: '请输入知识库描述',
      type: 'textarea',
      autosize: {
        minRows: 3,
        maxRows: 3,
      },
    },
   formItemProps: {
    rules: [{ required: true, message: '请输入知识库描述', trigger: ['blur'] }],
   }
  },
]) 
const open = async () => {
    visible.value = true;
  }
// 对外暴露方法
defineExpose({
  open
});
</script>
<script></script>