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

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

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

  useEffect(() => {
    if (props.visible) {
      setExValues(() => {
        const ev: any = new Object();
        props.singleTable?.fields
          .filter((f) => !!!f.hideInEditForm)
          .filter((f) => f.dataType.startsWith('#'))
          .forEach((f) => {
            const fValue = props.values[f.code];
            if (fValue) {
              const idValue = fValue.id;
              if (idValue) {
                ev[f.code] = idValue;
              }
            }
          });
        return ev;
      });
    }
  }, [props.singleTable, props.values, props.visible]);

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

  return (
    <DrawerForm
      formRef={formRef}
      title="编辑"
      width="780px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          if (props.singleTable) {
            formRef?.current?.setFieldsValue(
              fieldValueBuilderManager.build('edit', props.singleTable, props.values),
            );
          }
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (values) => {
        const params = await props.onSubmitting();
        try {
          await update(props.singleTable?.entityMetadata.code as string, {
            ...values,
            ...exValues,
            id: props.values.id,
          });
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        {props.singleTable &&
          fieldBuilderManager.build('edit', props.singleTable, appendExValues, formRef)}
      </ProFormGroup>
    </DrawerForm>
  );
};

export default EditForm;
