import React, { useEffect, useState, useRef } from 'react';
import {Card, Spin, Tooltip, Tree, Dropdown, Menu, Modal, AutoComplete, Select, Descriptions} from 'antd';
import { PlusOutlined, ImportOutlined,ExportOutlined,ReloadOutlined, SettingOutlined, UnorderedListOutlined } 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, getAssetRange } from '../../../../util';
import { AnchorTimestamp, AnchorId, AssetManageReference, AssetBrowseReference, ResourceBrowseReference, AssetMountReference, AnchorDirId, AnchorTemplateType } from '../../../../util/constant';
import { highlightSearchContentByTerms } from '../../../../util';
import { listSubject } from './AssetTable';
import Overview from './overview';
import './AssetManageTree.less';
import 'react-contexify/dist/ReactContexify.css';
import { appId } from '../../../../App';
import { getTemplateType } from '../../../../util/axios';

const { Option } = AutoComplete;

export const viewModes = [
  {
    key: 'dir',
    name: '目录视角'
  },
  {
    key: 'custom',
    name: '自定义目录视角'
  }
];

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) => {

  const MENU_ID = 'asset-manage-tree';

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

  const { checkable = false, onSelect, className, onCheck, tableId, reference=AssetManageReference, onDirectoryChange, centerId, metadataIds, onTemplateChange } = 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 [customOverview,setCustomOverview] = useState({
    visible:false,
    customItem:null
  })
  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 [metadataRelatedTemplate, setMetadataRelatedTemplate] = useState()
  const [ viewSelectedKey, setViewSelectedKey ] = useState(viewModes[0].key);

  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([]);
  const viewSelectedKeyRef = useRef(viewModes[0].key)

  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) {
          const _templateType = getQueryParam(AnchorTemplateType, props?.location?.search) || data[0].type;
          
          setTemplateType(_templateType)
          LocalStorage.set(`templateType-${appId}`, _templateType)

          const index = (data??[]).findIndex(item => item.type === _templateType)
          if (index !== -1) {
            listSubject.next({ msg: 'templateChange' })
            onTemplateChange?.(data[index])
          }
        
          onSelect?.('', '', null, false)
          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);

    function disposeData(data) {
      setLoading(false);

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

      let newData = [...data];

      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;
      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);
          setAutoExpandParent(true);

          setCurrentDirId(defaultItem.nodeId);
          setCurrentDirType(defaultItem.type||'');
          setCurrentDir(defaultItem);
          onSelect && onSelect(defaultItem.nodeId, defaultItem.type||'', defaultItem.level, defaultItem.allowdLoadDataAsset);
        
        } else if ((newData??[]).length > 0) {
          defaultItem = newData[0]
          setCurrentDirId(defaultItem.nodeId);
          setCurrentDirType(defaultItem.type||'');
          setCurrentDir(defaultItem);
          onSelect && onSelect(defaultItem.nodeId, defaultItem.type||'', defaultItem.level, defaultItem.allowdLoadDataAsset);
        } else {
          onSelect && onSelect('', '');
        }
      }
    }

    let url = 'assetmanage.queryAllDirectoryAsTree';
    if (viewSelectedKeyRef.current === 'custom') {
      url = 'assetmanage.queryCustomTypeRootDirectory';
    }

    dispatch({
      type: url,
      payload: {
        range: getAssetRange(AssetManageReference)
      },
      callback: data => {
        let newData = [];
        if (viewSelectedKeyRef.current==='dir') {
          newData = [...data];
        } else {
          newData = (data||[]).map((item) => {
            return {...item, text: item.name, nodeId: item.id, type: item.resourceType}
          });
        }

        disposeData(newData)
      },
      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, defaultItem.allowdLoadDataAsset);
    } 
  }

  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 onDetailClick = () => {
    setUpdateDirectoryAction('detail');
    setUpdateDirectoryModalVisible(true);
  }

  const editDir = () => {
    setUpdateDirectoryAction('edit');
    setUpdateDirectoryModalVisible(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 previewCustom = ()=>{
    setCustomOverview({
      visible: true,
      customItem: currentRightClickDir
    })
  }

  const editCustom = ()=>{
    setCustomDirectoryAction('edit');
    setCustomDirectoryModalVisible(true);
  }

  const deleteDir = () => {  
    console.log('currentRightClickDir', currentRightClickDir)  
    if (currentRightClickDir.nodeId) {
      modal.confirm({
        title: '您确定要删除该目录吗?',
        onOk: () => {
          dispatch({
            type: 'assetmanage.checkDirectoryDeleteAble',
            payload: {
              params: {
                dirId: currentRightClickDir.nodeId,
                currentDirIsCustom: currentRightClickDir.type==='custom'
              }
            },
            callback: able => {
              if (able === 'true') {
                dispatch({
                  type: 'assetmanage.deleteDirectory',
                  payload: {data: [ currentRightClickDir.nodeId ],              
                  params: {
                  currentDirIsCustom: currentRightClickDir.type==='custom'
                  }
                },
                  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) {
      setCurrentDirId();
      onSelect?.(undefined, '', null, false);
      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, node.allowdLoadDataAsset);
  }
  
  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 = (event) => {
    show(event, {
      position: {
        x: event.clientX + 30,
        y: event.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,
          currentDirIsCustom: true,
        },
        callback: (data) => {
          if (data && data.length>0) {
            let newTreeData = updateTreeData(treeData, key, data);
            setTreeData(newTreeData);
            treeDataRef.current = newTreeData;
          }
      
          resolve();
        }, 
        error: () => {
          resolve();
        }
      });
    });

  const onViewClick = ({ key }) => {
    if (viewSelectedKey &&  viewSelectedKey===key ) return;

    viewSelectedKeyRef.current = key;
    setViewSelectedKey(key);
    setExpandedKeys([]);
    
    getAllDirectoryAsTree();
  }  

  const viewMenus = (
    <Menu selectedKeys={[viewSelectedKey]} onClick={onViewClick}>
    {
      viewModes && viewModes.map(item => {
        return (
          <Menu.Item key={item.key} value={item.key} >
            <div style={{ textAlign: 'center' }}>
            {item.name}
            </div>
          </Menu.Item>
        )
      })
    }
    </Menu>
  );

  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}
          {
            viewSelectedKeyRef.current === 'dir' && <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);

              const index = (templates??[]).findIndex(item => item.type === val)
              if (index !== -1) {
                listSubject.next({ msg: 'templateChange' })
                onTemplateChange?.(templates[index])
              }

              setCurrentDirId();
              getAllDirectoryAsTree(true)

            }}
            style={{ width: 100 }}
          >
          {
            (templates??[]).map((item, index) => <Select.Option key={index} value={item.type}>{item.name}</Select.Option>)
          }
          </Select>
          <Dropdown overlay={viewMenus} placement="bottomLeft">
            <Tooltip title="视角">
              <UnorderedListOutlined className='default' style={{ fontSize:16,cursor:'pointer' }} />
            </Tooltip>
          </Dropdown>
          {
            viewSelectedKeyRef.current === 'dir' && <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>
          {
            viewSelectedKeyRef.current === 'dir' ? <>
              <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();
              getAllDirectoryAsTree(true)
            }}
            style={{ width: 100 }}
          >
          {
            (templates??[]).map((item, index) => <Select.Option key={index} value={item.type}>{item.name}</Select.Option>)
          }
          </Select>
        </div>
      }

      <Spin spinning={loading}>
        {
          viewSelectedKeyRef.current !== 'custom' && <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) {
              console.log('node',node);
              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 }
        node={ currentRightClickDir }
      />
      <Overview   
        visible={ customOverview.visible }
        onCancel={()=>{ 
          setCustomOverview({
            visible:false,
            customItem:null
          })
        }}
        customItem= { customOverview.customItem }
      />
      {
        (reference!==AssetMountReference) && <RcMenu id={MENU_ID}>
          {
            viewSelectedKeyRef.current==='dir' && <React.Fragment>
              <RcItem id="edit" onClick={editDir}>
                修改目录
              </RcItem>
              <RcItem id="up" onClick={() => { moveNode(1); }}>
                上移目录
              </RcItem> 
              <RcItem id="down" onClick={() => { moveNode(-1); }}>
                下移目录
              </RcItem> 
            </React.Fragment>
          }
          {
            viewSelectedKeyRef.current==='custom' && <React.Fragment>
              <RcItem id="edit" onClick={previewCustom}>
                预览
              </RcItem>
              <RcItem id="edit" onClick={editCustom}>
                编辑
              </RcItem>
            </React.Fragment>
          }
          <RcItem id="delete" onClick={deleteDir}>
            删除目录
          </RcItem>
        </RcMenu> 
      } 
      {contextHolder}
    </Card>
  )
}

export default AssetManageTree;