// 成品管理

import type { ActionType, EditableFormInstance, ProColumns } from '@ant-design/pro-components';
import { BetaSchemaForm, DragSortTable, EditableProTable, ProCard, ProForm, ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, TreeSelect, Select, Tag, Dropdown, Space, MenuProps, Spin, Row, Col, Card, Divider } from 'antd';
import { useEffect, useRef, useState } from 'react';
import finalInfoAPI from '@/api/finalService';
// 工艺服务
import finalMaterialAPI from '@/api/finalMaterial/service';
import productlineAPI from '@/api/productlineInfo/service';
import productlineInfoStepsAPI from '@/api/productlinesteps/service'
import finalCraftStepsAPI from '@/api/finalCraftSteps/service'

import { v4 as uuid } from 'uuid'
import DeviceInfoAPI from '@/api/DeviceInfo'
import DeviceProductAPI from '@/api/deviceInfo/services/deviceProduct';
import DeviceProductFunctionAPI from '@/api/deviceInfo/services/deviceProductFunction';
import MaterialAPI from '@/api/materialService';
// 无聊服务
import MaterialsInfoAPI from '@/api/materialService'
import { EditOutlined, PlusSquareOutlined, RedoOutlined } from '@ant-design/icons';
import styles from './index.less'
import line from '../productLine/line';
interface paramsType {
  paramType: string | number,
  paramName: string;
  paramUnit: string;
  paramCode: string;
}
const final = () => {
  const [formRef] = Form.useForm();
  const [lineFormRef] = Form.useForm();
  const [spinStatus, setSpinStatus] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const editactionformRef = useRef<EditableFormInstance>();
  const editactionRef = useRef<ActionType>();
  const [materiallist, setMateriallist] = useState<finalMaterialTypes.output[]>([]);
  const [selectMateriallist, setSelectMateriallist] = useState<finalMaterialTypes.output[]>([]);
  const [selectRowItem, setSelectRowItem] = useState<any>();

  //定于表单
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [typeForm] = Form.useForm();

  // 定义新增弹窗
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isModalOpen, setIsModalOpen] = useState(false);

  //  定义编辑弹窗
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const actionRef = useRef<ActionType>();

  // 定义title
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [modelTitle, setModelTitle] = useState<string>();

  const [peifangOpen, setPeifangOpen] = useState<boolean>();

  const [chaxianOpen, setChanxianOpen] = useState<boolean>();
  const [isLineStepOpen, setIsLineStepOpen] = useState<boolean>();
  //产线
  const [lineList, setLineList] = useState<any[]>([])
  const [finallineList, setFinalLineList] = useState<any[]>([])
  const [currentproductionline, setcurrentproductionline] = useState<any>();
  const [currentproductionProcess, setcurrentproductionProcess] = useState<any>();
  const [currentproductionDev,setcurrentproductionDev] = useState<any>();
  //获取产线工艺流程
  const [lineProcessList, setLineProcessList] = useState<any[]>([])
  const [selectLine, setSelectLine] = useState<number>()

  const [selectProcess, setSelectProcess] = useState<number>()
  //获取产线工艺所属设备
  const [lineProcessDevList, setLineProcessDevList] = useState<any[]>([])
  const [selectDev, setSelectDev] = useState(0)

  const [isSetpModalOpen, setIsSetpModalOpen] = useState(false);
  const [isSchemaModalOpen, setIsSchemaModalOpen] = useState(false);
  const [deviceParm, setDeviceParm] = useState<any>([]);
  const sortActionRef = useRef<ActionType>();
  const [stepTitle, setStepTitle] = useState<any>('步骤列表');
  const [stepparams, setStepparams] = useState<any>();
  const [deviceFun, setDeviceFun] = useState<deviceProductFunction.output[]>([]);
  const [dongtaiformRef] = Form.useForm();
  const [materialParmList, setMaterialParmList] = useState<any>();
  const processIdFlag = Form.useWatch('processId', typeForm);
  // 定义列表数据
  const columns: ProColumns<FinalTypes.Info>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
    },

    {
      title: '成品编号',
      dataIndex: 'code',
      width:120,
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '成品名称',
      dataIndex: 'name',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '已绑定产线',
      dataIndex: 'lineId',
      hideInSearch: true,
      ellipsis: true,
      valueType: 'select',
      request: async () => {
        const data: MyResponse.Content = await productlineAPI.selectlist()
        const chan: any[] = data.data;
        chan.map((item) => (
          item.label = item.value,
          item.value = item.key
        ))
        return chan;
      },
    },
    {
      title: '操作',
      valueType: 'option',

      key: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="primary" ghost

          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('成品编辑');
            const copyFormData = JSON.parse(JSON.stringify(record));
            copyFormData.state = copyFormData.state === '0';
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑成品
        </Button>,
        <Button key="peifang"
          type="primary" ghost

          onClick={async () => {


            setSpinStatus(true);
            const jsonData: finalMaterialTypes.queryParms = {
              finalId: record.id!,
            };
            setSelectRowItem(record);
            //根据工艺列表查询功能值
            finalMaterialAPI.List(jsonData)
              .then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  setMateriallist(res.data)
                  setPeifangOpen(true);
                }
                setSpinStatus(false)
              })
              .catch(() => {
                setPeifangOpen(false);
                setSpinStatus(false)
              });
          }}>
          配方设置
        </Button>
        ,
        <Button key="chanxian"
          type="primary" ghost
          onClick={async () => {
            setSelectRowItem(record);
            setChanxianOpen(true)
            const copyFormData = JSON.parse(JSON.stringify(record));
            lineFormRef.setFieldsValue(copyFormData);
          }}>
          绑定产线
        </Button>
        ,
        <Button disabled={record.lineId?.length == 0} key="chanxian"
          type="primary" ghost
          onClick={async () => {
            setIsLineStepOpen(true)
            setSelectRowItem(record);
            const b: any[] = []
            record.lineId!.map((item) => {
              b.push(lineList.find(x => x.key == item))
            })
            console.log(lineList);

            setFinalLineList(b)
            const copyFormData = JSON.parse(JSON.stringify(record));
            lineFormRef.setFieldsValue(copyFormData);


            finalMaterialAPI.List({finalId:record.id!})
            .then((res: MyResponse.Content) => {
              if (res.statusCode === 200) {
                res.data.map((item:any)=>(
                  item.value = item.id,
                  item.label=item.materialName
                ))
                console.log(res.data);
                
                setMaterialParmList(res.data)
              }
            })
          }}>
          设置工艺
        </Button>
        ,
        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {

            const EnablejsonData: FinalTypes.FinalInfoDelInput = {
              id: record.id,
              // name: '',
              // code: ''
            };

            finalInfoAPI.Del(EnablejsonData).then((r: MyResponse.Content) => {
              if (r.statusCode === 200) {
                message.success(r.statusCode === 200 ? '删除成功' : r.message);
                actionRef.current?.reload();
              }
            });
          }}
          onCancel={() => {
            message.info('已取消删除');
          }}
          okText="确认"
          cancelText="关闭"
        >
          <Button type="primary" danger ghost>删除</Button>
        </Popconfirm>,
      ],
    },
  ];


  const OnSubmit = async (values: FinalTypes.Info) => {

    if (values.id) {
      const response = await finalInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '修改失败');
      }
    } else {
      const response = await finalInfoAPI.Add(values);
      // console.log('response', response);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '添加失败');
      }
    }
  };

  useEffect(() => {
    productlineAPI.selectlist().then((res: MyResponse.Content) => {

      // const myData: any[] = [];
      if (res.statusCode === 200) {
        setLineList(res.data)
      }
    })
  }, [])
  //  定义工艺列表
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [formula, setformula] = useState([])



  // 定义配方列表
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [areas, setareas] = useState([])

  return (
    <>
      <ProTable<FinalTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        // 调用接口判断
        request={async (params = {}) => {
          const jsonData: FinalTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            code: params.code || ''
          };
          const response = await finalInfoAPI.PagedList(jsonData);
          if (response.statusCode === 200) {
            return {
              data: response.data.items,
              success: true,
              total: response.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: false
        }}
        dateFormatter="string"
        headerTitle="成品列表"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              typeForm.resetFields();
              setIsModalOpen(true);
              setModelTitle('新增成品');

            }}
          >
            新增成品
          </Button>,
        ]}




      />
      {/* 新增成品的model弹窗 */}
      <Modal
        maskClosable={false}
        key="01"
        width={800}
        title={<Tag color="#cd201f">{modelTitle}</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="finalForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        {/* 新增成品表单 */}

        <Form
          form={typeForm}
          name="basic"
          id="finalForm"

          labelCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          onFinish={OnSubmit}
          autoComplete="off"
        >
          <Form.Item label="id" name="id" hidden>
            <Input />
          </Form.Item>

          <Form.Item
            label="成品编码"
            name="code"
            rules={[{ required: true, message: '此项为必填项!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item name="name" label="成品名称" rules={[{ required: true, message: '此项为必填项' }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>


      <Modal
        maskClosable={false}
        key="02"
        width={1200}
        title="配置物料"
        open={peifangOpen}
        destroyOnClose
        onCancel={() => {
          setPeifangOpen(false);
          setMateriallist([]);
        }}
        onOk={() => {
          const list: finalMaterialTypes.addInput[] = JSON.parse(JSON.stringify(materiallist));
          list.map((item) => {
            item.finalId = selectRowItem.id;
          })
          finalMaterialAPI.BatchAdd(list).then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
              message.success("保存成功!");
              setPeifangOpen(false);
            } else {
              message.error("保存失败!");
            }
          });
        }}
      >
        <Spin spinning={spinStatus}>
          <ProCard>
            <div
              style={{
                maxWidth: 1200,
                margin: 'auto',
              }}
            >
              <EditableProTable<finalMaterialTypes.output>
                rowKey="id"
                controlled
                editableFormRef={editactionformRef}
                actionRef={editactionRef}
                columns={[
                  {
                    title: '物料名称',
                    dataIndex: 'materialId',
                    valueType: 'select',
                    ellipsis: true,
                    request: async () => {
                      const res: MyResponse.Content = await MaterialsInfoAPI.List();
                      const myData: any[] = [];
                      if (res.statusCode === 200) {
                        setSelectMateriallist(res.data)
                        res.data.map((item: MaterialsTypes.Info) => (
                          myData.push({
                            label: `${item.name}[${item.unit}]`,
                            value: item.id,
                          })
                        ))
                      }
                      return myData;
                    },
                    formItemProps: () => {
                      return {
                        rules: [{ required: true, message: '此项为必填项' }]
                      };
                    },
                  },
                  {
                    title: '重量',
                    dataIndex: 'weight',
                    valueType: 'text',
                    ellipsis: true,
                    formItemProps: () => {
                      return {
                        rules: [{ required: true, message: '此项为必填项' }],
                      };
                    },
                  },
                  {
                    title: '重量误差(±)',
                    dataIndex: 'errorWeight',
                    valueType: 'text',
                    ellipsis: true,
                    formItemProps: () => {
                      return {
                        rules: [{ required: true, message: '此项为必填项' }],
                      };
                    },
                  },
                  {
                    title: '操作',
                    valueType: 'option',
                    render: (_, row) => [
                      <Button
                        type='primary' ghost
                        key="edit"
                        onClick={() => {
                          console.log(row);
                          editactionRef.current?.startEditable(row.id);
                        }}
                      >
                        编辑原料
                      </Button>,

                    ],
                  },
                ]}
                value={materiallist}

                recordCreatorProps={{
                  record: () => (
                    {
                      id: Date.now().toString(),
                      materialId: '',
                      finalId: '',
                      weight: '',
                    })
                  ,
                }
                }
                editable={{
                  form: formRef,
                  type: 'single',
                  onValuesChange: (record, recordList: finalMaterialTypes.output[]) => {
                    console.log(selectMateriallist);
                    if (!recordList) {
                      materiallist.push(record);
                      setMateriallist(materiallist);
                    } else {
                      setMateriallist(recordList);
                    }
                    console.log('materiallist', materiallist);

                  },
                  actionRender: (row, _, dom) => {
                    return [dom.delete, dom.save, dom.cancel];
                  },
                }}
              />
            </div>
          </ProCard>
        </Spin>

      </Modal>

      <Modal
        maskClosable={false}
        key="03"
        width={500}
        title="绑定产线"
        open={chaxianOpen}
        destroyOnClose
        onCancel={() => {
          setChanxianOpen(false);

        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setChanxianOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="bindlineForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form id='bindlineForm' form={lineFormRef} onFinish={(values) => {
          finalInfoAPI.BindLine({ finalId: selectRowItem.id, LineId: values.lineId }).then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
              message.info('操作成功!');
              setChanxianOpen(false)
              sortActionRef.current?.reload()
            } else {
              message.error('操作失败!');
            }
          })
        }}>
          <Form.Item label='请选择产线' name='lineId'>
            <Select placeholder='请选择产线' mode='multiple' onChange={(v) => {
              //根据产线id获取工序
              productlineInfoStepsAPI.List({ lineId: v }).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  setLineProcessList(res.data)
                } else {
                  setLineProcessList([])
                }
              })

            }} style={{ width: 375 }}>
              {
                lineList.map((item: MySelectType.Select) => {
                  return <Select.Option value={item.key} key={item.key}>
                    <span>{item.value}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item>
        </Form>

      </Modal>
      <Modal title='设置工艺' open={isLineStepOpen} width={1500} onCancel={() => setIsLineStepOpen(false)}>
        <Divider />
        <Row wrap={false} gutter={[10, 10]}>
          <Col flex={0.1}>
            <Card title={'已绑定产线'}>
              <div className={styles.tag}>
                {finallineList.map((item, index) => (
                  <div key={index} onClick={() => {
                    // 当前选中的产线
                    console.log(item);
                    setcurrentproductionline(item);
                    setSelectLine(index);
                    // setStepparams({lineId:item.key})
                    productlineInfoStepsAPI.List({ lineId: item.key }).then((res: MyResponse.Content) => {
                      if (res.statusCode === 200) {
                        setLineProcessList(res.data);
                      }
                    })
                  }} className={`${styles.tag_item} ${index === selectLine ? styles.tag_item_activeItem : ''}`}>
                    <Space size="middle">
                      <div >{item.value}</div>
                    </Space>
                    <div className={index === selectLine ? styles.tag_item_active : ''}></div>
                  </div>
                ))}
              </div>
            </Card>
          </Col>
          <Col flex={0.1}>
            <Card title={'产线工艺路线'}>
              <div className={styles.tag}>
                {lineProcessList.map((item, index) => (
                  <div key={index} onClick={() => {
                    // 当前选中的产线
                    console.log('产线工艺路线',item);
                    setSelectProcess(index)
                    setcurrentproductionProcess(item)
                    productlineInfoStepsAPI.Devicelist({ stepId: item.id }).then((res: MyResponse.Content) => {
                      if (res.statusCode === 200) {
                        setLineProcessDevList(res.data);
                      }
                    })
                  }} className={`${styles.tag_item} ${index === selectProcess ? styles.tag_item_activeItem : ''}`}>
                    <Space size="middle">
                      <div >{item.processName}</div>
                    </Space>
                    <div className={index === selectProcess ? styles.tag_item_active : ''}></div>
                  </div>
                ))}
              </div>
            </Card>
          </Col>
          <Col flex={0.1}>
            <Card title={'设备列表'}>
              <div className={styles.tag}>
                {lineProcessDevList.map((item, index) => (
                  <div key={index} onClick={() => {
                    setcurrentproductionDev(item.deviceId)
                    // 当前选中的产线
                    const jsondata ={
                        lineId:currentproductionline.key,
                        deviceId:item.deviceId,
                        finalId:selectRowItem.id,
                        productLineStepsId:currentproductionProcess.id
                    }
                    console.log('11111',jsondata);
                    // setSelectLine(index);
                    setSelectDev(index)
                    setStepparams(jsondata)
                    // productlineInfoStepsAPI.Devicelist({ stepId: item.id }).then((res: MyResponse.Content) => {
                    //   if (res.statusCode === 200) {
                    //     setLineProcessDevList(res.data);
                    //   }
                    // })
                  }} className={`${styles.tag_item} ${index === selectDev ? styles.tag_item_activeItem : ''}`}>
                    <Space size="middle">
                      <div >{item.deviceName}</div>
                    </Space>
                    <div className={index === selectDev ? styles.tag_item_active : ''}></div>
                  </div>
                ))}
              </div>
            </Card>
          </Col>
          <Col flex={1}>
            <Card title={'工艺流程'}>
              <DragSortTable<CraftsTypes.Info>
                toolBarRender={() => [
                  <Button
                    type="primary"
                    disabled={currentproductionline == null}
                    onClick={() => {

                      typeForm.resetFields();
                      setIsSetpModalOpen(true);
                    }}
                  >
                    添加步骤
                  </Button>,
                  <Button
                  type="primary"
                  disabled={currentproductionline == null}
                  onClick={() => {

                    typeForm.resetFields();
                    setIsSetpModalOpen(true);
                  }}
                >
                  同步同类设备
                </Button>
                ]}
                actionRef={sortActionRef}
                headerTitle={'步骤列表'}
                columns={[
                  {
                    title: '步骤序号',
                    dataIndex: 'step',
                    align: 'center',
                    hideInSearch: true,
                    render: (dom, rowData, index) => {
                      return (
                        <span className="customRender">{`${index + 1}`}</span>
                      );
                    },
                  },
                  {
                    title: '步骤描述',
                    dataIndex: 'description',
                    align: 'center',
                    hideInSearch: true
                  },
                  {
                    title: '产线工序',
                    dataIndex: 'productLineStepsName',
                    align: 'center',
                    hideInSearch: true
                  }
                  ,
                  {
                    title: '设备类型',
                    dataIndex: 'deviceTypeName',
                    align: 'center',
                    hideInSearch: true
                  },
                  {
                    title: '设备名称',
                    dataIndex: 'deviceName',
                    align: 'center',
                    hideInSearch: true
                  },
                  {
                    title: '功能',
                    dataIndex: 'deviceProductFunctionName',
                    align: 'center',
                    hideInSearch: true,
                  },
                  {
                    title: '操作',
                    align: 'center',

                    valueType: 'option',

                    key: 'option',
                    render: (_, record, index, action) => [
                      <Space size="middle">
                        <Button
                          type='primary' ghost
                          onClick={async () => {
                            setIsSchemaModalOpen(true)
                            setDeviceParm([]);
                            setSpinStatus(true)
                            const copyFormData = JSON.parse(JSON.stringify(record));
                            formRef.setFieldsValue(copyFormData);
                            console.log('record', record);

                            const jsonData: deviceProductFunction.queryParms = {
                              deviceProductId: selectRowItem?.deviceProductId
                            };
                            DeviceProductFunctionAPI.List(jsonData).then((res: MyResponse.Content) => {
                              if (res.succeeded) {
                                setDeviceFun(res.data);
                                setTimeout(() => {
                                  const out = res.data.find((x:any) => x.id === record.deviceProductFunctionId);
                                  if (out?.params) {
                                    const b = JSON.parse(out?.params);
                                    console.log(b);
                                    const c: any[] = [];
                                    b.map((paramsItem: paramsType) => {
                                      const element = {
                                        title: paramsItem.paramName,
                                        dataIndex: paramsItem.paramCode,
                                        width: 'md',
                                        renderFormItem: (dom:any, rowData:any, index:any) => {
                                          return (
                                            paramsItem.paramType
                                              === 1 ? <Select mode='multiple' options={materialParmList}></Select> : <Input addonAfter={paramsItem.paramUnit} />
                                          );
                                        },
                                        colProps: {
                                          xs: 24,
                                          md: 12,
                                        },
                                      }
                                      c.push(element)
                                    })
                                    setDeviceParm(c);
                                  }
                                  if (dongtaiformRef) {
                                    if (record.params) {
                                      const element = JSON.parse(record.params!)
                                      dongtaiformRef.setFieldsValue(element)
                                    }
                                  }
                                  setSpinStatus(false)
                                }, 200);
                              }
                            })
                          }}
                        >
                          配置设备参数
                        </Button>
                        <Popconfirm
                          key={uuid()}
                          title="确定要删除此条数据吗？"
                          onConfirm={() => {
                            const delData: CraftsTypes.Info = {
                              id: record.id,
                              step: 0,
                              craftId: '',
                              deviceProductId: ''
                            };
                            finalCraftStepsAPI.Del(delData).then((r) => {
                              if (r.statusCode === 200) {
                                message.success(r.statusCode === 200 ? '删除成功' : r.message);
                                action?.reload();
                              }
                            });
                          }}
                          onCancel={() => {
                            message.info('已取消删除');
                          }}
                          okText="确认"
                          cancelText="关闭"
                        >
                          <Button type='primary' danger ghost>删除</Button>
                        </Popconfirm>
                      </Space>
                    ],
                  },
                ]}
                rowKey="step"
                search={false}
                pagination={{ pageSize: 100, showSizeChanger: false }}

                params={stepparams}
                request={async (params = {}) => {
                  if (!params.deviceId) {
                    return {
                      data: [],
                      success: false,
                      total: 0,
                    };
                  }
                  const jsonData: finalCraftStepsTypes.queryParms = {
                    lineId: params.lineId,
                    finalId:params.finalId,
                    deviceId:params.deviceId,
                    productLineStepsId:params.productLineStepsId
                  };
                  const response = await finalCraftStepsAPI.List(jsonData);
                  if (response.statusCode === 200) {
                    return {
                      data: response.data,
                      success: true,
                      total: response.data,
                    };
                  } else {
                    return {
                      data: [],
                      success: false,
                    };
                  }
                }}
                dragSortKey="step"
                onDragSortEnd={(beforeIndex: number, afterIndex: number, newDataSource: any[]) => {

                  console.log('newDataSource', newDataSource);

                  // 模拟将排序后数据发送到服务器的场景
                  // remoteData = newDataSource;
                  // 请求成功之后刷新列表
                  newDataSource.map((item, index) => {
                    item.step = index + 1;
                  })
                  console.log('排序后的数据', newDataSource);
                  finalCraftStepsAPI.BatchUpdate(newDataSource).then((res: MyResponse.Content) => {
                    if (res.data) {
                      sortActionRef.current?.reload();
                      message.success('修改列表排序成功');
                    }
                  });

                }}
              />
            </Card>
          </Col>
        </Row>
      </Modal>
      {
        /*
        * 配置设备参数弹框
        */}
      <Modal
        maskClosable={false}
        destroyOnClose
        width={800}
        title={<Tag color="#cd201f"> 配置设备参数信息</Tag>}
        open={isSchemaModalOpen}
        onCancel={() => {
          setIsSchemaModalOpen(false);
          dongtaiformRef.resetFields()
          setDeviceParm([]);
        }}
        footer={false}
      >
        <Spin spinning={spinStatus}>
          <Form
            form={formRef}
            name="basic1"
            id="myForm1111"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 12 }}
            autoComplete="off"
          >
            <Form.Item label="id" name="id" hidden>
              <Input />
            </Form.Item>
            <Form.Item
              label="设备功能信息"
              name="deviceProductFunctionId"
              rules={[{ required: true, message: '此项必填！' }]}
            >
              <Select placeholder='请选择功能'  onChange={(value: string, index) => {

                const out = deviceFun.find(x => x.id === value);
                if (out?.params) {
                  const b = JSON.parse(out?.params);
                  console.log(b);
                  const c: any[] = [];
                  b.map((paramsItem: paramsType) => {
                    const element = {
                      title: paramsItem.paramName,
                      dataIndex: paramsItem.paramCode,
                      width: 'md',
                      renderFormItem: (dom:any, rowData:any, index:any) => {
                        return (
                          paramsItem.paramType
                            === 1 ? <Select mode='multiple' options={materialParmList}></Select> : <Input placeholder='请输入' addonAfter={paramsItem.paramUnit} />
                        );
                      },
                      colProps: {
                        xs: 24,
                        md: 12,
                      },
                    }
                    c.push(element)
                  })
                  setDeviceParm(c);
                } else {
                  setDeviceParm([]);
                }
              }} >
                {
                  deviceFun.map((item: deviceProductFunction.output) => {
                    return <Select.Option value={item.id} key={item.id}>
                      <span>{item.name}</span>
                    </Select.Option>
                  })
                }
              </Select>
            </Form.Item>
          </Form>
          <Card>
            <BetaSchemaForm<any>
              trigger={<a>点击我</a>}
              rowProps={{
                gutter: [16, 16],
              }}
              colProps={{
                span: 12,
              }}
              grid={true}
              onFinish={async (values) => {
                console.log(formRef.getFieldsValue());

                const froms: CraftsTypes.craftsInfoOutput = formRef.getFieldsValue()
                if (!froms.deviceProductFunctionId) {
                  message.error("请选择设备产品功能");
                  return;
                }
                console.log('froms',froms);

                const jsonData: finalCraftStepsTypes.updateInput = {
                  id: froms.id,
                  deviceProductFunctionId: froms.deviceProductFunctionId,
                  params: JSON.stringify(values),
                  deviceId: ''
                }
                finalCraftStepsAPI.Update(jsonData).then((res: MyResponse.Content) => {
                  if (res.data) {
                    sortActionRef.current?.reload();
                    message.success("成功！");
                    setIsSchemaModalOpen(false)
                  }
                });
              }}
              columns={deviceParm}
              form={dongtaiformRef}
            />
          </Card>
        </Spin>
      </Modal>
      <Modal
        maskClosable={false}
        destroyOnClose
        width={800}
        open={isSetpModalOpen}
        onCancel={() => {
          setIsSetpModalOpen(false);
        }}
        footer={false}
        title={<Tag color="#cd201f"> 添加步骤 </Tag>}
      >
        <ProForm form={typeForm} onFinish={async (value: any) => {
          // value.craftId = stepparams.craftId;
         
            const jsonData:finalCraftStepsTypes.addInput =  {
              productLineStepsId:currentproductionProcess.id,
              description: value.description,
              deviceId: currentproductionDev,
              finalId : selectRowItem.id,
              deviceProductFunctionId: '',
              params: ''
            }
            console.log('11111111',jsonData);
            finalCraftStepsAPI.Add(jsonData).then((res:MyResponse.Content)=>{
            if (res.statusCode===200) {
              message.info('添加成功');
              setIsSetpModalOpen(false);
              sortActionRef.current?.reload()
              
            }else{
              message.error(res.errors);
            }
           })
        }}>
          {/* <Form.Item label="产线工艺路线" name="productLineStepsId"  rules={[{ required: true, message: '此项为必填项!' }]}>
            <Select onChange={(v: string) => {
              productlineInfoStepsAPI.Devicelist({ stepId: v! }).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  setLineProcessDevList(res.data);
                }
              })

            }} placeholder='请选择工艺' style={{ width: 375 }}>
              {
                lineProcessList.map((item: productlinestepsTypes.output) => {
                  return <Select.Option value={item.id} key={item.id}>
                    <span>{item.processName}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item label="设备" name="deviceId"  rules={[{ required: true, message: '此项为必填项!' }]}>
            <Select onChange={(v: processType.output) => {


            }} placeholder='请选择设备' style={{ width: 375 }}>
              {
                lineProcessDevList.map((item: any) => {
                  return <Select.Option value={item.deviceId} key={item.deviceId}>
                    <span>{item.deviceName}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item> */}

          <Form.Item label="步骤说明" name="description">
            <Input></Input>
          </Form.Item>
        </ProForm>
      
      </Modal>
    </>


  );
};

export default final;
