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.ProductionComprehensiveKanbanSettingDto>;
  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 [outputEditableKeys, setOutputEditableRowKeys] = useState<React.Key[]>(() => []);
  const [failureEditableRowKeys, setFailureEditableRowKeys] = useState<React.Key[]>(() => []);
  const [pmEditableRowKeys, setPmEditableRowKeys] = useState<React.Key[]>(() => []);

  const [failureDataSource, setFailureDataSource] = useState<
    Report.Settings.ProcessFailureRateProgressStepDto[]
  >(() => []);
  const [outputDataSource, setOutputDataSource] = useState<
    Report.Settings.ProcessOutputProgressStepDto[]
  >(() => []);
  const [pmDataSource, setPmDataSource] = useState<Report.Settings.ProcessPMProgressStepDto[]>(
    () => [],
  );

  const editFailureColumns: ProColumns<Report.Settings.ProcessFailureRateProgressStepDto>[] = [
    {
      title: '编码',
      dataIndex: 'code',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '序号',
      dataIndex: 'ordinal',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        const result = [
          { label: 'MES工序', value: 1 },
          { label: '手工导入', value: 3 },
        ];
        return result;
      },
    },
    {
      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',
    },
  ];
  const editOutputColumns: ProColumns<Report.Settings.ProcessOutputProgressStepDto>[] = [
    {
      title: '编码',
      dataIndex: 'code',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '序号',
      dataIndex: 'ordinal',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        const outputResult = [
          { label: 'MES工序', value: 1 },
          { label: '手工导入', value: 3 },
        ];
        return outputResult;
      },
    },
    {
      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',
    },
  ];
  const editPmColumns: ProColumns<Report.Settings.ProcessPMProgressStepDto>[] = [
    {
      title: '类型',
      dataIndex: 'pmType',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        const pmResult = [
          { label: '质量异常', value: 1 },
          { label: '焊接通过率', value: 2 },
          { label: '月度计划', value: 3 },
        ];
        return pmResult;
      },
    },
    {
      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.failureRateProgressStepList?.forEach((s) => {
            s.type = s.typeId;
            s.rowKey = s.id;
          });
          props.values.outputProgressStepList?.forEach((s) => {
            s.type = s.typeId;
            s.rowKey = s.id;
          });
          props.values.processPMProgressStepList?.forEach((s) => {
            s.pmType = s.pmTypeId;
            s.rowKey = s.id;
          });
          setFailureDataSource(props.values.failureRateProgressStepList || []);
          setOutputDataSource(props.values.outputProgressStepList || []);
          setPmDataSource(props.values.processPMProgressStepList || []);

          setFailureEditableRowKeys(
            () => props.values.failureRateProgressStepList?.map((item) => item.rowKey) || [],
          );
          setOutputEditableRowKeys(
            () => props.values.outputProgressStepList?.map((item) => item.rowKey) || [],
          );
          setPmEditableRowKeys(
            () => props.values.processPMProgressStepList?.map((item) => item.rowKey) || [],
          );
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          failureDataSource.forEach((s) => {
            s.processFailureRateProgress = props.values.processFailureRateProgressId;
          });
          outputDataSource.forEach((s) => {
            s.processOutputProgress = props.values.processOutputProgressId;
          });
          pmDataSource.forEach((s) => {
            s.processPMProgress = props.values.processPMProgressId;
          });
          const updateDto: Report.Settings.ProductionComprehensiveKanbanSettingUpdate = {
            id: props.values.id || '',
            kanbTitle: formData.kanbTitle,
            productDeviceException: formData.productDeviceException,
            werks: formData.werks,
            failureRateProgressUpdate: {
              id: props.values.processFailureRateProgressId || '',
              failureRateProgressStepsUpdate: failureDataSource,
            },
            outputProgressUpdate: {
              id: props.values.processOutputProgressId || '',
              outputProgressStepsUpdate: outputDataSource,
            },
            processPMProgressUpdate: {
              id: props.values.processPMProgressId || '',
              processPMProgressStepUpdates: pmDataSource,
            },
            ...formData,
          };
          await serviceClient.productionComprehensiveKanbanSettingService.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.ProcessPMProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editPmColumns}
          value={pmDataSource}
          //onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            position: 'top',
            record: () => ({
              rowKey: Date.now().toString(),
              id: '',
              pmType: 1,
              werks: '',
              fevor: '',
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys: pmEditableRowKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setPmDataSource(recordList);
            },
            onChange: setPmEditableRowKeys,
          }}
        />
      </ProForm.Item>
      <ProForm.Item
        label="添加工序产量数据列"
        name="outputDataSource"
        trigger="outputOnValuesChange"
      >
        <EditableProTable<Report.Settings.ProcessOutputProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editOutputColumns}
          value={outputDataSource}
          //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: outputEditableKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setOutputDataSource(recordList);
            },
            onChange: setOutputEditableRowKeys,
          }}
        />
      </ProForm.Item>
      <ProForm.Item
        label="添加工序未通过率数据列"
        name="failureDataSource"
        trigger="failureOnValuesChange"
      >
        <EditableProTable<Report.Settings.ProcessFailureRateProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editFailureColumns}
          value={failureDataSource}
          //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: failureEditableRowKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setFailureDataSource(recordList);
            },
            onChange: setFailureEditableRowKeys,
          }}
        />
      </ProForm.Item>
    </DrawerForm>
  );
};

export default EditForm;
