import React, { useState } from 'react';
import { Button, Dropdown, Icon, Input, Menu, Tooltip, Select, Upload, message, Spin, Modal } from 'antd';
import { httpUrl, TokenKey } from '../../fetch';
import cookie from 'react-cookies';
import { updateWiki, treeToMd, addWiki } from '../../api';
import { Base64 } from 'js-base64';

export default function UploadWiki(props) {
  const { match, history, showNotification, project, fileList, setFileList, fileArrInit, setReload, butClass } = props;
  const {location:{pathname}} = history;
  let projectsId = match.params.projectsId;
  let owner = match.params.owner;

  const uploadProps = {
    name: 'multipartFile',
    withCredentials: true,
    action: `${httpUrl}/api/wikiExport/uploadWiki/${owner}/${projectsId}/${project && project.id}`,
    showUploadList: false,
    headers: {
      Authorization: cookie.load(TokenKey),
    },
    beforeUpload: beforeUpload,
    onChange(info) {
      if (info.file.status === 'done') {
        if (info.file.response.message === '201') {
          // 截取文件名称
          const fileName = info.file.name.substring(0,info.file.name.lastIndexOf("."))
          // 修改sidebar文件
          if(!fileArrInit.length){
            // 仓库没有wiki文件
            addWiki({owner,repo: projectsId,projectId: project.id,pageName: "_Sidebar",title: "_Sidebar",message: '',content_base64: Base64.encode(`[[${fileName}]]`)}).then(res=>{
              if(res && res.message === "201"){
                message.success(`${fileName} 上传成功`);
                history.push(`/${owner}/${projectsId}/wiki/${encodeURI(fileName)}/0`);
                setReload(Math.random());
              }
            })
            return;
          }
          const newSidebarList = fileList.concat({title: `[[${fileName}]]`, children: []})
          updateWikiFun(newSidebarList, 0);
          message.success(`${fileName} 上传成功`);
          history.push(`/${owner}/${projectsId}/wiki/${encodeURI(fileName)}/0`);
          setReload(Math.random());
        } else if (info.file.response.message === '500') {
          message.error(info.file.response.data || '文件上传失败');
        } else {
          message.error('文件上传失败');
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  function beforeUpload(file) {
    if (!['md', 'txt', 'markdown'].includes(file.name.split('.').pop())) {
      message.error('只能上传md、txt文件');
      return false;
    }

    let regEn = /[\\/:*?"<>|[\]-]/g;
    if (regEn.test(file.name)) {
      message.error('文件名不能有特殊字符: \\ / : * ? \" < > | [ \] -');
      return false;
    }

    for (const item of fileArrInit) {
      if (item.name === file.name) {
        message.error('不能上传与已有文件相同文件名的文件');
        return false;
      }
    }
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (!isLt100M) {
      showNotification(`文件大小必须小于${100}MB!`);
    }
    return isLt100M;
  }

  function updateWikiFun(sidebarList, type){
    updateWiki({
      owner,
      repo: projectsId,
      projectId: project.id,
      pageName: '_Sidebar',
      title: '_Sidebar',
      commit_message: '',
      content_base64: Base64.encode(treeToMd(sidebarList))
    }).then(res => {
      if (res && res.message === "200") {
        setFileList(sidebarList);
      }else {
        message.error(res.data || "操作失败");
      }
    });
  }

  return <Upload {...uploadProps}>
    <Tooltip placement="top" title={'支持导入txt、markdown格式文件'}>
      <Button type="default" className={`ml10 ${butClass}`}><Icon type="plus" />导入模板</Button>
    </Tooltip>
  </Upload>
}