import React, { useEffect, useState } from 'react';
import { Drawer , Tree , Spin } from 'antd';
import './Component.scss';
import axios from 'axios';
const { TreeNode , DirectoryTree } = Tree;

function turnbar(str){
  if(str && str.length>0 && str.indexOf("/")>-1){
    return str.replaceAll('/','%2F');
  }
  return str;
}
function DrawerPanel({visible,onClose,branch,owner,projectsId,history, name , list}){
  const [ treeData , setTreeData ] = useState(undefined);
  const [ isSpin , setIsSpin ] = useState(true);
  const [first , setFirst ] = useState(true);
  useEffect(()=>{
    if(visible && first){
      if(list){
        setTreeData(list);
        setIsSpin(false);
      }else{
        getMenulist();
      }
      setFirst(false);
    }
  },[visible])

  function getMenulist(){
    const url = `/${owner}/${projectsId}/entries.json`;
    axios.get(url,{ params: { ref: branch } }).then(result=>{
      if(result){
        setTreeData(result.data.entries);
      }
      setIsSpin(false);
    }).catch(error=>{})
  }

  function renderTreeNodes(data) {
    return data && data.length > 0 && data.map((item) => {
      return (
        <TreeNode title={item.name} key={item.key} dataRef={item} isLeaf={item.type === "file"}>
          {renderTreeNodes(item.children)}
        </TreeNode>
      );
    });
  }

  function onLoadData(tr){
    return new Promise((resolve) => {
      if (tr.props.children) {
          resolve();
          return;
      }
      let en = [];
      const url = `/${owner}/${projectsId}/sub_entries.json`;
      axios.get(url, { 
        params:{
          filepath:tr.props.dataRef.path,
          ref:branch,
          type:"dir"
        }
      }).then((result) => {
        if(result){
          en =  result.data.entries;
        }
      }).catch(error=>{})
      setTimeout(() => {
        tr.props.dataRef.children = en;
        setTreeData([...treeData]);
        resolve();
      }, 2000);
    });
  }

  function selectTree(keys,event){
    let dataref = event.node.props.dataRef;
    if(dataref.type==="file"){
      onClose();
      let value = turnbar(branch);
      history.push(`/${owner}/${projectsId}/tree/${value}/${dataref.path}`);
    }
  }

  return(
    <Drawer
      placement="left"
      visible={visible}
      closable={false}
      onClose={onClose}
      width={"320px"}
      maskStyle={{backgroundColor:'rgba(0,0,0,0.09)'}}
    >
      <Spin spinning={isSpin}>
        <div className="drawerHead">
          <p className="font-20">{name}</p>
          <p><i class="iconfont icon-fenzhi2 font-18 color-grey-9 mr3"></i>{branch}</p>
        </div>
        <DirectoryTree loadData={onLoadData} onSelect={selectTree}>
          {treeData && renderTreeNodes(treeData)}
        </DirectoryTree>
      </Spin>
    </Drawer>
  )
}
export default DrawerPanel;
