<template>
  <BasicModal v-bind="$attrs" @register="register" :title="title" width="640px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from '../printTemplate.data';
  import { add, edit } from '../printTemplate.api';

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

  const isUpdate = ref(false);

  const title = computed(() => (!unref(isUpdate) ? '新增打印模板' : '编辑打印模板'));

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

  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate) && data?.record) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      if (!unref(isUpdate)) {
        delete values.id;
        if (!values.templateJson) {
          values.templateJson = '{}';
        }
      }
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        await edit(values);
      } else {
        await add(values);
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
