import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ModalForm, ProFormGroup, ProFormText, ProFormDigit } from '@ant-design/pro-form';
import serviceClient from '@/services/report/settings/index';

export type CreateFormProps = {
  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 formRef = useRef<ProFormInstance>();

  return (
    <ModalForm
      formRef={formRef}
      title="新增设备总数量"
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          const values: Report.Settings.DeviceTotalQuantityDto = {
            id: '',
            workshop: '',
            quantity: 0,
          };
          formRef?.current?.setFieldsValue(values);
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (value: Report.Settings.DeviceTotalQuantityDto) => {
        const params = await props.onSubmitting();
        try {
          const deviceTotalQuantityCreate: Report.Settings.DeviceTotalQuantityCreate = {
            workshop: value.workshop as string,
            quantity: value.quantity as number,
          };
          await serviceClient.deviceTotalQuantityService.create(deviceTotalQuantityCreate);
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText
          name="workshop"
          label={'车间'}
          width="md"
          rules={[{ required: true, message: '请输入车间。' }]}
        />
        <ProFormDigit
          width="md"
          name="quantity"
          label={'数量'}
          initialValue={0}
          rules={[{ required: true, message: '请输入数量。' }]}
        />
      </ProFormGroup>
    </ModalForm>
  );
};

export default CreateForm;
