import ArrayUtil from '../array.mjs';

"use strict";
class FileUploadRuleVo {
  /**
   * 扩展名
   */
  extraName = "";
  /**
   * 文件最大大小
   */
  maxSize = 0;
  constructor(extraName, maxSize) {
    this.extraName = extraName;
    this.maxSize = maxSize;
  }
}
class FileUploadRule {
  rules = [];
  changeHandler = null;
  errorMessage = "";
  constructor() {
  }
  /**
   * 新增上传规则
   * @param extraName
   * @param maxSize
   */
  add = (extraName, maxSize) => {
    const rule = new FileUploadRuleVo(extraName, maxSize);
    this.rules.push(rule);
    this.changeHandler && this.changeHandler();
  };
  /**
   * 清空规则
   */
  clear = () => {
    this.rules.length = 0;
    this.changeHandler && this.changeHandler();
  };
  /**
   * 规则发生变化事件
   * @param handler
   */
  setChangeHandler = (handler) => {
    this.changeHandler = handler;
  };
  /**
   * 获得所有规则
   * @returns
   */
  getRules = () => {
    return this.rules;
  };
  /**
   * 获得提示信息
   */
  getErrorMessage = () => {
    return this.errorMessage;
  };
  /**
   * 获得上传提示,根据收集的规则来生成提示信息
   */
  getUploadTips = () => {
    const data = ArrayUtil.findSame(this.rules, "maxSize");
    let tip = [];
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      let extraNames = [];
      let maxSize = item[0].maxSize;
      for (let j = 0; j < item.length; j++) {
        extraNames.push(item[j].extraName);
      }
      tip.push({ name: extraNames.join(","), size: this.bytesToSize(maxSize) });
    }
    return tip;
  };
  /**
   * 获得接受的文件类型
   */
  getAccept = () => {
    let accept = [];
    for (let i = 0; i < this.rules.length; i++) {
      accept.push("." + this.rules[i].extraName);
    }
    return accept.join(",");
  };
  // 字节转换
  bytesToSize(bytes) {
    const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    if (bytes === 0) return "0 Bytes";
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, i)).toFixed(2) + " " + sizes[i];
  }
  /**
   * 检查文件是否合法
   * @param file
   * @returns
   */
  check = (file) => {
    this.errorMessage = "";
    const fileName = file.name;
    var suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
    for (let i = 0; i < this.rules.length; i++) {
      if (this.rules[i].extraName.toLocaleLowerCase() == suffixName.toLocaleLowerCase()) {
        if (file.size <= this.rules[i].maxSize) {
          return true;
        } else {
          this.errorMessage = "\u4E0A\u4F20\u6587\u4EF6\u5C3A\u5BF8\u8FC7\u5927";
          return false;
        }
      }
    }
    this.errorMessage = "\u4E0D\u652F\u6301\u8BE5\u6587\u4EF6\u683C\u5F0F";
    return false;
  };
}

export { FileUploadRule as default };
//# sourceMappingURL=FileUploadRule.mjs.map
