<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 { createSubscription, updateSubscription } from '@/api/subscription/list'
import type { SubScription } from '@/api/subscription/list/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: SubScription) => {
  isUpdate.value = true
  setFieldsValue({
    ...data,
    messageType: data.messageType.split(',').map(Number),
  })
})

async function handleSubmit() {
  try {
    const values = await validate<Pick<SubScription, 'productId' | 'id' | 'messageType'>>()
    setModalProps({ confirmLoading: true })
    values.messageType = (values.messageType as unknown as string[]).join(',')
    await (isUpdate.value ? updateSubscription(values) : createSubscription(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>
