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/report/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.report.settings.monthlyPlan.createForm.title',
        defaultMessage: '新增月计划',
      })}
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          const values: Report.Settings.MonthlyPlanDto = {
            id: '',
            werks: '',
            fevor: '',
            quantity: 0,
            month: moment().toDate(),
          };
          formRef?.current?.setFieldsValue(values);
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (value: Report.Settings.MonthlyPlanDto) => {
        const params = await props.onSubmitting();
        try {
          const monthlyPlanCreate: Report.Settings.MonthlyPlanCreate = {
            werks: value.werks as string,
            fevor: value.fevor as string,
            month: moment(value.month)?.format('YYYY-MM-DD HH:mm:ss'),
            quantity: value.quantity as number,
          };
          await serviceClient.monthlyPlanService.create(monthlyPlanCreate);
          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: '请输入生产管理员。' }]}
        />
        <ProFormDatePicker.Month
          name="month"
          label={'月份'}
          /*fieldProps={{
            format: 'YYYY-MM',
          }}*/
          width="md"
          rules={[{ required: true, message: '请输入月份。' }]}
        />
        <ProFormDigit
          width="md"
          name="quantity"
          label={'数量'}
          initialValue={0}
          rules={[{ required: true, message: '请输入数量。' }]}
        />
      </ProFormGroup>
    </ModalForm>
  );
};

export default CreateForm;
