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

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

  /** 勾选*/
  const onChange = useCallback((e)=>{
    // 勾选状态
    const checked = e.target.checked;
    let newPeriods = commonPeriods;
    const exist = newPeriods.includes(period);
    const lent = newPeriods.length;
    // 校验统计周期
    if (period && checked ){
      if (!exist && lent===0){
        newPeriods = newPeriods.concat(period);
      }
      if (!exist && lent>0){
        message.warning("指标统计周期不唯一")
        return false
      }
    }
    if (period && !checked){
      const exist = getNodesState.find(p=>(p.data.period === period) && (p.id!==id) && p.data.checked)
      if (!exist){
        newPeriods = newPeriods.filter(p=>p!==period)
      }
    }

    setState(checked)


    // 先修改指标勾选状态
    const newState = getNodesState.map(({data,...rest})=>({
      ...rest,
      data:{
        ...data,
        checked: (rest.id === id && data.type===type)
          ? checked
          : data.checked,
        commonPeriods:newPeriods
      },
    }))


    // 同步更新公共维度
    let common=[];
    newState.forEach(v=>{
      const dims = v.data.dimensions;
      if (dims){
        if (v.data.checked && DEFINE_TYPE[v.data.type]){
          if (common.length===0){
            // 以第一个指标为基准
            common = dims
          }else{
            common = common.reduce((acc, curr) => {
              if (dims.includes(curr) && !acc.includes(curr)) {
                acc.push(curr);
              }
              return acc;
            }, []);
          }
        }
      }
    })

    // 再根据指标修改后的状态进行维度处理
    const newNodes = newState.map(item=>{
      // 勾选指标时，处理可勾选维度和已勾选维度
      if (DEFINE_TYPE[type] && !DEFINE_TYPE[item.data.type]){

        const isCommon = common.includes(item.data.id);
        // 为公共维度，且被勾选
        return {
          ...item,
          data:{
            ...item.data,
            checkable:isCommon,
            checked:isCommon && item.data.checked,
          }
        }
      }
      return item
    })

    console.log(newNodes)


    updateNodesState(newNodes)
  },[getNodesState,period,commonPeriods,state])

  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 checked={state} 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;
`