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

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 intl = useIntl();
  const formRef = useRef<ProFormInstance>();

  return (
    <ModalForm
      formRef={formRef}
      title={intl.formatMessage({
        id: 'pages.kanban/settings.processYieldStandDailyData.createForm.title',
        defaultMessage: '新增工序产量每日标准量数据',
      })}
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.resetFields();
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (value: KANBAN.Settings.ProcessYieldStandDailyDataDto) => {
        const params = await props.onSubmitting();
        try {
          const processYieldStandDailyDataCreate: KANBAN.Settings.ProcessYieldStandDailyDataCreate =
            {
              ...formRef.current?.getFieldsValue(),
              datumDate: moment(formRef.current?.getFieldValue('datumDate')).format(
                'YYYY-MM-DD HH:mm:ss',
              ),
            };
          await serviceClient.processYieldStandDailyDataService.create(
            processYieldStandDailyDataCreate,
          );
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText
          name="operationName"
          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="standDailyValue"
          label={'每日标准值'}
          width="md"
          rules={[{ required: true, message: '请输入每日标准值。' }]}
        />
        <ProFormDatePicker.Month
          name="datumDate"
          label={'月份'}
          width="md"
          rules={[{ required: true, message: '请输入月份。' }]}
        />
      </ProFormGroup>
    </ModalForm>
  );
};

export default CreateForm;
