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.MaterialComprehensiveKanbanSettingDto>;
  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 [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const [dataSource, setDataSource] = useState<Report.Settings.PartProgressStepDto[]>(() => []);

  const [pmEditableKeys, setPmEditableRowKeys] = useState<React.Key[]>(() => []);
  const [pmDataSource, setPmDataSource] = useState<
    Report.Settings.ProductionManagerProgressStepDto[]
  >(() => []);

  const editColumns: ProColumns<Report.Settings.PartProgressStepDto>[] = [
    {
      title: '车间',
      dataIndex: 'workShop',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        const result = [
          { label: '中压产线', value: '中压产线' },
          { label: '低温车箱产线', value: '低温车箱产线' },
          { label: '低温罐产线', value: '低温罐产线' },
          { label: '高压产线', value: '高压产线' },
        ];
        return result;
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      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',
    },
  ];
  const pmEditColumns: ProColumns<Report.Settings.ProductionManagerProgressStepDto>[] = [
    {
      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.progressStepList?.forEach((s) => {
            s.rowKey = s.id;
          });
          props.values.productionManagerProgressStepList?.forEach((s) => {
            s.rowKey = s.id;
          });
          setDataSource(props.values.progressStepList || []);
          setEditableRowKeys(() => props.values.progressStepList?.map((item) => item.rowKey) || []);

          setPmDataSource(props.values.productionManagerProgressStepList || []);
          setPmEditableRowKeys(
            () => props.values.productionManagerProgressStepList?.map((item) => item.rowKey) || [],
          );
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          dataSource.forEach((s) => {
            s.partProgress = props.values.partProgressId;
          });
          pmDataSource.forEach((s) => {
            s.productionManagerProgress = props.values.productionManagerKanbanProgressId;
          });
          const updateDto: Report.Settings.MaterialComprehensiveKanbanSettingUpdate = {
            id: props.values.id || '',
            kanbTitle: formData.kanbTitle,
            werks: formData.werks,
            productDeviceException: formData.productDeviceException,
            productionManagerKanbanProgressUpdate: {
              id: props.values.productionManagerKanbanProgressId || '',
              productionManagerProgressStepUpdates: pmDataSource,
            },
            progressUpdate: {
              id: props.values.partProgressId || '',
              steps: dataSource,
            },
          };
          await serviceClient.materialComprehensiveKanbanSettingService.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 }]} />
        <ProFormText
          name="productDeviceException"
          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>

      <ProForm.Item label="零部件进度配置" name="dataSource" trigger="onValuesChange">
        <EditableProTable<Report.Settings.PartProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editColumns}
          value={dataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            position: 'top',
            record: () => ({
              rowKey: Date.now().toString(),
              id: '',
              workShop: '',
              werks: '',
              fevor: '',
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProForm.Item>
    </DrawerForm>
  );
};

export default EditForm;
