"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _controller = require("../controller.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * 文件上传组件
 * @param {[type]} dataModel [description]
 */
var FileUpload = /*#__PURE__*/function (_FormInput) {
  _inherits(FileUpload, _FormInput);

  var _super = _createSuper(FileUpload);

  function FileUpload(__tfp, dataModel, parent, inputType) {
    var _this;

    _classCallCheck(this, FileUpload);

    if (inputType) {
      _this = _super.call(this, __tfp, inputType, dataModel, parent);
    } else {
      _this = _super.call(this, __tfp, "FileUpload", dataModel, parent);
    }

    return _possibleConstructorReturn(_this);
  } //应用代码


  _createClass(FileUpload, [{
    key: "appCode",
    get: function get() {
      return this.dataModel.appCode;
    },
    set: function set(value) {
      this.dataModel.appCode = value;
    } //应用数据ID

  }, {
    key: "appDataId",
    get: function get() {
      return this.dataModel.appDataId;
    },
    set: function set(value) {
      this.dataModel.appDataId = value;
    } //文件类型

  }, {
    key: "fileType",
    get: function get() {
      return this.dataModel.fileType;
    },
    set: function set(value) {
      this.dataModel.fileType = value;
    } //文件总数

  }, {
    key: "size",
    get: function get() {
      return this.dataModel.size;
    },
    set: function set(value) {
      this.dataModel.size = value;
    } //允许上传

  }, {
    key: "allowUpload",
    get: function get() {
      return this.dataModel.allowUpload;
    },
    set: function set(value) {
      this.dataModel.allowUpload = value;
    } //允许删除

  }, {
    key: "allowDelete",
    get: function get() {
      return this.dataModel.allowDelete;
    },
    set: function set(value) {
      this.dataModel.allowDelete = value;
    }
  }, {
    key: "value",
    get: function get() {
      var val = [];

      for (var i = 0; i < this.files.length; i++) {
        var f = this.files[i];
        val.push({
          name: f.name,
          code: f.code,
          size: f.size
        });
      }

      this.dataModel.value = val;
      return val;
    },
    set: function set(value) {
      if (!value || !Array.isArray(value)) return;
      this.files = value;
      this.dataModel.value = value;

      if (this._jqObj) {
        this.exeEventHandler("onChange");
      }
    }
  }, {
    key: "selectFile",
    value: function 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>");

      var uploadIpt = this._jqObj.find(".tfp-fileupload-row").last().find("input");

      var that = this;
      uploadIpt.change(function () {
        that.uploadFile(this);
      });
      uploadIpt.click();
    }
  }, {
    key: "uploadFile",
    value: function uploadFile(ipt) {
      var iptFile = $(ipt);
      var filePath = iptFile.val();

      if (this.files) {
        for (var i = 0; i < this.files.length; i++) {
          var 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);
      var 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);
    }
  }, {
    key: "deleteFile",
    value: function 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();
    }
  }, {
    key: "onUploaderProgressChange",
    value: function 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) + "%";
      }
    }
  }, {
    key: "initRuntime",
    value: function initRuntime() {
      var that = this;

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

  return FileUpload;
}(_controller.FormInput);

exports["default"] = FileUpload;