/**
 * 文件验证
 */
class FileVerification {
  file = null;
  constructor(file) {
    this.file = file;
  }
  /**
   * 验证文件大小
   * 参数:   number （单位：KB）
   * 返回值: boolean
   */
  vSize(size) {
    return this.file.size / 1024 < size;
  }
  /**
   * 验证图片的宽高比大小
   * 参数:  w:宽  (number)
   *        h:高  (number)
   *        tolerant: 容错 （默认0.1，可不传）(number)
   * 返回值: Promise
   */
  vImgPercentage(w, h, tolerant = 0.1) {
    var self = this;
    return new Promise((resolve, reject) => {
      if (!this.vIsImage) {
        resolve(this._returnErr())
      } else {
        self.vOnload().then((img) => {
          var percentage = (img.width / img.height);
          var width = img.width;
          var height = img.height;
          var result = Math.abs((w / h) - (width / height)) < tolerant;
          resolve({
            result,
            w,
            h,
            imgW: width,
            imgH: height,
            tolerant,
            percentage,
            code: 1
          })
        })
      }

    })
  }
  /**
   * 验证图片宽度
   * 参数:   w (number)
   * 返回值: Promise
   */
  vImgW(w) {
    return this.vImgWH(w);
  }
  /**
  * 验证图片宽度
  * 参数:   w (number)
  * 返回值: Promise
  */
  vImgH(h) {
    return this.vImgWH(null, h);
  }
  /**
   * 验证图片宽高
   * 参数: w (number)
   *        h (number)
   * 返回值：Promise
   */
  vImgWH(w, h) {
    var self = this;
    return new Promise((resolve, reject) => {
      if (!this.vIsImage) {
        resolve(this._returnErr())
      } else {
        self.vOnload().then((img) => {
          var result;
          var width = img.width;
          var height = img.height;
          if (w && h) {
            result = (w == width && h == height);
          } else if (w) {
            result = (w == img.width);
          } else {
            result = (h == img.height)
          }
          resolve({
            result: result,
            w,
            h,
            imgW: width,
            imgH: height,
            code: 1
          })
        })
      }
    })
  }
  /**
   * 验证是否为图片文件
   * 返回值: boolean
   */
  vIsImage() {
    return this.file.type.indexOf("image/") != -1;
  }
  /**
   * 验证是否为视频文件
   * 返回值: boolean
   */
  vIsVideo() { return this.file.type.indexOf("video/") != -1; }

  /**
   * 验证文件扩展名
   * 参数: ext (array<string> || string)
   * 返回值: number (-1不存在，反之存在)
   */
  vExt(ext) {
    var arrExt = Object.prototype.toString.call(ext) === "[object Array]" ? ext : [ext];
    var fileExt = /\.[^\.]+$/.exec(this.file.name)[0].replace(".", "");
    return arrExt.indexOf(fileExt) > -1;
  }
  vOnload() {
    var _URL = window.URL || window.webkitURL;
    var img;
    img = new Image();
    img.src = _URL.createObjectURL(this.file);
    return new Promise((resolve, reject) => {
      img.onload = () => {
        resolve(img)
      }
    })
  }
  _returnErr(msg) {
    return {
      result: false,
      msg: msg || "请传入图片格式文件",
      code: 0
    }
  }
}

export default FileVerification;
