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.ChouKongProcessKanbanSettingDto>;
  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 [deviceRowKeys, setDeviceRowKeys] = useState<React.Key[]>(() => []);

  const [deviceDataSource, setDeviceDataSource] = useState<
    Report.Settings.ChouKongDeviceProgressStepDto[]
  >(() => []);
  const [pmDataSource, setPmDataSource] = useState<
    Report.Settings.ChouKongProductionManagerProgressStepDto[]
  >(() => []);
  const [dataSource, setDataSource] = useState<Report.Settings.ChouKongProcessProgressStepDto[]>(
    () => [],
  );

  const editDeviceColumns: ProColumns<Report.Settings.ChouKongDeviceProgressStepDto>[] = [
    {
      title: '序号',
      dataIndex: 'ordinal',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '设备',
      dataIndex: 'device',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '工作单元',
      dataIndex: 'operationUnit',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
    },
  ];
  const editColumns: ProColumns<Report.Settings.ChouKongProcessProgressStepDto>[] = [
    {
      title: 'MES工序',
      dataIndex: 'extraTypeDes',
      valueType: 'text',
      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',
    },
  ];

  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.chouKongDeviceProgressStepList?.forEach((s) => {
            s.rowKey = s.id;
          });
          props.values.chouKongProcessProgressStepList?.forEach((s) => {
            s.type = s.typeId;
            s.rowKey = s.id;
          });
          props.values.chouKongProductionManagerProgressStepList?.forEach((s) => {
            s.rowKey = s.id;
          });
          setDeviceDataSource(props.values.chouKongDeviceProgressStepList || []);
          setPmDataSource(props.values.chouKongProductionManagerProgressStepList || []);
          setDataSource(props.values.chouKongProcessProgressStepList || []);
          setDeviceRowKeys(
            () => props.values.chouKongDeviceProgressStepList?.map((item) => item.rowKey) || [],
          );
          setEditableRowKeys(
            () => props.values.chouKongProcessProgressStepList?.map((item) => item.rowKey) || [],
          );
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          deviceDataSource.forEach((s) => {
            s.chouKongDeviceProgress = props.values.chouKongDeviceKanbanProgressId;
          });
          pmDataSource.forEach((s) => {
            s.chouKongProductionManagerProgress =
              props.values.chouKongProductionManagerKanbanProgressId;
          });
          dataSource.forEach((s) => {
            s.chouKongProcessProgress = props.values.chouKongProcessKanbanProgressId;
          });
          const updateDto: Report.Settings.ChouKongProcessKanbanSettingUpdate = {
            id: props.values.id || '',
            kanbTitle: formData.kanbTitle,
            werks: formData.werks,
            standardDays: formData.standardDays,
            beyondDays: formData.beyondDays,
            chouKongDeviceKanbanProgressUpdate: {
              id: props.values.chouKongDeviceKanbanProgressId || '',
              chouKongDeviceProgressStepUpdates: deviceDataSource,
            },
            chouKongProductionManagerKanbanProgressUpdate: {
              id: props.values.chouKongProductionManagerKanbanProgressId || '',
              chouKongProductionManagerProgressStepUpdates: pmDataSource,
            },
            chouKongProcessKanbanProgressUpdate: {
              id: props.values.chouKongProcessKanbanProgressId || '',
              chouKongProcessProgressStepUpdates: dataSource,
            },
            ...formData,
          };
          await serviceClient.chouKongProcessKanbanSettingService.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="standardDays"
          label={'标准加工天数'}
          width="md"
          rules={[{ required: true }]}
        />
        <ProFormText
          name="beyondDays"
          label={'超期天数N'}
          width="md"
          rules={[{ required: true }]}
        />
      </ProFormGroup>

      <ProForm.Item label="添加MES工序数据列" name="dataSource" trigger="outputOnValuesChange">
        <EditableProTable<Report.Settings.ChouKongProcessProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editColumns}
          value={dataSource}
          //onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            position: 'top',
            record: () => ({
              rowKey: Date.now().toString(),
              id: '',
              code: '',
              name: '',
              type: 1,
              werks: '',
              fevor: '',
              ordinal: 0,
              extraTypeDes: '',
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys: editableKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProForm.Item>
      <ProForm.Item
        label="添加设备与MES工作单元映射数据列"
        name="deviceDataSource"
        trigger="deviceOnValuesChange"
      >
        <EditableProTable<Report.Settings.ChouKongDeviceProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editDeviceColumns}
          value={deviceDataSource}
          //onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            position: 'top',
            record: () => ({
              rowKey: Date.now().toString(),
              id: '',
              device: '',
              operationUnit: '',
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys: deviceRowKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setDeviceDataSource(recordList);
            },
            onChange: setDeviceRowKeys,
          }}
        />
      </ProForm.Item>
    </DrawerForm>
  );
};

export default EditForm;
