<script setup lang="ts">
import { type CreateProductRequest, type Product } from '@/model/product'
import { type FormInstanceFunctions, type FormRules, MessagePlugin } from 'tdesign-vue-next'
import { createPetVariety, editPetVariety } from '@/api/petVariety'

const props = defineProps<{
  data: Product | null
}>()



const formData = ref<{
  name: string
}>({
  name: ''
})



watch(
  () => props.data,
  (newData) => {
    if (newData) {
      formData.value = newData
    }
  }
)

const rules: FormRules<CreateProductRequest> = {
  name: [
    {
      required: true,
      message: '品种名称不能为空'
    }
  ],

}

const formRef = ref<FormInstanceFunctions | null>(null)
const emits = defineEmits<{
  success: [void]
}>()

const editId = computed(() => props.data?.id)
const handleSave = async () => {
  const validate = await formRef.value?.validate()

  if (validate !== true) return

  try {
    editId.value
      ? await editPetVariety(editId.value, formData.value.name)
      : await createPetVariety(formData.value.name)
    await MessagePlugin.success(`${editId.value ? '编辑' : '创建'}成功`)
    emits('success')
  } finally {
    formRef.value?.reset()
  }
}
</script>

<template>
  <TDialog @confirm="handleSave">
    <TForm ref="formRef" :data="formData" :rules="rules" resetType="initial">
      <TFormItem label="宠物品种名称" name="name">
        <TInput v-model.trim="formData.name" clearable placeholder="请输入宠物品种名称" />
      </TFormItem>
    </TForm>
  </TDialog>
</template>

<style scoped></style>
