<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/chatModel/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 loading = ref(false)

const close = () => {
  formData.value = {}
  visible.value = false
  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
    loading.value = true
    const api = isEdit.value ? ModelApi.updateModel : ModelApi.createModel
    await api(values).finally(() => loading.value = false)
    ElMessage.success(isEdit.value ? '更新模型成功' : '创建模型成功');
    close();
    emit('reload');
  } catch (error) {
    console.error('Failed to save model:', error);
  }
}

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

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

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