import {memo, useCallback} from 'react';
import {Handle, Position, useConnection} from '@xyflow/react';
import {styled} from "styled-components";
import {Checkbox} from "antd";
import {ICON_MAP} from "../constants";
import {useWorkFlow} from "../../../hooks/useWorkFlow";

export const FieldsNode = memo(({ id,data }) => {
  const {getNodesState,updateNodesState} = useWorkFlow();
  const {checkable,label,description,isKey,type,checked} = data;
  const connection = useConnection();
  const isConnecting = !!connection.startHandle;

  /** 勾选*/
  const onChange = useCallback((e)=>{
    const checked = e.target.checked;
    updateNodesState(
      getNodesState.map(item=>{
        if (item.id === id){
          return {
            ...item,
            data:{
              ...item.data,
              checked
            }
          }
        }
        return item
      })
    )
  },[getNodesState])

  return (
    <Container>
      {!isConnecting && (
        <Handle
          className="customHandle"
          position={Position.Right}
          type="source"
        />
      )}
      <Handle
        className="customHandle"
        position={Position.Left}
        type="target"
        isConnectableStart={false}
      />
      <div style={{width:475, display: 'flex', justifyContent:'space-between'}}>
        <span>
          {isKey ? ICON_MAP.KEY : ICON_MAP[type]}
          {label}
          {description && `（${description}）`}
        </span>
        {checkable && !isKey && type!=="identify" && <Checkbox onChange={onChange} defaultChecked={checked}/>}
      </div>
    </Container>
  )
})

const Container = styled.div`
  //width: 100%;
  height: 40px;
  padding: 0 12px;
  border-top: 1px solid ${p => p.theme.colorBorderSecondary};
  position: relative;
  overflow: hidden;
  display: flex;
  //justify-content: center;
  align-items: center;
  font-weight: bold;
`