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/kanban/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 [dataSource, setDataSource] = useState<KANBAN.Settings.ProgressStepDto[]>(() => []);

  const editColumns: ProColumns<KANBAN.Settings.ProgressStepDto>[] = [
    {
      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: 'MES入库', value: 2 },
          { label: '手工导入', value: 3 },
        ];
        return result;
      },
    },
    {
      title: 'MES工序',
      dataIndex: 'extraTypeDes',
      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: KANBAN.Settings.ProductionProgressKanbanSettingCreate = {
            subTitle1: formData.subTitle1,
            subTitle2: formData.subTitle2,
            werks: formData.werks,
            fevor: formData.fevor,
            sgNoSourceType: formData.sgNoSourceType,
            progressCreate: {
              stepsCreate: dataSource,
            },
          };
          await serviceClient.productProgressSettingService.create(createDto);
          await props.onSuccess(params);
          setDataSource([]);
          setEditableRowKeys([]);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText name="subTitle1" label={'车间名称'} width="md" rules={[{ required: true }]} />
        <ProFormText name="subTitle2" label={'产品名称'} width="md" rules={[{ required: true }]} />
        <ProFormText
          name="werks"
          label={'工厂'}
          width="md"
          rules={[{ required: true, message: '请输入生产管理员。' }]}
        />
        <ProFormText
          name="fevor"
          label={'生产管理员'}
          width="md"
          rules={[{ required: true, message: '请输入生产管理员。' }]}
        />
      </ProFormGroup>
      <ProForm.Item label="添加数据列" name="dataSource" trigger="onValuesChange">
        <EditableProTable<KANBAN.Settings.ProgressStepDto>
          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,
              fevor: '',
              ordinal: 0,
              extraTypeDes: '',
            }),
          }}
          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 CreateForm;
