<script lang="ts" setup>
import { ref } from 'vue'
import { formSchema } from './data'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { createMenu, updateMenu } from '@/api/system/menu'
import type { MenuItem } from '@/api/system/menu/types'

defineOptions({ name: 'SystemMenuFormModal' })

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

const [registerForm, { setFieldsValue, validate }] = useForm({
  labelWidth: 140,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
})

const isUpdate = ref(false)
const [registerModal, { setModalProps, closeModal }] = useModalInner((data: Partial<MenuItem>) => {
  isUpdate.value = !!data.id
  console.log(data)
  setFieldsValue({
    ...data,
    parentId: data.parentId === '0' ? undefined : data.parentId,
  })
})

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

<template>
  <BasicModal
    :title="isUpdate ? '编辑' : '新建'"
    :after-close="() => isUpdate = false"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" @submit="handleSubmit" />
  </BasicModal>
</template>
