import React, { useRef, useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { DrawerForm, ProFormGroup, ProFormText } from '@ant-design/pro-form';
import ProForm from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import serviceClient from '@/services/report/settings/index';

export type EditFormProps = {
  values: Partial<Report.Settings.HjKanbanSettingDto>;
  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>();
  const [pmEditableKeys, setPmEditableRowKeys] = useState<React.Key[]>(() => []);
  const [pmDataSource, setPmDataSource] = useState<
    Report.Settings.HjProductionManagerProgressStepDto[]
  >(() => []);

  const pmEditColumns: ProColumns<Report.Settings.HjProductionManagerProgressStepDto>[] = [
    {
      title: '工厂',
      dataIndex: 'werks',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '生产管理员',
      dataIndex: 'fevor',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
    },
  ];
  return (
    <DrawerForm
      formRef={formRef}
      title="编辑焊接工序看板配置"
      width="900px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.resetFields();
          formRef?.current?.setFieldsValue({ ...props.values });
          props.values.hjProductionManagerProgressStepList?.forEach((s) => {
            s.rowKey = s.id;
          });
          setPmDataSource(props.values.hjProductionManagerProgressStepList || []);
          setPmEditableRowKeys(
            () =>
              props.values.hjProductionManagerProgressStepList?.map((item) => item.rowKey) || [],
          );
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          pmDataSource.forEach((s) => {
            s.hjProductionManagerProgress = props.values.hjProductionManagerKanbanProgressId;
          });
          const updateDto: Report.Settings.HjKanbanSettingUpdate = {
            id: props.values.id || '',
            kanbTitle: formData.kanbTitle,
            werks: formData.werks,
            hjProductionManagerKanbanProgressUpdate: {
              id: props.values.hjProductionManagerKanbanProgressId || '',
              hjProductionManagerProgressStepUpdates: pmDataSource,
            },
          };
          await serviceClient.hjKanbanSettingService.update(updateDto);
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText name="kanbTitle" label={'看板标题'} width="md" rules={[{ required: true }]} />
        <ProFormText name="werks" label={'工厂'} width="md" rules={[{ required: true }]} />
      </ProFormGroup>
      <ProForm.Item label="生产管理员" name="pmDataSource" trigger="pmOnValuesChange">
        <EditableProTable<Report.Settings.ProductionManagerProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={pmEditColumns}
          value={pmDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            position: 'top',
            record: () => ({
              rowKey: Date.now().toString(),
              id: '',
              werks: '',
              fevor: '',
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys: pmEditableKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              setPmDataSource(recordList);
            },
            onChange: setPmEditableRowKeys,
          }}
        />
      </ProForm.Item>
    </DrawerForm>
  );
};

export default EditForm;
