import {FormInput} from "../controller.js";

/**
 * 文件上传组件
 * @param {[type]} dataModel [description]
 */
export default class FileUpload extends FormInput {

  constructor(__tfp, dataModel, parent, inputType) {
    if(inputType) {
      super(__tfp, inputType, dataModel, parent);
    } else {
      super(__tfp, "FileUpload", dataModel, parent);
    }
  }

  //应用代码
  get appCode() { return this.dataModel.appCode }
  set appCode(value) {this.dataModel.appCode = value}

  //应用数据ID
  get appDataId() { return this.dataModel.appDataId }
  set appDataId(value) {this.dataModel.appDataId = value}

  //文件类型
  get fileType() { return this.dataModel.fileType }
  set fileType(value) {this.dataModel.fileType = value}

  //文件总数
  get size() { return this.dataModel.size }
  set size(value) {this.dataModel.size = value}

  //允许上传
  get allowUpload() { return this.dataModel.allowUpload }
  set allowUpload(value) {this.dataModel.allowUpload = value}

  //允许删除
  get allowDelete() { return this.dataModel.allowDelete }
  set allowDelete(value) {this.dataModel.allowDelete = value}

  get value() { 
    let val = [];
    for(var i=0;i<this.files.length;i++) {
      let f = this.files[i];
      val.push({
        name: f.name,
        code: f.code,
        size: f.size
      });
    }
    this.dataModel.value = val;
    return val; 
  }
  set value(value) {
    if(!value || !Array.isArray(value)) return;
    this.files = value;
    this.dataModel.value = value;
    if(this._jqObj) {
      this.exeEventHandler("onChange");
    }
  }

  selectFile() {
    if(!this.dataModel.size) this.dataModel.size = 10;
    if(this.files && this.files.length>=this.dataModel.size) {
      this._tfp.showMsg("最多只能上传"+this.dataModel.size+"个文件！");
      return;
    }
    this._jqObj.append("<div class=\"tfp-fileupload-row\" style=\"display:none\">"
      +"<input type=\"file\" style=\"display:none\" /><p class=\"tfp-fileupload-fileinfo\">"
      +"<img src=\"/images/icon/16/attach.png\" align=\"absmiddle\" /></p>"
      +"<p><progress value=\"0\" max=\"100\"></progress>&nbsp;"
      +"<span class=\"uploaderPercent\">0%</span></p></div>");
    let uploadIpt = this._jqObj.find(".tfp-fileupload-row").last().find("input");
    let that = this;
    uploadIpt.change(function() {
      that.uploadFile(this);
    });
    uploadIpt.click();
  }

  uploadFile(ipt) {
    var iptFile = $(ipt);
    var filePath = iptFile.val();
    if(this.files) {
      for(var i=0;i<this.files.length;i++) {
        let f = this.files[i];
        if(f.path==filePath) {
          this._tfp.showMsg("该文件已添加！");
          iptFile.parent().remove();
          return;
        }
      }
    }
    var fileName = filePath.substr(filePath.lastIndexOf("\\")+1);
    if(this.type=="PhotoUpload" && !this.dataModel.fileType) 
      this.dataModel.fileType = ".jpg,.jpeg,.gif,.png,.bmp";
    if(this.dataModel.fileType) {
      var isValidType = true;
      var end = fileName.lastIndexOf(".");
      if(end>=0) {
        var filetype = fileName.substr(end);
        if(!this.dataModel.fileType.toLowerCase().split(",").contains(filetype.toLowerCase())) 
          isValidType = false;
      } else {
        isValidType = false;
      }
      if(!isValidType) {
        this._tfp.showMsg("文件格式必须为："+this.dataModel.fileType+"。");
        iptFile.parent().remove();
        return;
      }
    }

    var fileObj = ipt.files[0];
    if(this.type=="PhotoUpload") { 
      var reader = new FileReader();  
      reader.onload = function(e){ 
        iptFile.parent().find("img").attr("src", e.target.result);
      } 
      reader.readAsDataURL(fileObj);
    } else {
      iptFile.parent().find(".tfp-fileupload-fileinfo").append("&nbsp;&nbsp;"+fileName);
    }
    iptFile.parent().show();
    var uploaderUrl = "/Upload";
    if(this.dataModel.appCode) {
      uploaderUrl += "?appCode="+this.dataModel.appCode;
      if(this.dataModel.appDataId) uploaderUrl += "&appDataId="+this.dataModel.appDataId;
      if(this.dataModel.onlyOne) uploaderUrl += "&onlyOne=true";
    }
    uploaderUrl = this._tfp.setUrlAuthData(uploaderUrl);
    let that = this;
    var form = new FormData();  
    //console.log(fileObj);
    form.append("file", fileObj); 
    var xhr = new XMLHttpRequest();
    xhr.open("post", uploaderUrl, true);
    xhr.onload = function() {
      var response = null;
      try {
        response = JSON.parse(xhr.responseText);
      } catch(e) {
        this._tfp.showMsg("文件["+fileName+"]上传失败，错误描述："+e.message);
        iptFile.parent().hide();
        iptFile.parent().remove();
        return;
      }
      if(response.code!=0) {
        this._tfp.showMsg("文件["+fileName+"]上传失败，错误描述："+response.message);
        iptFile.parent().hide();
        iptFile.parent().remove();
        return;
      }
      if(that.dataModel.allowDelete) {
        if(that.type=="PhotoUpload") {
          iptFile.parent().append("<p align=\"center\"><a href=\"javascript:void(0)\">删除</a></p>");
        } else {
          iptFile.parent().find(".tfp-fileupload-fileinfo").append(
            "&nbsp;&nbsp;<a href=\"javascript:void(0)\">删除</a>");
        }

        iptFile.parent().find("a").click(function() {
          that.deleteFile(this, response.path);
        });
      }
      
      var file = {};
      file.name = fileName;
      if(response.fileId) file.id = response.fileId;
      if(response.fileCode) {
        file.code = response.fileCode;
      } else {
        file.code = response.path;
      }
      if(response.fileSize) {
        file.size = response.fileSize;
      } else {
        file.size = response.size;
      }
      file.path = filePath;
      if(!that.files) that.files = [];
      that.files.push(file);
      iptFile.parent().find("progress").parent().remove();
      /*if(that.type=="PhotoUpload") {
        iptFile.parent().css("height", "100px");
      } else {
        iptFile.parent().css("height", "24px");
      }*/
      iptFile.remove();
      if(that.onChange) eval(that.onChange);
    };
    xhr.upload.fileInput = iptFile;
    xhr.upload.addEventListener("progress", this.onUploaderProgressChange, false);
    xhr.send(form);
  }

  deleteFile(ipt, fileCode) {
    if(this.files) {
      var fileIndex = -1;
      for(var i=0;i<this.files.length;i++) {
        if(this.files[i].code==fileCode) {
          fileIndex = i;
          break;
        }
      }
      if(fileIndex>=0) this.files.splice(fileIndex, 1);
    }
    $(ipt).parent().parent().remove();
  }

  onUploaderProgressChange(evt) {
    var ipt = evt.srcElement.fileInput;
    var uploadProgress = ipt.parent().find("progress").get(0);
    var uploadPercent = ipt.parent().find(".uploaderPercent").get(0);
    if (evt.lengthComputable) {
      uploadProgress.max = evt.total;
      uploadProgress.value = evt.loaded;
      uploadPercent.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
    }
  }

  initRuntime() {
    let that = this;
    this._jqObj.find(".tfp-fileupload-row").eq(0).find("input").click(function() {
      that.selectFile();
    });
  }
}