import React, { useEffect, useState } from 'react';
import { Input, Button,  Select, Dropdown, Icon, Menu, message, Tree } from 'antd';
import CopyTool from '../Component/CopyTool';
import { wikiPages, getWiki, parseSidebar, } from './api';
import { httpUrl } from './fetch';
import './Index.scss';
import { Base64 } from 'js-base64';
import RenderHtml from '../../components/render-html';
const {DirectoryTree, TreeNode} = Tree;
const InputGroup = Input.Group;
const { Option } = Select;

export default (props) => {
  const { match, history, showNotification } = props;

  let projectsId = match.params.projectsId;
  let owner = match.params.owner;

  let projectName = match.params.projectName;
  let projectId = match.params.projectId;
  let key = 1;

  const [checkItem, setCheckItem] = useState({});
  const [itemDetail, setItemDetail] = useState({});

  const [fileArr, setFileArr] = useState([]);
  const [urlType, setUrlType] = useState('HTTPS');
  const [fileList, setFileList] = useState([]);

  useEffect(()=>{
    if(checkItem && checkItem.name){
      document.title = `${checkItem.name}-维基预览`
    }
  }, [checkItem])

  useEffect(() => {
    projectsId && wikiPages({
      owner: owner,
      repo: projectsId,
      projectId: projectId,
    }).then(async res => {
      if (res && res.message === "200") {
        setFileArr(res.data);
        // 解析sidebar获取目录list
        const info = await parseSidebar(res.data, {
          owner: owner,
          repo: projectsId,
          projectId
        })
        const {menuList, sidebar} = info;
        setFileList(menuList);
        if (res.data.length) {
          setCheckItem(res.data[0]);
        };
      } else {
        showNotification("加载失败")
      }
    });
  }, [])


  useEffect(() => {
    projectsId && checkItem.name && getWiki({
      owner: owner,
      repo: projectsId,
      pageName: checkItem.name,
      projectId: projectId,
    }).then(res => {
      if (res && res.message === "200") {
        setItemDetail(res.data);
      } else {
        showNotification("加载失败")
      }
    });
  }, [checkItem]);

  function goBack() {
    history.push(`/${owner}/${projectsId}/wiki`);
  }

  // 支持 Markdown，Html，Pdf格式文件
  const menu = (
    <Menu >
      <Menu.Item key="1" onClick={() => { downloadWiki('markdown') }}>
        Markdown
      </Menu.Item>
      <Menu.Item key="2" onClick={() => { downloadWiki('html') }}>
        HTML
      </Menu.Item>
      <Menu.Item key="3" onClick={() => { downloadWiki('pdf') }}>
        PDF
      </Menu.Item>
    </Menu>
  );

  function downloadWiki(type) {
    window.open(`${httpUrl}/api/wikiExport/wikiExport-wrapper?repoName=${projectsId}&owner=${owner}&type=${type}&projectName=${projectName}&projectId=${projectId}`);
  }

  function renderTreeNodes(data) {
    return data && data.length > 0 && data.map((item) => {
      let title = item.title.trim();
      const isFile = title.startsWith('[[') && title.endsWith(']]');
      title = isFile ? title.substring(2,title.length-2) : title.substring(2, title.length);
      return (
        <TreeNode title={title} key={key++} isLeaf={isFile} dataRef={item}>
          {renderTreeNodes(item.children)}
        </TreeNode>
      );
    });
  }

  function selectTree(keys,event){
    let {title, key} = event.node.props.dataRef;
    title = title.trim()
    const isFile = title.startsWith('[[') && title.endsWith(']]');
    if(isFile){
      title = title.substring(2,title.length-2);
      setCheckItem({name: title, key});
    }
  }

  return (
    <div className="wiki-preview">
      <div className="preview-head">
        <div className="preview-head-left" onClick={goBack}>
          <i className="iconfont icon-wendangyulan_icon mr3"></i>
          <span className="ml10">{projectName}</span>
        </div>
        <div className="preview-head-right">
          <span className="copy-desc font-16">克隆地址</span>
          {
            fileArr.length && fileArr[0].wiki_clone_link ? <InputGroup className="copy-url" compact>
              <Select dropdownClassName="wiki-url-type" defaultValue="HTTPS" onChange={(v) => { setUrlType(v) }}>
                <Option value="HTTPS">HTTPS</Option>
                <Option value="SSH">SSH</Option>
              </Select>
              <Input id="wikiUrl" value={urlType === 'HTTPS' ? fileArr[0].wiki_clone_link.https : fileArr[0].wiki_clone_link.ssh} />
              <CopyTool className="copy-wiki" inputId="wikiUrl"/>
            </InputGroup> : ''
          }

          <Dropdown overlay={menu}>
            <Button className="ml10">导出<Icon type="caret-down" /></Button>
          </Dropdown>
        </div>
      </div>


      <div className="wiki-body">
        <div className="wiki-nav previewWiki">
          {/* {
            fileArr.map(item => {
              return <div className={`${item.name === checkItem.name ? 'active' : ''} wiki-nav-title`} key={item.name} onClick={() => { setCheckItem(item) }}>
                <span className="nav-title-left" >
                  <i className="iconfont icon-wenjianjia2 mr3"></i>
                  <span className="nav-title-left-text">{item.name}</span>
                </span>
              </div>
            })
          } */}
          {/* 读sidebar转换成目录树 */}
          {fileList && fileList.length ? <DirectoryTree onSelect={selectTree} defaultExpandAll>
            {renderTreeNodes(fileList)}
          </DirectoryTree> : ''}
        </div>

        <div className="wiki-content previewContent">
          <div className="wiki-content-head">
            <h3 className='mt10 pb10'>{checkItem.name}</h3>
          </div>

          {itemDetail && itemDetail.md_content && <RenderHtml className="wiki-content-detail editor-content-panel markdown-body" value={Base64.decode(itemDetail.md_content)} url={history.location}/>}
        </div>
      </div>


    </div>
  )
}