<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { formSchema } from './${businessName}.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    get${BusinessName}Api,
    add${BusinessName}Api,
    edit${BusinessName}Api,
#if($table.tree || $table.subTree)
    list${BusinessName}ExNodesApi,
#end
  } from '/@/api/${moduleName}/${authorityName}/${businessName}';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';

  export default defineComponent({
    name: '${BusinessName}Modal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, #if($table.tree || $table.subTree)updateSchema,#end validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(
        async (data) => {
          resetFields();
          setModalProps({ confirmLoading: false });
          isUpdate.value = !!data?.isUpdate;
  
          if (unref(isUpdate)) {
            const ${businessName} = await get${BusinessName}Api(data.record.${pkColumn.javaField});
            setFieldsValue({...${businessName}});
          }
#if($table.tree || $table.subTree)
          const treeData = await list${BusinessName}ExNodesApi(
            unref(isUpdate) ? data.record.${pkColumn.javaField} : undefined,
          );
          updateSchema({field: '${treeMap.parentIdColumn.javaField}', componentProps: { treeData } });
#end
        },
      );

      /** 标题初始化 */
      const getTitle = computed(() =>
        !unref(isUpdate) ? '新增${functionName}' : '编辑${functionName}',
      );

      /** 提交按钮 */
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          unref(isUpdate)
            ? await edit${BusinessName}Api(values).then(() => {
                closeModal();
                createMessage.success('编辑${functionName}成功！');
              })
            : await add${BusinessName}Api(values).then(() => {
                closeModal();
                createMessage.success('新增${functionName}成功！');
              });
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
