import React, { useEffect, useState } from 'react';
import RenderHtml from '../../components/render-html';
import { AlignCenter } from '../Component/layout';
import { Dropdown , Anchor , Spin } from 'antd';

import ReadmeCatelogue from './sub/ReadmeCatelogue';
const $ = window.$;

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

  useEffect(()=>{
    if(readme && readme.replace_content){
      setContent(readme.replace_content);
    }else{
      setContent(undefined);
    }
  },[readme])

  useEffect(()=>{
    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:`${href}`,text:el.textContent , level:level }
    });
    setMenuList(items);
  },[content])

  function menu(){
    if(menuList && menuList.length > 0){
      return(
        <ReadmeCatelogue menuList={menuList} hash={history.location.hash}/>
      )
    }else{
      return <Spin />
    }
  }

  return(
    <div className="commonBox readBox" id="readme">
      <Anchor offsetTop={58}>
        <div className="commonBox-title boxTitle">
          <AlignCenter>
            <Dropdown overlay={menu()} trigger={['hover']} overlayClassName="menuslist">
              <span className="catelogue">
                <i className="iconfont icon-muluicon font-12 mr5"></i>
                <span>目录</span>
              </span>
            </Dropdown>
            
              <span className="commonBox-title-read"><a href="#readme ">README.md</a></span>
            
          </AlignCenter>
          {
            operate ?
              <a className="ml20 pull-right" onClick={() =>ChangeFile(readme && readme.path, false)}>
                <i className="iconfont icon-a-bianji font-17 color-grey-6"></i>
              </a>
            :""
          }
        </div>
      </Anchor>
      {
        content && 
        <div className="commonBox-info">
          <RenderHtml className="break_word_comments imageLayerParent" value={content} url={history.location}/>
        </div>
      }
    </div>
  )
}
export default CoderDepotReadme;