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/report/settings/index';
import moment from 'moment';

export type EditFormProps = {
  values: Partial<Report.Settings.MonthlyPlanDto>;
  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.report.monthlyPlan.editForm.title',
        defaultMessage: '编辑月计划',
      })}
      width="740px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.setFieldsValue(props.values);
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (value: Report.Settings.MonthlyPlanDto) => {
        const params = await props.onSubmitting();
        try {
          const monthlyPlanUpdate: Report.Settings.MonthlyPlanUpdate = {
            id: props.values.id as string,
            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.update(monthlyPlanUpdate);
          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>
    </DrawerForm>
  );
};

export default EditForm;
