<script lang="ts" setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { createModelService, updateModelService } from '@/api/product/model'
import type { ModelService } from '@/api/product/types'

defineOptions({ name: 'ModelServiceFormModal' })

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

const isUpdate = ref(false)
const [registerForm, { setFieldsValue, validate }] = useForm({
  labelWidth: 80,
  baseColProps: { span: 24 },
  schemas: [
    {
      field: 'id',
      show: false,
      component: 'Input',
    },
    {
      field: 'serviceId',
      label: '服务 ID',
      required: true,
      component: 'Input',
      componentProps: {
        maxlength: 30,
        showCount: true,
      },
    },
    {
      field: 'description',
      label: '服务描述',
      required: true,
      component: 'InputTextArea',
    },
  ],
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

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

const route = useRoute()
async function handleSubmit() {
  try {
    const values = await validate<ModelService>()
    setModalProps({ confirmLoading: true })
    values.productId = route.params.id as string
    await (isUpdate.value ? updateModelService(values) : createModelService(values))
    closeModal()
    emit('success')
    useMessage().createMessage.success('保存成功')
  }
  catch {}
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

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