<script setup lang="ts">
import {Form} from '@/components/Form'
import {nextTick, ref} from 'vue'
import {FormSchema} from "@/types/form";
import {getSchemas} from "@/views/ai/model/embedding/composables/schemas";
import {ModelApi} from "@/api/new-ai/model";
import {ElMessage} from "element-plus";

const emit = defineEmits(['reload'])
const visible = ref(false)
const formData = ref({})
const formRef = ref()
const schemas = ref([])
const isEdit = ref(false)

const close = () => {
  visible.value = false
  formRef.value.clearForm()
  formData.value = {}
  schemas.value = []
  nextTick(() => {
    formRef.value?.clearForm()
    formRef.value?.setSchema(schemas.value)
  })
}

const show = async (data: any = {}) => {
  visible.value = true
  isEdit.value = !!data.id
  await nextTick()
  formRef.value.setValues(data)
  schemas.value = getSchemas(data.provider).slice(1);
  formRef.value.setSchema(schemas.value)
}

const handleSubmit = async () => {
  try {
    const form = formRef.value.getElFormRef()
    await form.validate()
    const values = formRef.value.formModel
    
    if (isEdit.value) {
      await ModelApi.updateModel(values);
      ElMessage.success('更新向量模型成功');
    } else {
      await ModelApi.createModel(values);
      ElMessage.success('创建向量模型成功');
    }
    close();
    emit('reload');
  } catch (error) {
    console.error('Failed to save model:', error);
    ElMessage.error(isEdit.value ? '更新向量模型失败' : '创建向量模型失败');
  }
}

defineExpose({
  show,
  close
})
</script>

<template>
  <el-dialog v-model="visible" draggable :title="isEdit ? '编辑向量模型' : '新增向量模型'" width="800px" @close="close">
    <Form ref="formRef" :model="formData" :schema="schemas" />
    <template #footer>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
</style>
