import React, { Component } from 'react';
import {getImageUrl} from "educoder";
import RepositoryDirectories from './RepositoryDirectories';
import { Button ,Tree,Icon,Modal,Tooltip} from "antd";
import axios from 'axios';
import {Link} from 'react-router-dom';
import RepositoryCombinePath from './RepositoryCombinePath';
import RepositoryNoneData from './RepositoryNoneData';
import Repositoryfile from './Repositoryfile';
import './Repository.css';
const { confirm } = Modal;
const $ = window.$;
const { TreeNode, DirectoryTree } = Tree;
// 点击按钮复制功能
function jsCopy(){
  var e = document.getElementById("copy_rep_content");
  e.select();
  document.execCommand("Copy");
}
/**
 提交记录
 使用指南
 */
class Repository extends Component {
  constructor(props) {
    super(props);
    this.state={
      evaluationvisible:false,
      ischecke:false,
      ischeckevalue:"",
      trees:undefined,
      treesdelecttype:true
		}
  }

  componentDidMount() {
    this.setState({
      trees:this.props.trees
    })
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevProps!=this.props){
      this.setState({
        trees:this.props.trees,
        ischecke:false,
        ischeckevalue:""
      })

    }
  }
  onRepoFileClick = (item) => {
    this.props.fetchRepo(item)
  }

  NewFolder=()=>{
    this.setState({
      evaluationvisible:true
    })
  }

  hideNewFolder=()=>{
    this.setState({
      evaluationvisible:false
    })
  }

  onSelectDirectoryTree=(selectedKeys, info)=>{
    this.setState({
      ischecke:false,
      ischeckevalue:""
    })
    this.onRepoFileClick(info.node.props.item)
  }

   showDeleteConfirm =()=>{

    let that=this;
    if(this.state.ischeckevalue===""){
      this.props.showNotification("请选择要删除的文件")
      return
    }else{
      confirm({
        title: '确认需要删除该文件?',
        centered:true,
        okText: '确定',
        cancelText: '取消',
        onOk() {
          that.onAttachmentRemove()
        }
      });
    }

  }
  onAttachmentRemove=()=>{

    let shixunId = this.props.match.params.shixunId;
    let matchpath =this.props.match.path;
    let Repositoryflag =undefined;

    if( matchpath.indexOf("repository")>-1){
      Repositoryflag =undefined;
    }
    if(matchpath.indexOf("secret_repository")>-1){
      Repositoryflag =true;
    }

    let newfilspath=this.state.ischeckevalue;

    let path="";

    if(this.props.pathArray.length>0){
      this.props.pathArray.map((item,key)=>{
        if(key===0){
          path=item
        }else{
          path=path+"/"+item
        }
      })
    }
    let pathtype=path;
    if(path===undefined||path===""){
      path=newfilspath
    }else{
      path=path+"/"+newfilspath
    }
    let gototype;
    if(pathtype){
      gototype=1
    }else{
      gototype=2
    }

    const url = `/shixuns//${shixunId}/delete_git_file.json`;

    axios.delete(url, { data: {
        path:path,
        message:"删除"+newfilspath,
        secret_repository:Repositoryflag
      }})
      .then((response) => {
        if(response.data.status == 0) {
          this.setState({
            treesdelecttype:false
          })
           this.props.showNotification("删除成功")
           if(gototype===1){
             if(this.state.trees.length>1){
               this.state.trees.map((item,key)=>{
                 if(item.name===newfilspath){
                   this.state.trees.splice(key,1)
                 }
               })
             }else{
               this.props.fetchRepo(this.props.pathArray.length-1)
             }
           }else{
             this.state.trees.map((item,key)=>{
               if(item.name===newfilspath){
                 this.state.trees.splice(key,1)
               }
             })
           }
            this.setState({
              ischecke:false,
              ischeckevalue:"",
              treesdelecttype:true
            })

        }
      })
      .catch(function (error) {
        console.log(error)
      });
  }
  onCheck = (checkedKeys, info) => {

    if(checkedKeys.length===0){

      this.setState({
        ischecke:false,
        ischeckevalue:""
      })
    }

     if(info.node.props.title&&checkedKeys.length!=0){

       this.setState({
           ischecke:true,
           ischeckevalue:info.node.props.title
       })
     }
   };
  render() {
    let { match, author, git_url, lastest_commit,repositoryLoading, commits,pathArray , TPMRightSectionData } = this.props;
    let{trees,treesdelecttype}= this.state;
    let matchpath =this.props.match.path;
    let Repositoryflag ="";

    if( matchpath.indexOf("repository")>-1){
      Repositoryflag ="repository";
    }

    if(matchpath.indexOf("secret_repository")>-1){
      Repositoryflag ="secret_repository";
    }

    if (!author) {
      author = {}
    }
    let userauthority=false;
    if(this.props.author!=undefined){
      userauthority=this.props.author.login===""||this.props.author.user_id===""||this.props.author.login===null||this.props.author.user_id===null;
    }

    return (
      <React.Fragment>
        {this.state.evaluationvisible===true?<Repositoryfile
          {...this.state}
          {...this.props}
          Repositoryflag={Repositoryflag}
          hideNewFolder={()=>this.hideNewFolder()}
        />:""}
        { repositoryLoading ? <div style={{ minHeight: '500px'}}></div> :
          <div  className="mb10" id="collaborators_list_info">
            <div className="clearfix edu-back-white">
              <div className="padding16-20 clearfix borbotF4">
                <div className="fl1 clearfix1 mr201">
                  <div className="repositorytitle">
                    <div className="fl font-12 color-grey-9 pr">
                      <label className="fl Websiteclone">网址克隆：</label>
                      <div className={"fl copy_rep_contentbox"}>
                      <input type="text" id="copy_rep_content" className="fl url-input mt2"
                             defaultValue={ git_url } style={{width: 266}}/>
                        <Tooltip placement="topLeft" title={"点击复制版本库"}>
                          <a onClick={() => {jsCopy()}} className="fl ml5">
                            <i className="iconfont icon-fuzhi2 colorbe" style={{lineHeight: '18px'}}></i>
                          </a>
                        </Tooltip>

                      </div>
                      <style>
                        {`
                      .top-black-trangle {
                        right: 68px;

                      }
                      a.guideBtn {
                        color: #4CACFF !important;
                        margin-left: 4px;
                      }
                      a.guideBtn:hover {
                        text-decoration: underline;
                      }

                      #repository_url_tip {
											top: 30px !important;
										  left:111px !important;
											width: 292px !important;
                      }
                      `}
                      </style>
                      {/* <a href="https://www.educoder.net/forums/2784" target="_blank"
                      className="fr edu-default-btn edu-greenback-btn">Git使用指南</a> */}


                      <a
                        onClick={() => { $('#repository_url_tip').css('display') === 'none'
                          ? $('#repository_url_tip').show()
                          : $('#repository_url_tip').hide() }}
                        className="fl ml6 mt4">
                        {/*<img src={getImageUrl("images/educoder/problem.png")}/>*/}
                        <i className="iconfont icon-tishi2 colorbe"></i>
												<div className="invite-tip clearfix none" id="repository_url_tip"
														 style={{  width: '300px', display: 'none'}}>
													<span className="top-black-trangle" style={{"right":"0px"}}></span>
													<div className="padding16 invitecontent clearfix">
														<p className="font-12 edu-txt-left">请上传当前实训中各个关卡涉及的所有文件<br/>
															包括任务文件、执行文件，以及其他的必须文件<br/><br/>
															提交代码的方法：<br/>
															1、在电脑上安装Git tortoise客户端，或者其它熟悉的Git客户端,在Git客户端上向左侧的地址提交代码<br/>
                              2.直接在平台上新建文件/文件夹，或者拖拽上传相关代码文件<br/><br/>
															注意:<br/>
															请在Git客户端要求填写时，按照如下说明填写：<br/>
															* 用户名：使用您在本平台绑定的邮箱<br/>
															* 口令：使用您在本平台的登录口令
														</p>
													</div>
													<p className="inviteTipbtn with100"><a
														onClick={() => { $('#repository_url_tip').css('display') === 'none'}}>知道了</a></p>
												</div>
                      </a>

                    </div>

                    {
                      this.props.current_user && ( this.props.identity<5||this.props.current_user.business==true || this.props.current_user.admin==true || (TPMRightSectionData && TPMRightSectionData.creator && TPMRightSectionData.creator.login == this.props.current_user.login)) ?
                        // !this.props.secret_repository_tab &&
                        (
                          <div>
                            <Button type="primary"
                                    onClick={this.NewFolder}
                                    className="edu-default-btn edu-greenback-btn  mt5 fr"
                            >新建文件夹</Button>

                            <Link to={`/shixuns/${match.params.shixunId}/${Repositoryflag}/add_file`}>
                              <Button type="primary"
                                      className="edu-default-btn edu-greenback-btn  mt5 mr10 fr"
                              >新建文件</Button>
                            </Link>

                            <Link to={`/shixuns/${match.params.shixunId}/${Repositoryflag}/upload_file`}>
                            <Button type="primary"
                                    className="edu-default-btn edu-greenback-btn  mt5 mr10 fr"
                            >上传文件</Button>
                            </Link>
                          </div>
                        )

                        :""
                    }

                  </div>



                </div>
              </div>

              <style>
                {`
              .va_sub {
                vertical-align: sub;
              }
            `}
              </style>

              {/*私密版本库*/}
              {this.props.secret_repository_tab && (
                <div className={"combinePathEditRow padding040pxRepository"}>
                  <div className={"colorFF6601"}>私密版本库的文件对学员始终隐藏，无法访问查看。 </div>
                  <div className={"colorFF6601"}>若评测学员任务需要使用私密版本库的文件，请指定将私密版本库合并到常规版本库的目标路径，以确保评测时能访问私密版本库的文件。</div>
                </div>
              )}
            {  trees === undefined || trees === null ||trees.length===0? "":this.props.secret_repository_tab && <div className={"padding020Repository mt20"}>
                  <RepositoryCombinePath {...this.props}></RepositoryCombinePath>
              </div> }


              {/* 用户、最近提交时间 */}
              {
                trees === undefined || trees === null ||trees.length===0? <RepositoryNoneData></RepositoryNoneData>:
                  <div className={"padding020Repository"}>
										{commits===undefined?"":commits===null||commits.length===0?"":<div className="padding0-12 clearfix height7052pxRepositor borbotF4">
                      <img alt={author.name} className="radius fl mr10 mt5"
                           height="35"
                           src={getImageUrl(`images/`+commits[0].author.image_url)}
                           style={{display:userauthority===true?"none":"block"}}
                           width="35"/>
                      <a href={author.user_url} className="mr5 va_sub color-grey-8" target="_blank">{commits[0].author.name}</a>
                      <span className="color-grey-8 va_sub">提交于
                                <acronym title={commits[0].time}>
                                  {commits===undefined?"":commits[0].time}
                                </acronym> ：{commits===undefined?"":commits[0].title}
                              </span>
                      <Link to={`/shixuns/${match.params.shixunId}/${this.props.secret_repository_tab ? 'secret_repository' : 'repository'}/${match.params.shixunId}/commits`}
                         className="color-grey-8 fr font-16 mt3">
                        <i className="iconfont icon-tijiaojilu font-18 fl mr5"></i>
                        <span className="fl color-grey-8 ">提交记录</span>
                      </Link>
                    </div>}


                    {/*className="padding20" */}
                    <div style={{minHeight: '372px'}}>
                      <div>
                        {/* 当前目录位置 */}
                        <div className={"mb10"}>
                          <RepositoryDirectories {...this.props}></RepositoryDirectories>
                        </div>

                        {/*<div className="versionFileList">*/}
                        {/*  { trees === undefined ?"": trees === null || trees.length===0?"":trees.map((item, index) => {*/}
                        {/*    return (*/}
                        {/*      <li id={`file${index}`} key={index} className=" file padding5-10">*/}
                        {/*                        <span style={{marginLeft: '0px'}} className="task-hide">*/}
                        {/*                          <i className={`${item.type === 'tree' ? 'icon-wenjianjia' : 'icon-zuoye'}*/}
                        {/*                            iconfont color-blue`}></i>*/}
                        {/*                          <a*/}
                        {/*                            onClick={() => this.onRepoFileClick(item)}>*/}
                        {/*                            &nbsp;{item.name}*/}
                        {/*                          </a>*/}
                        {/*                        </span>*/}
                        {/*      </li>*/}
                        {/*    )*/}
                        {/*  })}*/}
                        {/*</div>*/}

                        { this.props.current_user && (this.props.identity<5||this.props.current_user.business==true || this.props.current_user.admin ==true || (TPMRightSectionData && TPMRightSectionData.creator && TPMRightSectionData.creator.login == this.props.current_user.login)) ?
                          <Button size={"small"} className={"fr"} type="link" onClick={this.showDeleteConfirm}>删除</Button>:""}
                        <div className={"both"}></div>

                        <style>
                          {
                            `
                            .reposanttreeswitcher .ant-tree-switcher{
                                display: none !important;
                             }
                            `
                          }
                        </style>


                        <DirectoryTree
                          className={"reposanttreeswitcher"}
                          multiple
                          defaultExpandAll
                          checkable={ this.props.current_user && (this.props.identity<5||this.props.current_user.business==true ||this.props.current_user.admin ==true || (TPMRightSectionData && TPMRightSectionData.creator && TPMRightSectionData.creator.login == this.props.current_user.login)) ?true:false}
                          onSelect={this.onSelectDirectoryTree}
                          onCheck={this.onCheck}
                        >
                          {treesdelecttype===false || trees === undefined ?"": trees === null || trees.length===0?"":trees.map((item, index) => {
                            return (
                                <TreeNode className={item.type==='tree'?"pl23":""} checkable={item.type==='tree'?false:true} disableCheckbox={this.state.ischeckevalue===item.name?false:this.state.ischecke?true:item.type==='tree'?true:false} item={item} title={`${item.name}`} key={item.type==='tree'?"0-0":`0-0-${index}`} icon={item.type==='tree'?<i className="iconfont icon-xingzhuangjiehebeifen color-blue font-12" />:<i className="iconfont icon-xingzhuangjiehe color-blue font-12"/>} id={`file${index}`}  key={index}>

                                </TreeNode>
                            )})}
                        </DirectoryTree>
                      </div>
                    </div>

                  </div>
              }
            </div>
          </div>
        }
        {    trees === undefined || trees === null ||trees.length===0?"":<a href="/forums/2784" target="_blank"
           className=" guideBtn" >Git使用指南</a>}
        {/* 当前分支的文件 */}
      </React.Fragment>

    );
  }
}


export default Repository;
