import {styled} from "styled-components";

import {memo, useCallback, useEffect} from 'react';

import {
  ReactFlow,
  Controls,
  MiniMap,
  addEdge,
  useNodesState,
  useEdgesState,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import './style.css';

import {useWorkFlow} from "../../hooks/useWorkFlow";

export const WorkFlowPanel = memo(({
  style,
  initialNodes,
  initialEdges,
  ...rest
}) => {
  //console.log("Workflow更新")
  const {updateEdgesState} = useWorkFlow();

  /** 同步节点 */
  useEffect(() => {
    setNodes(initialNodes)
  }, [initialNodes]);

  /** 同步连接线 */
  useEffect(() => {
    setEdges(initialEdges)
  }, [initialEdges]);

  /** 数据透传 */
  const [nodes, setNodes, onNodesChange] = useNodesState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);

  /** 节点连接 */
  const onConnect = useCallback(
    (params) => {
      const sourceIndex = nodes.findIndex(item => item.id === params.source);
      const targetIndex = nodes.findIndex(item => item.id === params.target);
      const sourceNode = nodes[sourceIndex];
      const targetNode = nodes[targetIndex];
      /** 若是同表字段不能相连*/
      if (sourceNode.parentId !== targetNode.parentId) {
        setEdges((eds) => updateEdgesState(addEdge(params, eds)))
      }
    },
    [nodes,edges]
  );
  const proOptions = { hideAttribution: true };
  return (
    <Container style={style}>
      <ReactFlow
        fitView
        nodes={nodes}
        edges={edges}
        elementsSelectable={false}
        nodesFocusable={false}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        proOptions={proOptions}
        {...rest}
      >
        <Controls />
        <MiniMap />
      </ReactFlow>
    </Container>
  );
})

const Container = styled.div`
  width: 100%;
  height: 600px;
  border-radius: ${p=> p.theme.borderRadius}px;
  color: ${p => p.theme.colorTextBase};
  border: ${p=> `1px solid `+ p.theme.colorBorder};
  .react-flow {
    background-color: ${p=>
        p?.style?.backgroundColor 
          ?p.style.backgroundColor
          :p.theme.colorBgTextHover
    }
  }
`