/* eslint-disable */
/* eslint-disable prefer-destructuring,no-await-in-loop,radix,,no-loop-func */
import React, { useState, useCallback, useNodes } from 'react';
import { Button, Modal, Input } from 'antd-v4';
import ReactFlow, {
  addEdge,
  MiniMap,
  Controls,
  Background,
  useNodesState,
  useEdgesState,
} from 'react-flow-renderer';
import * as commonutils from '../../../utils/utils'
import './flows.less'
import { MarkerType } from 'react-flow-renderer';
import { connect } from "umi"
const getNodeId = () => `randomnode_${+new Date()}`;
const OverviewFlow = (props) => {
  const { flowData} = props;
  let initialNodes =[];
  let initialEdges =[];
  if(commonutils.isNotEmptyObject(flowData)) {
    initialNodes = flowData.initialNodes;
    initialEdges = flowData.initialEdges;
    if (commonutils.isNotEmptyArr(initialNodes)) {
        initialNodes.forEach((item) =>{
          const labelObj= (
            <span id='strToLabel' dangerouslySetInnerHTML={{__html: item.data.label }} />
          )
          if(!(commonutils.isNotEmptyObject(item) && commonutils.isNotEmptyObject(item.data) && commonutils.isNotEmptyObject(item.data.label) &&
          commonutils.isNotEmptyObject(item.data.label.props) && item.data.label.props.dangerouslySetInnerHTML)) {
            item.data.label= labelObj;
          }
        });
      }
    if (commonutils.isNotEmptyArr(initialEdges)) {
      initialEdges.forEach((item) => {
        if (commonutils.isNotEmptyStr(item.markerEnd)) {
          const markerObj = { 
            type: MarkerType.ArrowClosed,
          }
          item.markerEnd = markerObj
        }
      })
    }
  }

  // eslint-disable-next-line no-unused-vars
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
  const [rfInstance, setRfInstance] = useState(null);
  const [label, setlabel, onsetlabelChange] = useState('');
  const [value, setvalue, onsetvalueChange] = useState('')
  const [flowColor, setflowColor, onsetflowColor] = useState('')
  const [flowdata, delflowdata, ondelflowdata] = useState({})
  const [isModalVisible, setIsModalVisible] = useState(false);
  const onConnect = useCallback((params) => setEdges((eds) => addEdge(params, eds)), [setEdges]);
  const onAdd = (e) => { //添加部件
    setvalue('')
    setIsModalVisible(true);
    if (e.currentTarget.id === 'AddSole') {
      setflowColor('#f7b501')
    } else if (e.currentTarget.id === 'AddPortalBundle') {
      setflowColor('#fe7e83')
    } else if (e.currentTarget.id === 'AddClaim') {
      setflowColor('#00ff41')
    }
  };
  const handleOk = () => {
    setIsModalVisible(false);
    const newNode = {
      id: getNodeId(),
      sourcePosition: 'right',
      targetPosition: 'left',
      type: 'step',
      data: { label: label },
      style: {
        background: flowColor,
        width: '150px',
        height: '80px',
        fontWeight: 700,
      },
      position: {
        x: Math.random() * window.innerWidth - 100,
        y: Math.random() * window.innerHeight,
      },
    };
    setNodes((nds) => nds.concat(newNode));
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const onSave = useCallback(() => { //保存部件
    if (rfInstance) {
      const flow = rfInstance.toObject();
      localStorage.setItem(flow, JSON.stringify(flow));
    }
  }, [rfInstance]);
  const handleChangeValue = useCallback((e) => {
    setvalue(e.target.value)
    setlabel(e.target.value)
  })
  const onNodeClick = (e, node) => {
    // delflowdata(node);
  }
  const onDel = () => { //删除部件
    let newnodes = nodes.filter(item => item.id !== flowdata.id)
    setNodes(newnodes)
  }
  const onMadl = () => {
    alert('二期项目')
  }
  return (
    <ReactFlow
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      onNodeClick={(e, node) => onNodeClick(e, node)}
    >
      <div className="save__controls">
        <Button onClick={onAdd} id='AddSole'>单一部件</Button>
        <Button onClick={onAdd} id='AddPortalBundle'>合版部件</Button>
        <Button onClick={onAdd} id='AddClaim'>组装部件</Button>
        <Button onClick={onMadl}>选择工序</Button>
        <Button onClick={onMadl}>选择材料</Button>
        <Button onClick={onDel}>删除</Button>
        <Button onClick={onSave}>保存</Button>
        <Button id='Generate' onClick={onMadl}>反向生成工单</Button>
        <Button id='Err' onClick={onMadl}>开单逻辑错误</Button>
        <Modal title="添加部件名称" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}><Input placeholder="Basic usage" onChange={e => handleChangeValue(e)} value={value} /></Modal>
      </div>
      <MiniMap
        nodeStrokeColor={(n) => {
          if (n.style?.background) return n.style.background;
          if (n.type === 'input') return '#0041d0';
          if (n.type === 'output') return '#ff0072';
          if (n.type === 'default') return '#1a192b';
          return '#eee';
        }}
        nodeColor={(n) => {
          if (n.style?.background) return n.style.background;
          return '#fff';
        }}
        nodeBorderRadius={2}
      />
      <Controls />
      <Background color="#aaa" gap={16} />
    </ReactFlow>
  );
};
export default connect()(OverviewFlow)
// export default () => (
//   <ReactFlowProvider>
//     <OverviewFlow />
//   </ReactFlowProvider>
// );
