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.ProcessDefectRatioDatumDto>;
  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.processDefectRatioDatum.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.ProcessDefectRatioDatumDto) => {
        const params = await props.onSubmitting();
        try {
          const processDefectRatioDatumUpdate: KANBAN.Settings.ProcessDefectRatioDatumUpdate = {
            id: props.values.id as string,
            ...formRef.current?.getFieldsValue(),
            datumDate: moment(formRef.current?.getFieldValue('datumDate')).format(
              'YYYY-MM-DD HH:mm:ss',
            ),
          };
          await serviceClient.processDefectRatioDatumService.update(processDefectRatioDatumUpdate);
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText
          name="stepCode"
          label={'工序编号'}
          width="md"
          rules={[{ required: true, message: '请输入工序编号。' }]}
        />
        <ProFormText
          name="werks"
          label={'工厂'}
          width="md"
          rules={[{ required: true, message: '请输入工厂。' }]}
        />
        <ProFormText
          name="fevor"
          label={'生产管理员'}
          width="md"
          rules={[{ required: true, message: '请输入生产管理员。' }]}
        />
        <ProFormDigit
          name="datumValue"
          label={'基准值'}
          width="md"
          rules={[{ required: true, message: '请输入基准值。' }]}
        />
        <ProFormDatePicker.Month
          name="datumDate"
          label={'月份'}
          width="md"
          rules={[{ required: true, message: '请输入月份。' }]}
        />
      </ProFormGroup>
    </DrawerForm>
  );
};

export default EditForm;
