import React , { useState , useEffect } from 'react';
import { Input } from 'antd';
import './index.scss';

function FileName({
onChangeFile,addonBefore , name , empty , onEmpty
}){
  const [ defaultUrl , setDefaultUrl ] = useState(undefined);
  const [ newUrl , setNewUrl ] = useState([]);
  const [ value , setValue ] = useState(undefined);

  useEffect(()=>{
    if(name){
      let v ="";
      if(name.indexOf("/")>-1){
        let s = name.split("/");
        v = s[s.length-1];
        console.log(v);
        setValue(v);
      }else{
        v=name;
        setValue(name);
      }
      let a  = newUrl && newUrl.length > 0 ? newUrl.join("/")+"/" +v : v ;
      onChangeFile(a);
    }else{
      setValue(undefined);
    }
  },[name])


  useEffect(()=>{
    if(addonBefore){
      setDefaultUrl(addonBefore.split('/'));
    }
  },[addonBefore])

  function keyUpFun(e){
    const key = e.keyCode;
    if(key === 8){
      //当input框无数据、新加过文件夹、点击删除键时
      if(value === undefined && (newUrl && newUrl.length>0)){
        const last = newUrl[newUrl.length-1];
        let n = newUrl;
        n.splice(n.length-1,1);
        setNewUrl(n);
        setValue(last);
      }
    }
  }

  function changeValue(e){
    const value = e.target.value;
    if(value){
      if(value === "/"){
        setValue(undefined);
      }
      else if(value.indexOf("/")>-1){
        let a = value.split("/");
        let b = newUrl;
        let c = b.concat(a[0]);
        setNewUrl(c);
        let v = a[a.length-1];
        setValue(v);
        if(v){
          onChangeFile(c && c.length > 0?c.join("/")+"/"+v:v);
          onEmpty && onEmpty(false);
        }else{
          clearvalue();
        }
      }else{
        let a  = newUrl && newUrl.length > 0 ? newUrl.join("/")+"/" +value : value ;
        onChangeFile(a);
        setValue(value);
        onEmpty && onEmpty(false);
      }
    }else{
      clearvalue();
    }
  }

  function clearvalue(){
    if(newUrl && newUrl.length>0){
      setTimeout(()=>{setValue(undefined)},200);
    }else{
      setValue(undefined);
    }
    onEmpty && onEmpty(true);
  }

  const renderList=(list)=>{
    return(
      <div>
        {
          list.map((i,k)=>{
            return(
              i && <span>{i}<span className="ml2 mr3">/</span></span>
            )
          })
        }
      </div>
    )
  }
  return(
    <div className="fileName">
      {
        defaultUrl && defaultUrl.length>0 ? renderList(defaultUrl) : ""
      }
      {
        newUrl && newUrl.length>0 ? renderList(newUrl) : ""
      }
      <Input 
        placeholder="命名文件名称或文件路径"
        value={value} 
        onKeyUp={keyUpFun} 
        onChange={changeValue}
        style={{width:"220px",borderColor:empty===true ? "red":"grey"}}
      />
      {empty && <p className="color-red ml20">请输入文件名称</p>}
    </div>
  )
}
export default FileName;