<script lang="ts" setup>
import { ref } from 'vue'
import { getFormSchema } from './data'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { createProduct, updateProduct } from '@/api/product'
import type { Product } from '@/api/product/types'

defineOptions({ name: 'ProductFormModal' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(false)
const [registerForm, { setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: getFormSchema(isUpdate),
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: Product) => {
  isUpdate.value = true
  setFieldsValue({ ...data })
})

async function handleSubmit() {
  try {
    const values = await validate<Product>()
    setModalProps({ confirmLoading: true })
    await (isUpdate.value ? updateProduct(values) : createProduct(values))
    closeModal()
    emit('success')
    useMessage().createMessage.success('保存成功')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    width="30%"
    :min-height="100"
    :title="isUpdate ? '编辑' : '新增'"
    :after-close="() => isUpdate = false"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
