import React, { useEffect, useState, useRef } from 'react';
import {Card, Spin, Tooltip, Tree, Dropdown, Menu, Modal, AutoComplete, Select} from 'antd';
import { PlusOutlined, ImportOutlined,ExportOutlined,ReloadOutlined, SettingOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { useContextMenu, Menu as RcMenu, Item as RcItem } from "react-contexify";
import LocalStorage from 'local-storage';

import { dispatch } from '../../../../model';
import ImportDirectory from './ImportDirectory'; 
import UpdateDirectoryModal from './UpdateDirectoryModal';
import CustomDirectoryModal from './CustomDirectoryModal';
import { showMessage, getQueryParam } from '../../../../util';
import { AnchorTimestamp, AnchorId, AssetManageReference, AssetBrowseReference, ResourceBrowseReference, AssetMountReference, AnchorDirId } from '../../../../util/constant';
import { highlightSearchContentByTerms } from '../../../../util';

import './AssetManageTree.less';
import 'react-contexify/dist/ReactContexify.css';
import { appId } from '../../../../App';
import { getTemplateType } from '../../../../util/axios';

const { Option } = AutoComplete;

function updateTreeData(list, key, children) {
  return list.map((node) => {
    if (node.nodeId === key) {
      return { ...node, children };
    }

    if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }

    return node;
  });
}

const AssetManageTree = (props) => {
  console.log('AssetManageTreeProps',props);

  const MENU_ID = 'asset-manage-tree';

  const { show } = useContextMenu({
    id: MENU_ID,
  });

  const { checkable = false, onSelect, className, onCheck, tableId, reference=AssetManageReference, onDirectoryChange, centerId, metadataIds,myAssets} = props; 
  const [ keyword, setKeyword ] = useState('');
  const [ loading, setLoading ] = useState(false);
  const [ treeData, setTreeData ] = useState([]);
  const [ dataList, setDataList ] = useState([]);
  const [ groupIds, setGroupIds ] = useState([]);
  const [ expandedKeys, setExpandedKeys ] = useState([]);
  const [ checkedKeys, setCheckedKeys ] = useState([]);
  const [ autoExpandParent, setAutoExpandParent ] = useState(false);
  const [ currentDirId, setCurrentDirId ] = useState('');
  const [ currentDirType, setCurrentDirType ] = useState('');
  const [ currentDir, setCurrentDir ] = useState({});
  const [ currentRightClickDir, setCurrentRightClickDir ] = useState({});
  const [ importDirectoryVisible, setImportDirectoryVisible ] = useState(false);
  const [ updateDirectoryModalVisible, setUpdateDirectoryModalVisible ] = useState(false);
  const [ updateDirectoryAction, setUpdateDirectoryAction ] = useState('');
  const [ customDirectoryModalVisible, setCustomDirectoryModalVisible ] = useState(false);
  const [ customDirectoryAction, setCustomDirectoryAction ] = useState('');
  const [options, setOptions] = useState([]);
  const [ loadedKeys, setLoadedKeys ] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(false)
  const [templates, setTemplates] = useState()
  const [currentTemplateType, setTemplateType] = useState()

  const [modal, contextHolder] = Modal.useModal();
  
  const timestamp = getQueryParam(AnchorTimestamp, props?.location?.search);
  const id = getQueryParam(AnchorId, props?.location?.search);
  const did = getQueryParam(AnchorDirId, props?.location?.search);

  const treeDataRef = useRef([]);
  const dataListRef = useRef([]);

  useEffect(() => {
    if (reference === AssetManageReference) {
      getTemplates()
    } else if (reference === AssetMountReference && (metadataIds??[]).length > 0) {
      getMetadataTemplates()
    } else {
      getAllDirectoryAsTree(false)
    }
    
    window?.addEventListener("storage", storageChange);

    return () => {
      window?.removeEventListener("storage", storageChange);
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [metadataIds])

  // useEffect(() => {
  //   if ((did||'') !== '') {
  //     getAllDirectoryAsTree(true, did);
  //   } else if ((id||'') !== '') {
  //     getDataAssetLocationThenGetTreeData();
  //   }  else {
  //     getAllDirectoryAsTree(true);
  //   } 
  //   //eslint-disable-next-line react-hooks/exhaustive-deps
  // }, [timestamp])

  useEffect(() => {
    if ((tableId||'') !== '') {
      getTableDirIds();
    } 
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tableId])

  useEffect(() => {
    if ((centerId||'')!=='' && centerId!==currentDirId) {
      treeDirectoryChanged(centerId);
    } 
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [centerId])

  const storageChange = (e) => {
    if (e.key === 'assetDirChangeEvent' || e.key === 'assetPathOnClickEvent') {
      if ((e.dirId||'') !== '') {
        treeDirectoryChanged(e.dirId);
      }
    } else if (e.key === 'assetRelationOnClickEvent') {
      treeDirectoryChanged(e.relation?.dirId);
    }
  }

  const getTemplates = () => {
    setLoadingTemplates(true)
    dispatch({
      type: 'assetmanage.getTemplates',
      callback: data => {
        setLoadingTemplates(false)
        setTemplates(data)
        if ((data??[]).length > 0) {
          setTemplateType(data[0].type)
          LocalStorage.set(`templateType-${appId}`, data[0].type)
          let event = new Event('storage');
          event.key = 'assetTemplateChange';
          window?.dispatchEvent(event);
          
          getAllDirectoryAsTree(true)
        }
      },
      error: () => {
        setLoadingTemplates(false)
      }
    })
  }

  const getMetadataTemplates = () => {
    setLoadingTemplates(true)
    dispatch({
      type: 'assetmanage.getMetadataTemplates',
      payload: {
        metadataIdPath: metadataIds[0]
      },
      callback: data => {
        setLoadingTemplates(false)
        setTemplates(data)
        if ((data??[]).length > 0) {
          setTemplateType(data[0].type)
          LocalStorage.set(`templateType-${appId}`, data[0].type)
          getAllDirectoryAsTree(true)
        }
      },
      error: () => {
        setLoadingTemplates(false)
      }
    })
  }

  const getDataAssetLocationThenGetTreeData = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getDataAssetLocation',
      payload: {
        dataAssetId: id
      },
      callback: data => {
        getAllDirectoryAsTree(true, data.dirId||'');
      },
      error: () => {
        setLoading(false);
        getAllDirectoryAsTree(true);
      }
    });
  }

  const getTableDirIds = () => {
    dispatch({
      type: 'assetmanage.getDataAssetDetail',
      payload: {
        dataAssetId: tableId
      },
      callback: data => {
        setCheckedKeys(data.dirIds||[]);
        setExpandedKeys(data.dirIds||[]);
        setAutoExpandParent(true);
        onCheck && onCheck(data.dirIds||[]);
      },
    })
  }

  const getAllDirectoryAsTree = (resetCurrentDirId=true, defaultSelectedId='', refresh = false) => {

    setLoading(true);
    if (resetCurrentDirId) {
      onSelect && onSelect('', '');
    }

    function disposeData(data) {
      setLoading(false);

      refresh && showMessage('success', '操作成功');

      let newData = [...data];

      if (reference === AssetMountReference) {
        newData = newData.filter(item => item.resourceType!=='custom');
      }

      setLoadedKeys([]);
      setTreeData(newData);

      const _dataList = [], _groupIds = [];
      generateList(newData, _dataList);
      generateGroupIds(newData, _groupIds);
      setDataList(_dataList);

      setGroupIds(_groupIds);

      treeDataRef.current = newData;
      dataListRef.current = _dataList;

      let defaultItem = null;

      if ((defaultSelectedId||'') === '') {
        _dataList.forEach(item => {
          if ((defaultSelectedId||'')==='') {
            defaultSelectedId = item.key;
          }
        })
      }

      function recursion(subCatalogs) {

        if ((subCatalogs||[]).length===0) return;

        (subCatalogs||[]).forEach(catalog=> {
  
          if (catalog.nodeId === defaultSelectedId) {
            defaultItem = catalog;
          }

          recursion(catalog.children);
        })
      } 

      if ((defaultSelectedId||'') !== '') {
        recursion(newData);
      } 

      if (resetCurrentDirId) {

        if (defaultItem) {  
          const expandedKeys = _dataList
            .map(item => {
              if (item.key.indexOf(defaultSelectedId) > -1) {
                return getParentKey(item.key, newData);
              }
              return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);

          setExpandedKeys([...expandedKeys, defaultSelectedId]);
          setAutoExpandParent(true);

          setCurrentDirId(defaultItem.nodeId);
          setCurrentDirType(defaultItem.type||'');
          setCurrentDir(defaultItem);
          onSelect && onSelect(defaultItem.nodeId, defaultItem.type||'', defaultItem.level);
        } 
      }
    }
    
    dispatch({
      type: 'assetmanage.queryAllDirectoryAsTree',
      callback: data => {
        disposeData(data)
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const treeDirectoryChanged = (did) => {

    let defaultItem = null;

    function recursion(subCatalogs) {

      if ((subCatalogs||[]).length===0) return;

      (subCatalogs||[]).forEach(catalog=> {

        if (catalog.nodeId === did) {
          defaultItem = catalog;
        }

        recursion(catalog.children);
      })
    } 

    if ((did||'') !== '') {
      recursion(treeDataRef.current);
    }

    if (defaultItem) {  
      const expandedKeys = (dataListRef.current||[])
        .map(item => {
          if (item.key.indexOf(did) > -1) {
            return getParentKey(item.key, treeDataRef.current);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);

      setExpandedKeys([...expandedKeys, did]);
      setAutoExpandParent(true);

      setCurrentDirId(defaultItem.nodeId);
      setCurrentDirType(defaultItem.type||'');
      setCurrentDir(defaultItem)
      onSelect && onSelect(defaultItem.nodeId, defaultItem.type||'', defaultItem.level);
    } 
  }

  const generateList = (treeData, list, path = null) => {
    for (let i = 0; i < treeData.length; i++) {

      if (treeData[i].resourceType !== 'custom') {
        const node = treeData[i];
        const { nodeId, text } = node;

        const currentPath = path ? `${path}/${text}` : text;

        list.push({ key: nodeId , title: text, value: currentPath, level: node.level });
        
        if (node.children) {
          generateList(node.children, list, currentPath);
        }
      }
    }
  };

  const generateGroupIds = (treeData, list) => {
    
    function generateGroupItem(data, list) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        list.push(node.nodeId);
        if (node.children) {
          generateGroupItem(node.children, list);
        }
      }
    }
   
    for (let i = 0; i < treeData.length; i++) {

      const channelTreeData = treeData[i];
      if (channelTreeData.children) {
        for (let j =0; j < channelTreeData.children.length; j++) {
          const node = channelTreeData.children[j];
          const { nodeId } = node;
    
          const groupItem = [nodeId];
          if (node.children) {
            generateGroupItem(node.children, groupItem);
          }
    
          list.push(groupItem);
        }
      }
    }

  };

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.nodeId === key)) {
          parentKey = node.nodeId;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  const getCurrentType = (key, tree) => {
    let type = '';

    (tree||[]).forEach(node => {
      if (node.nodeId === key) {
        type = node.type||'';        
      } else if (node.children) {
        if (getCurrentType(key, node.children)) {
          type = getCurrentType(key, node.children);
        }
      }
    })
    
    return type;
  }

  const getCurrentDir = (key, tree) => {
    let dir = undefined;

    (tree||[]).forEach(node => {
      if (node.nodeId === key) {
        dir = node       
      } else if (node.children) {
        if (getCurrentDir(key, node.children)) {
          dir = getCurrentDir(key, node.children);
        }
      }
    })
    
    return dir;
  }
 
  const addDir = () => {
    if (currentDir?.resourceType==='custom') return;

    setUpdateDirectoryAction('add');
    setUpdateDirectoryModalVisible(true);
  }

  const editDir = () => {

    if ((currentDirType||'') === '') {

      setUpdateDirectoryAction('edit');
      setUpdateDirectoryModalVisible(true);
    
    } else if (currentDirType === 'custom') {
      
      setCustomDirectoryAction('edit');
      setCustomDirectoryModalVisible(true);
    
    }
  }

  const refreshTree = () => {
    getAllDirectoryAsTree(false, '', true);
  }

  const importDir = () => {
    if (currentDirType==='custom') return;

    setImportDirectoryVisible(true);
  }

  const exportAllDir = () => {
    window.open(`/api/dataassetmanager/directoryApi/export?templateType=${getTemplateType()}`);
  }

  const exportCurrentDir = () => {
    if(currentDirId){
      dispatch({
        type: 'assetmanage.getDirectoryById',
        payload: { 
          dirId: currentDirId
        },
        callback: data => {
          window.open(`/api/dataassetmanager/directoryApi/export?parentPath=${data.path}&templateType=${getTemplateType()}`);  
        }
      })
    } else {
      showMessage("warn","请选择目录")
    }
  }

  const deleteDir = () => {    
    if (currentRightClickDir.nodeId) {
      modal.confirm({
        title: '您确定要删除该目录吗?',
        onOk: () => {
          dispatch({
            type: 'assetmanage.checkDirectoryDeleteAble',
            payload: {
              params: {
                dirId: currentRightClickDir.nodeId
              }
            },
            callback: able => {
              if (able === 'true') {
                dispatch({
                  type: 'assetmanage.deleteDirectory',
                  payload: {data: [ currentRightClickDir.nodeId ]},
                  callback: () => {
                    showMessage("success","删除成功");
                    getAllDirectoryAsTree(true, (currentRightClickDir.nodeId===currentDirId)?'':currentDirId);
                  }
                })
              } else {
                showMessage("warn","目录下有资产目录信息,不允许删除!");
              }
            }
          })
        }
      })

    } else {
      showMessage('info', '请先选择目录');
    }
  }

  const moveNode = (steps) => {
    if ((currentRightClickDir.nodeId||'') === '') {
      showMessage('info', '请先选择目录');
      return;
    }

    setLoading(true);
    dispatch({
      type: 'assetmanage.upDownDirectory',
      payload: {
        params: {
          dirId: currentRightClickDir.nodeId,
          steps
        }
      },
      callback: () => {
        showMessage('success', (steps===1)?'上移目录成功':'下移目录成功');
        getAllDirectoryAsTree(false);
      }, 
      error: () => {
        setLoading(false);
      }
    });
  }

  const customDir = () => {
    setCustomDirectoryAction('add');
    setCustomDirectoryModalVisible(true);
  }

  // const onChange = (e) => {

  //   const { value } = e.target;

  //   if (value === '') {
  //     setExpandedKeys([]);
  //     setAutoExpandParent(false);
  //     setKeyword(value);
  //     return;
  //   }

  //   const expandedKeys = dataList
  //     .map(item => {
  //       if (item.title.indexOf(value) > -1) {
  //         return getParentKey(item.key, treeData);
  //       }
  //       return null;
  //     })
  //     .filter((item, i, self) => item && self.indexOf(item) === i);

  //   setExpandedKeys(expandedKeys);
  //   setAutoExpandParent(true);
  //   setKeyword(value);
  // }

  const onTreeSelect = (keys, { node }) => {
    if ((keys||[]).length === 0) {
      return;
    }

    setCurrentDirId(keys[0]);

    const _currentDirType = getCurrentType(keys[0], treeData);
    const _currentDir = getCurrentDir(keys[0], treeData);

    setCurrentDirType(_currentDirType);
    setCurrentDir(_currentDir);
    onSelect && onSelect(keys[0], _currentDirType, node.level);
  }
  
  const onTreeCheck = (values, e) => {
    //同一主题下只能挂载一个目录

    if (e.node?.level === 1) {
      showMessage('warn', '栏目不允许勾选');
      return;
    }

    // const _checkedKeysValue = [...(values.checked||[])];

    if (e.checked) {
      // const _currentNodeId = e.node?.key;
      // let _groupItem = [];

      // groupIds.forEach(groupItem => {
      //   groupItem.forEach(id => {
      //     if (id === _currentNodeId) {
      //       _groupItem = groupItem;
      //     }
      //   })
      // })

      // const _filterKeys = (_checkedKeysValue.filter(item => item===_currentNodeId || !(_groupItem.includes(item))));
      
      setCheckedKeys([e.node?.key]);
      onCheck && onCheck([e.node?.key]);
    } else {  
      setCheckedKeys([]);
      onCheck && onCheck([]);
    }

  }

  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  const onUpdateDirectoryCancel = (refresh=false, id) => {
    setUpdateDirectoryModalVisible(false);
    if (refresh) {
      if (updateDirectoryAction === 'add') {
        getAllDirectoryAsTree(true, id);
      } else {
        getAllDirectoryAsTree();
        onDirectoryChange && onDirectoryChange();
      }
    }
  }

  const onImportDirectoryCancel = (refresh=false, resetCurrentDirId=false) => {
    setImportDirectoryVisible(false);
    refresh && getAllDirectoryAsTree(resetCurrentDirId);
  }

  const onCustomDirectoryCancel = (refresh=false, id='') => {
    setCustomDirectoryModalVisible(false);
    if (refresh) {
      if (customDirectoryAction === 'add') {
        getAllDirectoryAsTree(true, id);
      } else {
        getAllDirectoryAsTree(false);
      }
    }
  }

  const displayMenu = (e) => {
    show(e, {
      position: {
        x: e.clientX + 30,
        y: e.clientY - 10
      }
    });
  }

  const onAutoCompleteSearch = (searchText) => {
    setKeyword(searchText);
    setOptions(
      !searchText ? [] : (dataList||[]).filter(item => item.value.indexOf(searchText)!==-1),
    );
  };

  const onAutoCompleteSelect = (value, option) => {
    const paths = value.split('/');
    setKeyword(paths[paths.length-1]);
    treeDirectoryChanged(option.key);
  };

  const onLoadData = ({ key, children }) => 
    new Promise((resolve) => {

      if (children) {
        resolve();
        return;
      }

      setLoadedKeys([...loadedKeys, key]);

      dispatch({
        type: 'assetmanage.getDirectoryChild',
        payload: {
          parentId: key,
        },
        callback: (data) => {
          if (data && data.length>0) {
            let newTreeData = updateTreeData(treeData, key, data);
            setTreeData(newTreeData);
            treeDataRef.current = newTreeData;
          }
      
          resolve();
        }, 
        error: () => {
          resolve();
        }
      });
    });

  const exportMenu = (
    <Menu>
      <Menu.Item>
        <div style={{ textAlign: 'center' }} onClick={() => exportAllDir()}>
          导出所有
        </div>
      </Menu.Item>
      <Menu.Item>
        <div style={{ textAlign: 'center' }} onClick={() => exportCurrentDir()}>
          导出选中目录
        </div>
      </Menu.Item>
    </Menu>
  );

  const loop = (data, rootResourceType = null) =>
    data.map(item => {

      if (item.level === 1) {
        rootResourceType = item.resourceType;
      }

      const title = (
        <span
          className={(item.level===1)?'title-color': 'text-color'}
        >
          {item.text}
          {
            //自定义类型栏目不统计资产数
            (item.level!==1||(item.level===1&&item.resourceType!=='custom')) && <span>{` (${item.dataAssetAndSubDirCount})`}</span>
          }
        </span>
      );

      if (item.children && item.children.length>0) {
        return { ...item, ...{title, key: item.nodeId, disableCheckbox: !item.allowdLoadDataAsset, children: loop(item.children, rootResourceType), className: (item.level===1)?'root':''} };
      }

      if (rootResourceType !== 'custom') {
        return { ...item, ...{ title, key: item.nodeId, disableCheckbox: !item.allowdLoadDataAsset, isLeaf: true, className: (item.level===1)?'root':'' }};
      }

      return { ...item, ...{ title, key: item.nodeId, disableCheckbox: !item.allowdLoadDataAsset, children: null, className: (item.level===1)?'root':''}};
    });

  const classes = classNames('asset-manage-tree', className, {
    'asset-manage-tree-read-only': (reference===AssetBrowseReference||reference===ResourceBrowseReference),
    'asset-manage-tree-asset-mount-reference': reference===AssetMountReference,
  });  

  return (
    <Card
      className={classes}
      title={ (reference===AssetBrowseReference||reference===ResourceBrowseReference || reference===AssetMountReference) ? null : (
        <div
          className='flex'
          style={{
            height: 57,
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '0 15px'
          }}
        >
          <Select 
            loading={loadingTemplates}
            size='small'
            value={currentTemplateType}
            onChange={(val) => {
              setTemplateType(val)
              LocalStorage.set(`templateType-${appId}`, val);
              let event = new Event('storage');
              event.key = 'assetTemplateChange';
              window?.dispatchEvent(event);

              setCurrentDirId();
              onSelect?.(null, null);
              setTimeout(() => {
                onSelect?.('', '');
                getAllDirectoryAsTree(true)
              }, 100)
            }}
            style={{ width: 100 }}
          >
          {
            (templates??[]).map((item, index) => <Select.Option key={index} value={item.type}>{item.name}</Select.Option>)
          }
          </Select>
          {myAssets ? (
            <Tooltip title="刷新目录">
              <ReloadOutlined className='default' onClick={refreshTree} style={{ fontSize:16,cursor:'pointer' }} />
            </Tooltip>
          ) : (
            <>
              <Tooltip title="新增目录">
                <PlusOutlined className={(currentDir?.resourceType==='custom')?'disable': 'default'} onClick={addDir} style={{ fontSize:16,cursor: (currentDirType==='custom')?'not-allowed':'pointer' }}/>
              </Tooltip>
              <Tooltip title="刷新目录">
                <ReloadOutlined className='default' onClick={refreshTree} style={{ fontSize:16,cursor:'pointer' }} />
              </Tooltip>
              <Tooltip title="导入目录">
                <ImportOutlined className={(currentDirType==='custom')?'disable': 'default'} onClick={importDir} style={{ fontSize:16,cursor:(currentDirType==='custom')?'not-allowed':'pointer' }} />
              </Tooltip>
              <Dropdown overlay={exportMenu} placement="bottomCenter" >
                <Tooltip title="导出目录">
                  <ExportOutlined className='default' style={{ fontSize:16,cursor:'pointer' }} />
                </Tooltip>
              </Dropdown>
            </>
          )}
          {/* <Tooltip title="自定义目录">
            <SettingOutlined className='default' onClick={customDir} style={{ fontSize:16,cursor:'pointer' }} />
          </Tooltip> */}
        </div>
      )}
      bordered={false} 
      bodyStyle={{ padding: (reference===AssetMountReference)?0:'10px 15px' }}
      headStyle={{ padding: 0 }}
      style={{ width: '100%' }} 
    >
      {
        (metadataIds??[]).length>0 && <div className='mb-3'>
          <Select 
            loading={loadingTemplates}
            size='small'
            value={currentTemplateType}
            onChange={(val) => {
              setTemplateType(val)
              LocalStorage.set(`templateType-${appId}`, val);
              setCurrentDirId();
              onSelect?.(null, null);
              setTimeout(() => {
                onSelect?.('', '');
                getAllDirectoryAsTree(true)
              }, 100)
            }}
            style={{ width: 100 }}
          >
          {
            (templates??[]).map((item, index) => <Select.Option key={index} value={item.type}>{item.name}</Select.Option>)
          }
          </Select>
        </div>
      }
      <Spin spinning={loading}>
        <AutoComplete
          allowClear
          value={keyword}
          style={{ marginBottom: 10, width: '100%' }}
          placeholder='搜索目录'
          onSelect={onAutoCompleteSelect}
          onSearch={onAutoCompleteSearch}
          onClear={() => { setKeyword(''); }}
          notFoundContent={keyword?<span>暂无数据</span>:null}
        >
        {
          (options||[]).map((item, index) => {
            return (
              <Option key={item.key} value={item.value}>
                <div style={{ whiteSpace: 'normal' }}>
                {highlightSearchContentByTerms(item.value, [keyword])}
                </div>
              </Option>
            );
          })
        }
        </AutoComplete>
        <Tree
          className='tree-contextmenu'
          checkable={checkable}
          showLine={true}
          showIcon={false}
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          treeData={loop(treeData)}
          loadData={onLoadData}
          loadedKeys={loadedKeys}
          selectedKeys={[currentDirId||'']} 
          onSelect={onTreeSelect} 
          onCheck={onTreeCheck}
          checkedKeys={checkedKeys}
          checkStrictly
          onRightClick={({event, node}) => {
            if (reference === AssetManageReference) {
              setCurrentRightClickDir(node);
              setCurrentDirType(node.type||'');
              displayMenu(event);
            }
          }}
        />
      </Spin>

      <UpdateDirectoryModal 
        visible={ updateDirectoryModalVisible }
        onCancel={ onUpdateDirectoryCancel }
        action={ updateDirectoryAction }
        dirId={ (updateDirectoryAction==='add')?currentDirId:currentRightClickDir.nodeId }
      />
      <ImportDirectory 
        visible={ importDirectoryVisible }
        onCancel={ onImportDirectoryCancel }
        dirId={ currentDirId }
      />
      <CustomDirectoryModal 
        visible={ customDirectoryModalVisible }
        onCancel={ onCustomDirectoryCancel }
        action={ customDirectoryAction }
        dirId= { currentDirId }
      />
      {
        (reference!==AssetMountReference) && <RcMenu id={MENU_ID}>
          {
            currentRightClickDir && (currentRightClickDir.type!=='custom') && <RcItem id="edit" onClick={editDir}>
            { (currentRightClickDir.level===1)?'修改栏目':'修改目录' }
            </RcItem>
          } 
          <RcItem id="up" onClick={() => { moveNode(1); }}>
          { (currentRightClickDir.level===1)?'上移栏目':'上移目录' }
          </RcItem> 
          <RcItem id="down" onClick={() => { moveNode(-1); }}>
          { (currentRightClickDir.level===1)?'下移栏目':'下移目录' }
          </RcItem>
          {
            currentRightClickDir && (currentRightClickDir.type!=='custom'||(currentRightClickDir.type==='custom'&&currentRightClickDir.level===2)) && <RcItem id="delete" onClick={deleteDir}>
            { (currentRightClickDir.level===1)?'删除栏目':'删除目录' }
            </RcItem>
          } 
        </RcMenu> 
      } 
      {contextHolder}
    </Card>
  )
}

export default AssetManageTree;