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

export type EditFormProps = {
  values: Partial<Report.Settings.DeviceTotalQuantityDto>;
  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 formRef = useRef<ProFormInstance>();

  return (
    <DrawerForm
      formRef={formRef}
      title="编辑设备总数量"
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.setFieldsValue(props.values);
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          const updateDto: Report.Settings.DeviceTotalQuantityUpdate = {
            id: props.values.id || '',
            workshop: formData.workshop,
            quantity: formData.quantity,
          };
          await serviceClient.deviceTotalQuantityService.update(updateDto);
          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>
    </DrawerForm>
  );
};

export default EditForm;
