import { Base64 } from 'js-base64';
import fetch from './fetch';

// 获取wiki列表
export function wikiPages(params) {
  return fetch({
    url: '/api/wiki/wikiPages',
    method: 'get',
    params
  });
}

// 获取单个wiki
export function getWiki(params) {
  return fetch({
    url: '/api/wiki/getWiki',
    method: 'get',
    params
  });
}

//新增wiki
export function addWiki(data) {
  return fetch({
    url: '/api/wiki/createWiki',
    method: 'post',
    data: data
  });
}

//更新wiki
export function updateWiki(data) {
  return fetch({
    url: '/api/wiki/updateWiki',
    method: 'PUT',
    data: data
  });
}

//删除wiki
export function deleteWiki(data) {
  return fetch({
    url: '/api/wiki/deleteWiki',
    method: 'DELETE',
    data,
  });
}

// 初始化sidebar文件
export async function parseSidebar(wikiList, info){
  const sidebarArr = wikiList.filter(item => item.name === '_Sidebar');
  let ReInfo = undefined;
  if(sidebarArr.length){
    // 有sidebar文件，执行解析
    // 通过getWiki获取sidebar文件内容
    await getWiki({
      ...info,
      pageName: '_Sidebar'
    }).then(res=>{
      if(res && res.message === "200"){
        const sidebarCont = Base64.decode(res.data.md_content);
        const list = wikiList.filter(item=> sidebarCont.indexOf(`[[${item.name}]]`) === -1 && item.name !== "_Sidebar");
        const wikiSidebar = list.map(item=>`\n[[${item.name}]]`).join("");
        if(list.length){
          // sidebar存在丢失的wiki
          updateWiki({
            ...info,
            pageName: '_Sidebar',
            title: '_Sidebar',
            message: '',
            content_base64: Base64.encode(`${sidebarCont}${wikiSidebar}`)
          })
        }
        ReInfo={
          menuList: markdownToTree(list.length ? `${sidebarCont}${wikiSidebar}` : sidebarCont),
          sidebar: sidebarCont
        }
      }
    })
  }else{
    // 如果没有wiki目录，那么不处理
    if(!wikiList.length){
      return
    }
    // 没有sidebar文件，根据用户的目录结构进行初始化(\n[[item.name]]结构)
    const wikiArr = [];
    wikiList.map(item=>{
      wikiArr.push(`[[${item.name}]]`)
    });
    const wikiSidebarStr = wikiArr.join('\n');
    await addWiki({
      ...info,
      pageName: '_Sidebar',
      title: '_Sidebar',
      message: '',
      content_base64: Base64.encode(wikiSidebarStr)
    })
    ReInfo={
      menuList: markdownToTree(wikiSidebarStr),
      sidebar: wikiSidebarStr
    }
  }
  return ReInfo;
}

export function markdownToTree(markdownText){
  const lines = markdownText.split('\n');
  let key = -1;
  // stack: [{一级目录}，{二级目录}]
  let stack = [];
  let root = {
    title: "root",
    children: [],
    key: key++
  }
  lines.map((item, index) =>{
    const title = item.trim();
    const node = {
      title: item,
      children: [],
      key: undefined
    }
    // level：空格的个数(层级)
    const level = item.search(/\S/);
    if(!level){
      node.key = key+"";
      key++;
      // push根目录
      stack = [];
      stack.push(node);
      root.children.push(node);
    }else{
      // 解析子目录
      // 当前节点的父节点
      const parentNode = stack[level-1];
      // 当前节点的顶级跟节点
      const rootNode = root.children.filter(i => i.key === stack[0].key)[0];
      if(level === 1){
        // 二级目录
        node.key = `${rootNode.key}-${rootNode.children.length}`;
        rootNode.children.push(node);
      }else{
        // 更深的层级 找key = stack最后一个item的key
        const parentNodeByRoot = findNodeByKey(rootNode.children, parentNode.key);
        node.key = `${parentNodeByRoot.key}-${parentNodeByRoot.children.length}`
        parentNodeByRoot && parentNodeByRoot.children.push(node);
      }
      // 下一个节点的空格个数(层级)
      const nextNodeLevel = lines[index+1] && lines[index+1].search(/\S/);
      if(nextNodeLevel>level && (title.startsWith('- ') || title.startsWith('* '))){
        stack.push(node);
      }else if(nextNodeLevel<level){
        stack.pop()
      }
    }
  })
  return root.children;
}

export function findNodeByKey(list, key){
  for (let index = 0; index < list.length; index++) {
    const element = list[index];
    if (element.key == key) {
      return element;
    }else if (element.children.length) {
      let result = findNodeByKey(element.children, key);
      if (result) {
        return result;
      }
    }
  }
  return undefined;
}

// 找到children中有相同key的数组
export function findNodeByChildrenKey(list, key){
  for (let index = 0; index < list.length; index++) {
    const element = list[index];
    if (element.key == key) {
      return list;
    }else if (element.children.length) {
      let result = findNodeByChildrenKey(element.children, key);
      if (result) {
        return result;
      }
    }
  }
  return [];
}

// 目录结构转md内容
export function treeToMd(treeList){
  const list = []
  readList(list, treeList)
  return list.join('\n');
}

function readList(list, readChildren){
  readChildren.map(item=>{
    list.push(item.title)
    readList(list, item.children)
  })
}