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

export type EditFormProps = {
  values: Partial<KANBAN.Settings.QiPingDayNumberDto>;
  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 intl = useIntl();
  const formRef = useRef<ProFormInstance>();

  return (
    <DrawerForm
      formRef={formRef}
      title={intl.formatMessage({
        id: 'pages.kanban/settings.qiPingDayNumber.editForm.title',
        defaultMessage: '编辑气瓶制造工序日标准产量',
      })}
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.resetFields();
          formRef?.current?.setFieldsValue(props.values);
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (value: KANBAN.Settings.QiPingDayNumberDto) => {
        const params = await props.onSubmitting();
        try {
          const processDefectRatioDatumUpdate: KANBAN.Settings.QiPingDayNumberUpdate = {
            id: props.values.id as string,
            ...formRef.current?.getFieldsValue(),
            month: moment(formRef.current?.getFieldValue('month')).format('YYYY-MM-DD HH:mm:ss'),
          };
          await serviceClient.qiPingDayNumberProgressStepService.update(
            processDefectRatioDatumUpdate,
          );
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText
          name="werks"
          label={'工厂'}
          width="md"
          rules={[{ required: true, message: '请输入工厂。' }]}
        />
        <ProFormText
          name="fevor"
          label={'生产管理员'}
          width="md"
          rules={[{ required: true, message: '请输入生产管理员。' }]}
        />
        <ProFormText
          name="operationName"
          label={'工序名'}
          width="md"
          rules={[{ required: true, message: '请输入车间。' }]}
        />
        <ProFormDatePicker.Month
          name="month"
          label={'月份'}
          width="md"
          rules={[{ required: true, message: '请输入月份。' }]}
        />
        <ProFormDigit
          name="dayNumber"
          label={'日标准产量'}
          width="md"
          rules={[{ required: true, message: '请输入日标准产量。' }]}
        />
      </ProFormGroup>
    </DrawerForm>
  );
};

export default EditForm;
