import React, { Component } from 'react';
import {Modal,Input,Form} from "antd";
import axios from 'axios';
class Repositoryfile extends Component{
  constructor(props) {
    super(props)
    this.state={
      selectpath:"",
      trees:[],
      main:[],
      path:""
    }
  }

  evaluationhideModal=()=>{
    this.props.hideNewFolder();
  }

  componentDidMount() {

    let pathArrays;
    if(this.props.pathArray){
      pathArrays=this.props.pathArray;
    }else{
      pathArrays=this.props.newathArray;
    }

    let path='';
    let ary=[];
    if(pathArrays){
      if(pathArrays.length>0){
        pathArrays.map((item,key)=>{
          if(key===0){
            path=item;
            ary.push({val:"根目录",path:""},{val:"/"+item,path:path});
          }else{
            path=path+'/'+item;
            ary.push({val:"/"+item,path:path});
          }
        })
      }
    }

    this.getdata(path,ary)

  }

  getdata(path,ary){

    let matchpath =this.props.match.path;
    let id = this.props.match.params.shixunId;

    let url ="";
    if( matchpath.indexOf("repository")>-1){
      url ="/shixuns/"+id+"/repository.json";
    }
    if(matchpath.indexOf("secret_repository")>-1){
      url ="/shixuns/"+id+"/secret_repository.json";
    }

    axios.post(url,{
      path: path
    }).then((response) => {
      if (response.data.status === 403||response.data.status === 401||response.data.status === 500) {

      }else {
        this.setState({
          trees: response.data.trees,
          path: path,
          main: ary,
        })
      }
    }).catch((error) => {
      console.log(error)
    });

  }

  goblakepath=(path,key)=>{
    let {main} =this.state;
    let matchpath =this.props.match.path;
    let id = this.props.match.params.shixunId;

    let url ="";
    if( matchpath.indexOf("repository")>-1){
      url ="/shixuns/"+id+"/repository.json";
    }
    if(matchpath.indexOf("secret_repository")>-1){
      url ="/shixuns/"+id+"/secret_repository.json";
    }
    let newmain=[]
    for(var i=0;i<=key;i++){
      newmain.push(main[i])
    }

    axios.post(url,{
      path: path
    }).then((response) => {
      if (response.data.status === 403||response.data.status === 401||response.data.status === 500) {

      }else {
        this.setState({
          trees: response.data.trees,
          path: path,
          main: newmain,
        })
      }
    }).catch((error) => {
      console.log(error)
    });


  }

  sendgetfilepath=(newpath,type)=>{

    let id = this.props.match.params.shixunId;
    let{path,main}=this.state;

    let matchpath =this.props.match.path;
    let url ="";

    if( matchpath.indexOf("repository")>-1){
      url ="/shixuns/"+id+"/repository.json";
    }
    if(matchpath.indexOf("secret_repository")>-1){
      url ="/shixuns/"+id+"/secret_repository.json";
    }
    let ary=main;
    let paths=path;
    let  mainpath;
    this.setState({
      selectpatharr:[],
    })
     mainpath=newpath;

    if(paths===""&&type==="tree"){
      if(main.length===0){
        ary.push({val:"根目录",path:""},{val:"/"+mainpath,path:mainpath});
      }else{
        ary.push({val:"/"+mainpath,path:mainpath});
      }
    }else if(paths!=""&&type==="tree"){
      newpath=paths+"/"+newpath;
      ary.push({val:"/"+mainpath,path:mainpath});
    }

      axios.post(url,{
        path: newpath
      }).then((response) => {
        if (response.data.status === 403||response.data.status === 401||response.data.status === 500) {

        }else{
          this.setState({
            trees:response.data.trees,
            path:newpath,
            main:ary,
            // selectpath:""
          })
        }

      }).catch((error) => {
        console.log(error)
      });
  }

  handleSubmit = (e) => {
    let {path,trees}=this.state;

    let matchpath =this.props.match.path;
    let flag =undefined;

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

    if(this.props.selectupfils===true){
      this.props.selectupfilspath(path);
      this.props.showNotification("选择文件目录成功")
      this.props.hideNewFolder();
    }else if(this.props.RepositoryCombinePath===true){
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if(path===""){
            this.props.selectupfilspath(values.name);
          }else{
            this.props.selectupfilspath(path+"/"+values.name);
          }
          this.props.showNotification("保存成功")
          this.props.hideNewFolder();
        }
      });
    }else{
      let url=`/shixuns/${this.props.match.params.shixunId}/upload_git_folder.json`;
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          let types=false;
          if(trees){
            trees.map((item,key)=>{
              if(item.type==="tree"){
                if(item.name===values.name){
                  types=true
                  return
                }
              }
            })
          }


          if(types===true){
            this.props.showNotification("请勿新建相同名字的文件夹")
            return
          }
          let paths;
          if(path===""){
            paths=values.name;
          }else{
            paths=path+"/"+values.name;
          }
          axios.post(url,{
            path: paths,
            secret_repository:flag===false?undefined:flag,
          }).then((result)=>{
            if(result){
              if(result.data.status===0){
                this.props.fetchRepo(this.props.pathArray.length)
                this.props.showNotification("新建成功")
                this.props.hideNewFolder();

              }
            }
          }).catch((error)=>{
            console.log(error);
          })
        }
      });
    }
  }

  render(){
    const {getFieldDecorator} = this.props.form;
    const {evaluationvisible} = this.props;
    const {selectpath,trees,main,path}=this.state;


    return(
      evaluationvisible===true?<Modal
        keyboard={false}
        title={this.props.titles?this.props.titles:"新建文件夹"}
        visible={evaluationvisible}
        closable={false}
        footer={false}
      >
        <div className="task_popup_con">
          <style>
            {
              `
              .ant-form-explain{
                  padding-left: 0px;
                  margin-top:5px;
              }
              body{
                   width: calc(100%) !important;
              }
              `
            }
          </style>
          <div className="newupload_conbox clearfix">
            <ul id="directory_file">
              {
                main.length===0?"":main.map((item,key)=>{
                  return(
                    <a className="f14 fb"  key={key} onClick={()=>this.goblakepath(item.path,key,item)}>{item.val}</a>
                  )
                })
              }
              {/*文件*/}
              {trees === undefined || trees === null ? "" : trees.map((item, key) => {
                return(
                  <li className="entry" key={key}>
                    <div className="filename_no_report hidden">{
                      item.type==="tree"?<a onClick={()=>this.sendgetfilepath(item.name,item.type)} data-remote="true">
                        <i className="iconfont icon-wenjianjia color-blue mr2"></i>
                        {item.name}</a>:""
                    }
                    </div>
                  </li>
                )
              })}
            </ul>
           <div className="clearfix mt5">
              <label className=" mt5">选中的新建文件夹目录：</label>
              <div className={"mt5 mb5"}  >{path}</div>
             {this.props.selectupfils===true?"": <Form>
                <Form.Item
                  className="mt15"
                >
                  {getFieldDecorator('name', {
                    rules: [{
                      required: true, message: '请输入名称',
                    },{
                      whitespace: true, message: '请勿输入空格'
                    }],
                  })(
                    <Input id="points_tusi" placeholder="请输入新文件夹名/子文件夹名。（如：src/step1）" className="input-60-40"
                           style={{width:"400px"}}
                        />
                  )}
                </Form.Item>
              </Form>}
            </div>

            <div className={"clearfix edu-txt-center mt20"}>
               <a className="task-btn task-btn-orange fr"
                  style={{marginTop: '20px',marginLeft:'20px'}} id="add_path"
                  onClick={() => this.handleSubmit()}>确定</a>
               <a  className="pop_close task-btn mb10 fr"
                   style={{marginTop: '20px'}} id="back_page" onClick={()=>this.evaluationhideModal()}>取消</a>
             </div>

          </div>
        </div>
      </Modal>:""
    )
  }
}

const newRepositoryfile = Form.create({name: 'newRepositoryfile'})(Repositoryfile);

export default newRepositoryfile;