import React, { useEffect, useState } from 'react';
import RenderHtml from '../../components/render-html';
import { Dropdown , Menu , Spin } from 'antd';
import { Link } from 'react-router-dom';
const $ = window.$;

function CoderDepotReadme({ operate , history , readme , ChangeFile }){
  const [ menuList ,setMenuList ] = useState(undefined);

  useEffect(()=>{
    if(readme && readme.content){
      let path = history.location.pathname;
      const items = $.map($("#readme").find("h1,h2,h3,h4,h5,h6"), function (el, _) {
        const anchor = el.id;
        const level = el.tagName.replace("H", "");
        const href = `#${anchor}`;
        return { href:`${path}${href}`,text:el.textContent , level:level }
      });
      setMenuList(items);
    }
  },[readme])

  function menu(){
    if(menuList && menuList.length > 0){
      let hash = history.location.hash;
      return(
        <Menu className="menuslist">
          {
            menuList.map((item,key)=>{
              return(
                <Menu.Item key={item.id} className={decodeURI(hash).indexOf(item.text)>-1 ?"active":""}><Link to={`${item.href}`} style={{paddingLeft:`${item.level *10}px`}} title={item.text}>{item.text}</Link></Menu.Item>
              )
            })
          }
        </Menu>
      )
    }else{
      return <Spin />
    }
  }
  return(
    <div className="commonBox" id="readme">
      <div className="commonBox-title">
        <Dropdown overlay={menu()}>
          <i className="iconfont icon-zhangjie1 font-16 color-grey-3 mr10"></i>
        </Dropdown>
        <span className="commonBox-title-read">README.md</span>
        {
          operate ?
            <a className="ml20 pull-right" onClick={() =>ChangeFile(readme && readme.path, false)}>
              <i className="iconfont icon-bianji6 font-16 color-blue"></i>
            </a>
          :""
        }
      </div>
      <div className="commonBox-info">
        <RenderHtml className="break_word_comments imageLayerParent" value={readme && readme.content} url={history.location}/>
      </div>
    </div>
  )
}
export default CoderDepotReadme;