import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { DrawerForm, ProFormDatePicker, 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.GaoYaProcessDataDto>;
  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 formRef = useRef<ProFormInstance>();
  return (
    <DrawerForm
      formRef={formRef}
      title="编辑抽空工序看板配置"
      width="900px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.resetFields();
          Reflect.set(props.values, 'date', moment(props.values.date));
          formRef?.current?.setFieldsValue({ ...props.values });
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          const updateDto: Report.Settings.GaoYaProcessDataUpdate = {
            id: props.values.id || '',
            operationName: formData.operationName,
            date: formData.date,
            type: formData.type,
            planNumber: formData.planNumber,
            actNumber: formData.actNumber,
            qiFangNo: formData.qiFangNo,
            ...formData,
          };
          await serviceClient.gaoYaProcessDataService.update(updateDto);
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText
          name="operationName"
          label={'工序名称'}
          width="md"
          rules={[{ required: true }]}
        />
        <ProFormDatePicker name="date" label={'日期'} width="md" rules={[{ required: true }]} />
        <ProFormText name="type" label={'类别'} width="md" rules={[{ required: true }]} />
        <ProFormText
          name="planNumber"
          label={'计划完工数量'}
          width="md"
          rules={[{ required: true }]}
        />
        <ProFormText
          name="actNumber"
          label={'实际完工数量'}
          width="md"
          rules={[{ required: true }]}
        />
        <ProFormText name="qiFangNo" label={'漆房编号'} width="md" rules={[{ required: true }]} />
      </ProFormGroup>
    </DrawerForm>
  );
};

export default EditForm;
