import { Component, render, createElement } from 'rax';
import "./index.less";
import FileListItem from "../FileListItem";
import Drag from "../Drag";
import { reqGet, reqPost, reqGetDownload } from "../Util/request";
import { updateStrJoin } from '../Util/utils';
import Texp from '../Texp';
import config from '../../../config';
import TexpkCfgItem from '../TexpkCfgItem';
import AddCfgDialog from '../AddCfgDialog';
import UpLoading from '../UpLoading';

export default class App extends Component {
  inst;
  _uploadingCom;
  constructor(props) {
    super(props);
    App.inst = this;
    
    this.checked = null;
    this.itemComs = [];
    this.ranFolder = "",
      this.state = {
        folderList: [],
        fileList: [],
        directory: "",

        configList: [],
        showdialog: false,
        showTexp: false,
        showImg: false,
        curConfig: null,
        image: null,
        plist: null
      }
  }

  search = () => {
    let value = this.input.value;
    let newlist = [];
    let arr = this.allFolders;
    if (value === "") {
      newlist = this.allFolders.slice();
    } else {
      for (let i = 0; i < arr.length; ++i) {
        if (arr[i].folderName.indexOf(value) != -1) {
          newlist.push(arr[i]);
        }
      }
    }

    this.setState({
      folderList: newlist
    })
  }

  onEnterFile = (folderName) => {
    this.reqFileList(folderName, (data) => {
      this.updateFileList(data)
    })

    reqGet("./readFileList/?path=" + folderName + "/.tp", (data) => {
      this.setState({
        configList: data.data
      })
    })
  }

  updateFileList = (data) => {
    let alllists = data.data.fileList.slice();
    Drag.inst.updateFileList(alllists);
  }


  reqFolderList = (cb) => {
    reqGet("./folderList", (data) => {
      if (data.err) {
        return;
      }
      this.allFolders = data.data.folderList.slice();
      cb(data);

    });

  }

  reqFileList = (folderName, cb) => {
    let str = "/?folderName=" + folderName;

    reqGet("./fileList" + str, (data) => {
      if (data.err) {
        return;
      }
      cb(data);

    });

  }

  createFolder = () => {
    let folderName = this.newFolderName.value;
    reqGet("./create/?folderName=" + folderName, (data) => {
      if (data) {
        this.reqFolderList((result) => {
          this.setState({
            directory: result.data.directory,
            folderList: result.data.folderList
          })
        })
      }

    });
  }

  getCurFolderName = () => {
    let folderName = this.checked && this.checked.getFolderName();
    if (!folderName) {
      folderName = "";
    }
    return folderName;
  }

  download(filename) {
    let folderName = this.getCurFolderName();
    reqGetDownload("./download/?fileName=" + filename + "&folderName=" + folderName, (data) => {
      if (data.err) {
        return;
      }

    });
  }

  deleteFolder(folderName, cb) {
    reqGet("./deleteFolder/?folderName=" + folderName, (data) => {
      if (data) {
        cb();
        this.reqFolderList((result) => {
          // let folderName = this.getCurFolderName();
          // this.reqFileList(folderName,(data)=>{
          //   this.updateFileList(data)
          // })
          this.setState({
            directory: result.data.directory,
            folderList: result.data.folderList
          })
        })
      }
    });
  }

  deleteFiles(reqData) {
    reqPost("./deleteFiles", reqData, (resData) => {
      alert(resData)
      this.reqFileList(reqData.folderName, (data) => {
        this.updateFileList(data)
      })
    })
  }

  addConfigure() {
    this.setState({
      showdialog: !this.state.showdialog
    })
  }

  showConfigure(dir, config) {
    this.setState({
      showTexp: true,
    })
    let folderName = this.getCurFolderName() + "/.tp";
    reqGet("./configure/?fileName=" + dir + "&folderName=" + folderName, (data) => {
      Texp.inst.updateCfgData(data.data, dir, config);
      this.createTexpk(data.data, false);
    })
  }
  createCfgFile(dir, texpkData) {
    let folderName = this.getCurFolderName() + "/.tp";
    reqPost("./createConfigFile/?fileName=" + dir + "&folderName=" + folderName, texpkData, () => {
      reqGet("./readFileList/?path=" + folderName, (data) => {
        this.setState({
          configList: data.data
        })
      })
    })
  }
  createTexpk(reqdata, texpk) {
    
    if (texpk) {
      this.showUpLoadUI();
      reqPost("./texturePacker", reqdata, (data) => {
        let err = data.data.result;
        this.hideUpLoadUI();
        if (err && err.indexOf("error") !== -1) {
          this.setState({
            showImg: false
          })
          alert(data.data.result);
          Texp.inst.setTexpkResult(false); 
        }
        this.setState({
          showImg: true,
          image: "./temp/" + reqdata.texture.sheet,
          plist: "./temp/" + reqdata.data.dataFile
        })
        Texp.inst.setTexpkResult(true); 
      })
    } else {
      if (reqdata.texture.sheet !== "" && reqdata.data.dataFile !== "") {

        this.setState({
          showImg: true,
          image: "./temp/" + reqdata.texture.sheet,
          plist: "./temp/" + reqdata.data.dataFile
        })
      } else {
        this.setState({
          showImg: false
        })
      }
    }
  }

  deleteConfig(reqData) {
    let folderName = this.getCurFolderName() + "/.tp";
    reqPost("./deleteFiles", reqData, (resData) => {
      reqGet("./readFileList/?path=" + folderName, (data) => {
        this.setState({
          configList: data.data
        })
      })
    })
    this.setState({
      showTexp: false,
      showImg: false
    })
  }
  downloadSheet = () => {
    let sheet = this.state.image.slice(this.state.image.lastIndexOf("/") + 1, this.state.image.length);
    let folder = "./temp/" + this.state.image.slice(0, this.state.image.lastIndexOf("/")).replace("./temp/", "");
    reqGetDownload("./downloadConfig/?fileName=" + sheet + "&folderName=" + folder, (data) => {
      if (data.err) {
        return;
      }
    });

  }
  downloadPlist = () => {
    let plist = this.state.plist.slice(this.state.plist.lastIndexOf("/") + 1, this.state.plist.length);
    let folder = "./temp/" + this.state.plist.slice(0, this.state.plist.lastIndexOf("/")).replace("./temp/", "");
    reqGetDownload("./downloadConfig/?fileName=" + plist + "&folderName=" + folder, (data) => {
      if (data.err) {
        return;
      }
    });
  }

  showUpLoadUI=()=>{
    this._uploadingCom && this._uploadingCom.show();
  }

  hideUpLoadUI=()=>{
    this._uploadingCom && this._uploadingCom.hide();
  }


  componentWillUnmount() {

  }
  componentWillMount() {
    this.setState({
      configData: config.texpkDefault
    })

  }
  componentDidMount() {
    this.reqFolderList((data) => {
      //  this.onEnterFile("");
      // this.allFolders = data.data.folderList.slice();
      this.setState({
        directory: data.data.directory,
        folderList: data.data.folderList,
      })
    })
  }


  render() {
    let listItemBgColor = ["#aaaabb", "#aaccaa"];
    return (
      <div className={"app_box"}>
        <div className={"app_left"}>
          <div className={"app_search"}>
            <input ref={ref => this.input = ref} className={"app_input"} onInput={this.search} onpropertychange={this.search} type="text" placeholder={"输入文件名查找"} />
            <input className={"app_searchBtn"} type="button" value={"查找"} />
          </div>
          <div className={"app_lfbox"}>
            <div className={"app_lfRootfile"}>{this.state.directory}</div>
            <div className={"app_lffile"}>
              {
                this.state.folderList.map((msg, index) => {
                  return <FileListItem key={index} data={{ msg: msg, bgColor: listItemBgColor[index % 2] }} />
                })
              }
            </div>
            <div className={"app_addfilebox"}>
              <input ref={ref => this.newFolderName = ref} className={"app_addfileInput"} type="text" placeholder={"输入文件名"} />
              <input className={"app_addfileBtn"} type="button" value={"添加"} onClick={this.createFolder} />
            </div>
          </div>
        </div>
        <div className={"app_right"}>
          <Drag fileList={this.state.fileList} />
          <div className={"config_box"}>
            {
              this.state.configList.map((v, index) => {
                return <TexpkCfgItem key={index} fileName={v.name} bgColor={v.name === this.state.curConfig ? "#C9A788" : "#EEDACA"} />
              })
            }
          </div>
        </div>
        <div ref={ref => this.app_texp = ref} className={"app_texp"}>
          {
            this.state.showTexp ? <Texp /> : <div></div>
          }
        </div>
        {
          this.state.showdialog ? <AddCfgDialog /> : <div></div>
        }
        <div style={{ 'margin-top': '600px', 'width': ' 1000px', 'height': '800px', 'overflow': 'scroll' }}>
          {
            this.state.showImg ? <div>
              <img src={this.state.image} style={{ 'float': 'left' }} />
              <div style={{ 'position': 'absolute', 'width': '100px', 'left': ' 1300px' }}>
                <input type="button" value="下载图片文件" onClick={this.downloadSheet} style={{ 'font-size': '20px', 'width': '100px', 'height': '50px' }}></input>
                <input type="button" value="下载数据文件" onClick={this.downloadPlist} style={{ 'font-size': '20px', 'width': '100px', 'height': '50px', 'margin-top': '10px' }}></input>
              </div>
            </div> : <div></div>
          }
        </div>
        <UpLoading app={this}/>
        {/* {
          <div style={{display:this.state.showUpLoading?'block':'none'}}>
          
          </div>
        } */}
      </div>
    )
  }
}
