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 CreateFormProps = {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSubmitting: () => Promise<any>;
  onSuccess: (params: any) => Promise<void>;
  onError: (params: any, error: unknown) => Promise<void>;
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [editableKeys, setEditableRowKeys] = 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();
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          const createDto: Report.Settings.ProductionComprehensiveKanbanSettingCreate = {
            kanbTitle: formData.kanbTitle,
            werks: formData.werks,
            productDeviceException: formData.productDeviceException,
            failureRateProgressCreate: {
              failureRateProgressStepsCreate: failureDataSource,
            },
            outputProgressCreate: {
              outputProgressStepsCreate: outputDataSource,
            },
            processPMProgressCreate: {
              processPMProgressStepCreates: pmDataSource,
            },
          };
          await serviceClient.productionComprehensiveKanbanSettingService.create(createDto);
          await props.onSuccess(params);
          setFailureDataSource([]);
          setOutputDataSource([]);
          setPmDataSource([]);

          setEditableRowKeys([]);
          setPmEditableRowKeys([]);
          setFailureEditableRowKeys([]);
        } 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: editableKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record);
              console.log(recordList);
              setOutputDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </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 CreateForm;
