import React, { useCallback, useRef, useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ModalForm, ProFormGroup } from '@ant-design/pro-form';
import { create } from '@/services/mgr/api';
import { fieldBuilderManager, fieldValueBuilderManager } from './api';

export type CreateFormProps = {
  singleTable: Api.SingleTable | undefined;
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSubmitting: () => Promise<any>;
  onSuccess: (params: any) => Promise<void>;
  onError: (params: any, error: unknown) => Promise<void>;
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const [exValues, setExValues] = useState<any>({});
  const formRef = useRef<ProFormInstance>();

  const appendExValues = useCallback((ev: any) => {
    setExValues((v: any) => {
      return { ...v, ...ev };
    });
  }, []);

  return (
    <ModalForm
      formRef={formRef}
      title="新增"
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          if (props.singleTable) {
            formRef?.current?.setFieldsValue(
              fieldValueBuilderManager.build('create', props.singleTable),
            );
          }
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (value: any) => {
        const params = await props.onSubmitting();
        try {
          await create(props.singleTable?.entityMetadata.code as string, { ...value, ...exValues });
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        {props.singleTable &&
          fieldBuilderManager.build('create', props.singleTable, appendExValues, formRef)}
      </ProFormGroup>
    </ModalForm>
  );
};

export default CreateForm;
