import { useEffect, useState } from 'react';
import { Radio } from 'antd';

import { dispatch } from '../../../../model';
import Relation from './Relation';
import Thermodynamic from './Thermodynamic';
import { AssetBrowseReference, ResourceBrowseReference } from '../../../../util/constant';

const relationTypes = [
  {
    title: '关系图',
    key: 'relation',
  },
  {
    title: '热力图',
    key: 'thermodynamic'
  },
  {
    title: '数据地图',
    key: 'map',
  }
]

const RelationContainer = (props) => {

  const { nodeParams, onChange, reference,  resize } = props;

  const [ type, setType ] = useState('relation');
  const [ dirs, setDirs ] = useState([]);
  const [ nodes, setNodes ] = useState([]);
  const [ relationData, setRelationData ] = useState(null); 
  const [ thermodynamicData, setThermodynamicData ] = useState(null);

  useEffect(() => {
    getDirectoryData();
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (type === 'relation') {
      if ((nodeParams?.expandId||'') !== '') {
        generateExpandNodeRelationData();
      } else if ((nodeParams?.centerId||'')!== '' && (dirs||[]).length>0) {
        generateNodes();
      } else {
        setRelationData(null);
      }
    } else {
      if ((nodeParams?.centerId||'')!=='' && (dirs||[]).length>0) {
        generateThermodynamicData();
      } else {
        setThermodynamicData(null);
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [nodeParams, dirs, type])

  const getDirectoryData = () => {

    let url = '';
    if (reference === AssetBrowseReference) {
      url = 'assetmanage.queryAssetDirectoryAsTree';
    } else if (reference === ResourceBrowseReference) {
      url = 'assetmanage.queryResourceDirectoryAsTree';
    }

    dispatch({
      type: url,
      callback: data => {
        let newDirs = [...data];
        newDirs = (newDirs||[]).filter(item => item.type!=='custom');
        setDirs(newDirs);
      }
    });
  }

  const generateNodes = () => {

    let centerDirectory = {};

    function recursionToGetCenterDirectory(data) {
      (data||[]).forEach((item, index) => {
        if (item.nodeId === nodeParams?.centerId) {
          centerDirectory = item;
          return;
        }

        recursionToGetCenterDirectory(item.children);
      })
    }

    recursionToGetCenterDirectory(dirs);

    if (centerDirectory.nodeId) {
      let newNodes = [{id: centerDirectory.nodeId, pid: null, levelId: '0', simple: false, show: true, text: centerDirectory.text, count: centerDirectory.dataAssetAndSubDirCount }];
    
      function recursion(data, parentId, parentLevelId) {
        (data||[]).forEach((item, index) => {
          let currentLevelId = `${parentLevelId}-${index}`;
          newNodes.push({ id: item.nodeId, pid: parentId, levelId: currentLevelId, simple: (currentLevelId.split('-').length>=3)?true: false, show: (currentLevelId.split('-').length>2)?false:true, text: item.text, count: item.dataAssetAndSubDirCount });

          recursion(item.children, item.nodeId, currentLevelId);
        })
      }

      recursion(centerDirectory.children||[], centerDirectory.nodeId, '0');

      //判断是否有子节点
      newNodes.forEach(node => {
        const index = newNodes.findIndex(_node => _node.levelId===`${node.levelId}-0`);

        node.haveChild = (index!==-1);
      })

      setNodes(newNodes);
      generateCenterNodeRelationData(newNodes);
    }
  }

  const generateCenterNodeRelationData = (data = nodes) => {
    if ((data||[]).length===0) {
      setRelationData(null);
      return;
    }

    const index = (data||[]).findIndex(node => node.id === nodeParams?.centerId);
    if (index !== -1) {
      let rootNode = data[index];
      let totalLevel = 1;

      rootNode = {...rootNode, center: true };

      let newRelationData = {...rootNode, children: []};

      function recursion(subData, parentId) {

        (data||[]).forEach(node => {
          if (totalLevel < node.levelId.split('-').length) {
            totalLevel = node.levelId.split('-').length;
          }
          
          if (!node.show) return;

          if (node.pid === parentId) {

            let newNode = { ...node, children: [] };

            (subData||[]).push(newNode);
            recursion(newNode.children, newNode.id);
          }
        })
      }

      recursion(newRelationData.children, rootNode.id);

      newRelationData = {...newRelationData, totalLevel};

      // const _index = (dirs||[]).findIndex(dir => dir.nodeId === rootNode.id);
      // if (_index !== -1) {
      //   if (reference === AssetBrowseReference) {
      //     newRelationData = {text: '资产', show: true, simple: false, virtual: true, children: [newRelationData]};
      //   } else if (reference === ResourceBrowseReference) {
      //     newRelationData = {text: '资源', show: true, simple: false, virtual: true, children: [newRelationData]};
      //   }
      // }

      setRelationData(newRelationData);
    }
  }

  const generateExpandNodeRelationData = (data = nodes) => {
    if ((data||[]).length===0) {
      setRelationData(null);
      return;
    }

    const index = (data||[]).findIndex((node) => node.id === nodeParams?.expandId);
    if (index !== -1) {
      let currentNode = data[index];

      currentNode = {...currentNode, expand: true};

      (data||[]).forEach(node => {

        let nodeLevelId = `${node.levelId}-`;
        let currentLevelId = `${currentNode.levelId}-`;

        if (currentNode.levelId.split('-').length > 1) {
          if ((node.levelId.split('-').length===currentNode.levelId.split('-').length+1) && node.levelId.slice(0, currentLevelId.length)===currentLevelId) {
            node.show = !node.show;
          }
        }

        if (node.levelId.split('-').length >2) {
          if (node.levelId.split('-').length<currentNode.levelId.split('-').length) {
            node.simple = (currentNode.levelId.slice(0, nodeLevelId.length)!==nodeLevelId);
          } else if (node.levelId.split('-').length===currentNode.levelId.split('-').length) {
            node.simple = (node.levelId !== currentNode.levelId);
          } else if (node.levelId.split('-').length===currentNode.levelId.split('-').length+1) {
            node.simple = (node.levelId.slice(0, currentLevelId.length)!==currentLevelId);
          } else if (node.levelId.slice(0, currentLevelId.length)!==currentLevelId) {
            node.simple = true;
          }
        }
      })

      console.log('data', data)
      setNodes(data);

      generateCenterNodeRelationData(data);
    }
  }

  const generateThermodynamicData = () => {
    let centerDirectory = {};

    function recursionToGetCenterDirectory(data) {
      (data||[]).forEach((item, index) => {
        if (item.nodeId === nodeParams?.centerId) {
          centerDirectory = item;
          return;
        }

        recursionToGetCenterDirectory(item.children);
      })
    }

    recursionToGetCenterDirectory(dirs);

    if (centerDirectory.nodeId) {

      let newCenterDirectory = JSON.parse(JSON.stringify(centerDirectory));

      function recursionCenterDirctory(data, depth) {
        (data||[]).forEach((item, index) => {
          item.name = `${item.text} (${item.dataAssetAndSubDirCount})`;
          item.value = item.dataAssetAndSubDirCount;
  
          recursionCenterDirctory(item.children);
        })
      }

      recursionCenterDirctory(newCenterDirectory.children);

      let newThermodynamicData = [{
        ...newCenterDirectory,
        value: newCenterDirectory.dataAssetAndSubDirCount,
        name: `${newCenterDirectory.text} (${newCenterDirectory.dataAssetAndSubDirCount})`,
      }];

      setThermodynamicData(newThermodynamicData);
    }
  }

  const onCenterClick = (id) => {
    onChange && onChange({centerId: id, expandId: ''});
  }

  const onExpandClick = (id) => {
    onChange && onChange({...nodeParams, expandId: id});
  }

  const onThermodynamicClick = (id) => {
    onChange && onChange({centerId: id, expandId: ''});
  }

  const onTypeChange = (e) => {
    if (e.target.value === 'map') {
      window?.open('/center-home/menu/asset-map');
    } else {
      setType(e.target.value);
    }
  }

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative' }}>
      {
        (type==='relation') && <Relation data={relationData} expandId={nodeParams?.expandId} resize={resize} onCenterClick={onCenterClick} onExpandClick={onExpandClick} />
      }
      {
        (type==='thermodynamic') && <Thermodynamic data={thermodynamicData} resize={resize} onClick={onThermodynamicClick} />
      }
      <Radio.Group value={type} onChange={onTypeChange} buttonStyle="solid" style={{ position: 'absolute', right: 15, top: 20 }}>
      {
        relationTypes.map((item, index) => {
          return <Radio.Button key={index} value={item.key}>{item.title}</Radio.Button>
        })
      }
      </Radio.Group>
    </div>
  );
}

export default RelationContainer;
