// 成品管理

import type { ActionType, EditableFormInstance, ProColumns } from '@ant-design/pro-components';
import { BetaSchemaForm, CheckCard, 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, Radio, List, Badge, Empty, Flex } 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 DeviceProductFunctionAPI from '@/api/deviceInfo/services/deviceProductFunction';
// 无聊服务
import MaterialsInfoAPI from '@/api/materialService'
import { EditOutlined, LeftCircleOutlined, PlusSquareOutlined, RedoOutlined } from '@ant-design/icons';
import styles from './index.less'
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 [isConfigDevOpen, setisConfigDevOpen] = useState<boolean>(false);
  const [m_device, setM_device] = useState<any[]>([])
  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',
      hideInSearch: false,
    },
    {
      title: '成品名称',
      dataIndex: 'name',
      hideInSearch: false,
    },
    {
      title: '已绑定产线',
      dataIndex: 'lineId',
      hideInSearch: 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',
      fixed: 'right',
      key: 'option',
      render: (_, record) => [

        <Button key="peifang"
          type="primary" size='small'

          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="edit"
          type="primary" size='small'

          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('成品编辑');
            const copyFormData = JSON.parse(JSON.stringify(record));
            copyFormData.state = copyFormData.state === '0';
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </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 size='small'>删除</Button>
        </Popconfirm>,
      ],
    },
    {
      title: '设计操作',
      valueType: 'option',
      fixed: 'right',
      key: 'option',
      render: (_, record) => [
        <Button key="chanxian"
          type="primary" size='small'
          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" size='small'
          onClick={async () => {
            setIsLineStepOpen(true)
            setSelectRowItem(record);
            setSelectLine(0);
            // const b: any[] = []
            // record.lineId!.map((item) => {
            //   b.push(lineList.find(x => x.key == item))
            // })
            // console.log(lineList);

            finalInfoAPI.LineList(record.id!).then((res: MyResponse.Content) => {
              if (res.statusCode === 200) {
                console.log(res.data);

                setFinalLineList(res.data)
                UpdateGY(res.data[0].key, record?.id!)
              }
            })
            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>

      ],
    },
  ];


  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([])


  const UpdateGY = (lineId: string, finalId: string) => {
    productlineInfoStepsAPI.List({ lineId: lineId, finalId: finalId }).then((res: MyResponse.Content) => {
      if (res.statusCode === 200) {
        setLineProcessList(res.data);
      }
    })
  }

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

  return (
    <>
      {
        !isLineStepOpen ?
          <ProTable<FinalTypes.Info>
            key="myTable"
            columns={columns}
            actionRef={actionRef}
            cardBordered
            bordered
            scroll={{ x: true }}
            rowClassName={(record: any, index: number, indent: number) => {
              if (index % 2 === 0) {
                return ''; // 偶数行的类名
              } else {
                return 'even-row-background'; // 奇数行的类名
              }
            }}
            // 调用接口判断
            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>,
            ]}
          />
          :
          <Card size="default" title={'当前配置成品工艺:  ' + selectRowItem?.name} styles={{ header: { textAlign: 'center', margin: 'auto', fontSize: '22px' } }} extra={
            currentproductionline && lineProcessList.length>0 ?
              <Popconfirm title="确定要保存当前配置？" onConfirm={(i) => {

                finalInfoAPI.Saveconfigstatus({ LineId: currentproductionline.key, finalId: selectRowItem.id }).then((res: MyResponse.Content) => {
                  if (res.statusCode === 200) {
                    message.success('保存成功!');
                    setTimeout(() => {
                      setIsLineStepOpen(false);
                    }, 1000);
                  } else {
                    message.error(res.errors || res.message);
                  }
                })
              }} onCancel={() => {
                message.info('未保存配置');
                setIsLineStepOpen(false);
              }} > <Button style={{ position: 'absolute', top: '20px', right: '20px' }} icon={<LeftCircleOutlined />} type='primary' size='small'>返回</Button>
              </Popconfirm> : <Button
                onClick={() => {
                  setIsLineStepOpen(false);
                }}
                style={{ position: 'absolute', top: '20px', right: '20px' }} icon={<LeftCircleOutlined />} type='primary' size='small'>返回</Button>
          }>
            <Divider />

            <Card title={'选择产线'}>
              <div className={styles.tag}>
                {finallineList.map((item, index) => (
                  <Badge.Ribbon text={item.status == '0' ? '未配置' : '已配置'} color={item.status == '0' ? '' : 'pink'}>
                    <div key={index} onClick={() => {
                      // 当前选中的产线
                      console.log(item);
                      setcurrentproductionline(item);
                      setSelectLine(index);
                      setSelectProcess(-1)
                      // setStepparams({lineId:item.key})
                      productlineInfoStepsAPI.List({ lineId: item.key, finalId: selectRowItem.id }).then((res: MyResponse.Content) => {
                        if (res.statusCode === 200) {
                          setLineProcessList(res.data);
                        }
                      })
                    }} className={`${styles.tag_item} ${index === selectLine ? styles.tag_item_activeItem : ''}`}>
                      <Space size='small'>
                        <div >{item.value}</div>
                      </Space>
                      <div className={index === selectLine ? styles.tag_item_active : ''}></div>
                    </div>
                  </Badge.Ribbon>
                ))}
              </div>
            </Card>
            {lineProcessList.length > 0 ?
              <Card title={'产线工序路线'} extra={<Space direction='horizontal' >
                <Popconfirm
                  key="save"
                  title="确定要保存配置?保存成功后将返回成品列表。"
                  onConfirm={() => {
                    finalInfoAPI.Saveconfigstatus({ LineId: currentproductionline.key, finalId: selectRowItem.id }).then((res: MyResponse.Content) => {
                      if (res.statusCode === 200) {
                        message.success('保存成功!');
                        setTimeout(() => {
                          setIsLineStepOpen(false);
                        }, 1000);
                      } else {
                        message.error(res.errors || res.message);
                      }
                    })
                  }}
                >
                  <Button size='small' type='primary' danger >保存配置</Button>
                </Popconfirm>
                {/* <Button type='primary' danger>取消配置</Button> */}
              </Space>
              }>

                <CheckCard.Group onChange={() => {

                }} >
                  <div className={styles.gongyi_tag}>
                    <Flex wrap gap="small">

                      {lineProcessList.map((item, index) => (
                        <div className={styles.gongyi_tag_box} key={index} >
                          <div

                            className={`${styles.gongyi_tag_item} ${index === selectProcess ? styles.gongyi_tag_item_activeItem : ''}`}>
                            <Space size="middle">
                              <div color="#2db7f5" style={{ fontSize: '22px' }}> 0{index + 1}-{item.processName}</div>
                            </Space>
                            <div className={index === selectProcess ? styles.gongyi_tag_item_active : ''}></div>

                          </div>
                          <Card title='所属设备' size="small" bordered={false} style={{ height: '200px', overflowY: 'auto', overflowX: 'hidden' }} className={styles.gongyi_tag_device}>
                            {
                              item.devicesInfo.length > 0 ?
                                <Space title='设备' direction="vertical">
                                  {item.devicesInfo.map((devicesItem: any, devicesIndex: number) => (
                                    <Badge.Ribbon text={devicesItem.status == '0' ? '未设置' : '已设置'} color={devicesItem.status == '0' ? '' : 'pink'}>
                                      <CheckCard onClick={(v) => {
                                        setcurrentproductionProcess(item)
                                        setcurrentproductionDev(devicesItem.code)
                                        setStepTitle(item.processName + '-' + devicesItem.name + '[' + devicesItem.code + ']')
                                        setIsEditModalOpen(true)
                                        const jsondata = {
                                          lineId: currentproductionline.key,
                                          deviceId: devicesItem.code,
                                          finalId: selectRowItem.id,
                                          productLineStepsId: item.id
                                        }
                                        setStepparams(jsondata)
                                      }} size='small' title={devicesItem.name} value={devicesItem.id} />
                                    </Badge.Ribbon>
                                  ))}
                                </Space>
                                : <Empty description='未绑定设备' />
                            }
                          </Card>
                          {/* <Card title='备注' size="small" style={{ height: '150px' }}>
                          <Input aria-label='备注' />
                        </Card> */}

                          <Divider />
                        </div>

                      ))}
                    </Flex>
                  </div>
                </CheckCard.Group>

              </Card>
              : <Empty  description='未配置工序路线' />}

          </Card>
      }
      <Modal maskClosable={false} open={isEditModalOpen}
        width={1000}


        // title={<Tag color='#0960bd' bordered style={{fontSize:'18px',borderRadius:'0px'}}>{stepTitle}</Tag>}
        onCancel={() => {
          setIsEditModalOpen(false)
          UpdateGY(currentproductionline.key, selectRowItem.id)
        }
        }
        onOk={() => setIsEditModalOpen(false)}
        footer={false}
      // footer={[
      //   <Button
      //     key="back"
      //     onClick={() => {
      //       setIsEditModalOpen(false)
      //     }}
      //   >
      //     返回
      //   </Button>,
      //   <Button key="submit" danger type="primary" onClick={() => setIsEditModalOpen(false)} >
      //     完成配置
      //   </Button>,
      // ]}
      >
        <DragSortTable<CraftsTypes.craftsInfoOutput>
          tableStyle={{ overflowY: 'auto', overflowX: 'hidden', maxHeight: '500px' }}
          toolBarRender={() => [
            <Button
              type="primary"
              disabled={selectDev < 0}
              onClick={() => {

                typeForm.resetFields();
                setIsSetpModalOpen(true);
              }}
            >
              自定义步骤
            </Button>,
            <Button
              type="primary"
              danger
              disabled={selectDev < 0}
              onClick={() => {
                console.log('sss', currentproductionProcess?.devicesInfo);
                const b = JSON.stringify(currentproductionProcess?.devicesInfo);
                const c: any[] = JSON.parse(b);
                const d = c.filter(x => x.code != currentproductionDev);
                setM_device(d);
                setisConfigDevOpen(true)
              }}
            >
              使用同类型设备配置
            </Button>
          ]}
          actionRef={sortActionRef}
          headerTitle={stepTitle}
          columns={[
            {
              title: '步骤序号',
              dataIndex: 'step',
              tooltip: '鼠标放在序号前变成手形,上下拖拽调整顺序',

              hideInSearch: true,
              render: (dom, rowData, index) => {
                return (
                  <span className="customRender">{`${index + 1}`}</span>
                );
              },
            },
            {
              title: '步骤备注',
              dataIndex: 'description',

              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',
              hideInSearch: true,
            },
            {
              title: '设备参数预览',
              width: 100,
              hideInSearch: true,
              render(dom, entity, index, action, schema) {
                const deviceFunParams = JSON.parse(entity?.deviceFunParams);
                if (entity?.deviceStepParms) {
                  const deviceStepParms = JSON.parse(entity?.deviceStepParms);
                  let newParms: any[] = []
                  if (deviceStepParms) {
                    deviceFunParams?.map((item: any, index: number) => {
                      Object.keys(deviceStepParms).forEach((citem, cindex) => {
                        if (item.paramCode == citem) {
                          if (item.paramType == 1) {
                            let wl: string = '';
                            deviceStepParms[citem]?.map(
                              (s: any) => {
                                if (wl == '') {
                                  wl = materialParmList.find((x: any) => x.value == s).label
                                } else {
                                  wl = wl + ',' + materialParmList.find((x: any) => x.value == s).label
                                }
                              }
                            )
                            newParms.push({ name: item.paramName + ':' + wl! })
                          } else {
                            newParms.push({ name: item.paramName + ':' + deviceStepParms[citem] + item.paramUnit })
                          }
                        }
                      });
                    })
                  }
                  return (
                    <Space size='small' direction="vertical" align='start'>
                      {
                        newParms.map((sss) => (
                          <Tag>{sss.name}</Tag>
                        ))
                      }
                    </Space>
                  )
                }
              },
            },
            {
              title: '操作',
              align: 'center',

              valueType: 'option',
              fixed: 'right',
              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)
                              })
                              console.log(c);

                              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={false}
          params={stepparams}
          request={async (params = {}) => {
            if (!params.deviceId) {
              console.log('我来了');
              return {
                data: [],
                success: true,
              };
            }
            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('修改列表排序成功');
              }
            });

          }}
        />

      </Modal>

      {/* 新增成品的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"

          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;

          })
          console.log('list', list);

          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: 'mode',
                    valueType: 'select',
                    ellipsis: true,
                    valueEnum: {
                      '0': {
                        text: '设备',
                      },
                      '1': {
                        text: '其他',
                      },
                    }
                  },
                  {
                    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: '',
                      mode: ''
                    })
                  ,
                }
                }
                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)
              actionRef.current?.reload()
            } else {
              message.error('操作失败!');
            }
          })
        }}>
          <Form.Item label='请选择产线' name='lineId'>
            <Select placeholder='请选择产线' mode='multiple' >
              {
                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
        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>
      <Modal
        maskClosable={false}
        destroyOnClose
        width={800}
        open={isConfigDevOpen}
        onCancel={() => {
          setisConfigDevOpen(false);
        }}
        footer={false}
      >
        <ProForm onFinish={(value: any) => {
          finalCraftStepsAPI.Copyfinalcraftsteps({
            finalId: selectRowItem?.id,
            lineId: currentproductionline.key,
            copyDeviceId: value.deviceId,
            productLineStepsId: currentproductionProcess.id,
            toDeviceId: currentproductionDev
          }).then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
              message.success('同步成功!');
              setisConfigDevOpen(false);
              setTimeout(() => {
                const jsondata = {
                  lineId: currentproductionline.key,
                  deviceId: currentproductionDev,
                  finalId: selectRowItem?.id,
                  productLineStepsId: currentproductionProcess.id
                }
                setStepparams(jsondata)
                sortActionRef.current?.reload();
              }, 2000);

            }
          })


        }}>
          <Form.Item label="设备" name="deviceId" rules={[{ required: true, message: '此项为必填项!' }]}>
            <Select onChange={(v: processType.output) => {
            }} placeholder='请选择设备' style={{ width: 375 }}>
              {
                m_device?.map((item: any) => {
                  return <Select.Option value={item.code} key={item.code}>
                    <span>{item.name + '[' + item.code + ']'}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item>
        </ProForm>
      </Modal>
    </>


  );
};

export default final;
