"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));

require("core-js/modules/es6.regexp.to-string");

require("regenerator-runtime/runtime");

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));

var _getIterator2 = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/get-iterator"));

var _isArray2 = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/array/is-array"));

require("core-js/modules/web.dom.iterable");

require("core-js/modules/es6.regexp.replace");

require("core-js/modules/es6.regexp.split");

require("core-js/modules/es6.regexp.constructor");

require("./index.css");

var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));

var _gdFile = _interopRequireDefault(require("./gd-file"));

var _Icon = _interopRequireDefault(require("../Icon"));

var _component = require("../_utils/component");

var _oss = _interopRequireDefault(require("../oss"));

var _vueNormalizeComponent = _interopRequireDefault(require("../_utils/vue-normalize-component.js"));

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var TYPE2CN = {
  image: '图片',
  text: '文本',
  audio: '音频',
  video: '视频',
  application: '二进制'
};
var __vue_script__ = {
  name: (0, _component.createComponentName)('upload'),
  components: {
    Icon: _Icon.default
  },
  mixins: [_component.componentMixin],
  // TODO: fileList 支持 v-model
  // model: {
  //     prop: 'fileList',
  //     event: 'update',
  // },
  props: {
    // 接受上传的文件类型
    accept: {
      type: String,
      default: 'image/jpeg, image/png, image/gif'
    },

    /**
    * 上传前处理钩子
    * @args { GdFile }
    * @return { Promise | boolean | File | Blob | GdFile } 如果返回 false 将会终止上传并删除文件
    */
    beforeUpload: {
      // `(gdFile): Promise | boolean | File | Blob | GdFile`
      type: Function
    },
    action: {
      type: Function
    },
    // 上传文件夹, IE 不支持
    directory: {
      type: Boolean,
      default: false
    },
    // 是否支持多选文件
    multiple: {
      type: Boolean,
      default: false
    },
    // 选择文件立即上传
    autoUpload: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 最大上传数目
    limit: {
      type: Number,
      // 0 表示 不限制
      default: 0
    },
    concurrent: {
      type: Number,
      default: 1
    },
    type: {
      // `card` `normal`
      type: String,
      default: 'normal'
    }
  },

  data() {
    return {
      fileList: []
    };
  },

  created() {
    this.willUploadFileds = [];
  },

  methods: {
    onClick() {
      if (!this.disabled && this.$refs.input) this.$refs.input.click();
    },

    verifyAccept(type) {
      if (this.accept && this.accept !== '*') {
        var reg = new RegExp(this.accept.split(',').map(function (type) {
          return type.trim();
        }).join('|').toLowerCase());
        return reg.test(type.toLowerCase());
      }

      return true;
    },

    accepterrorText() {
      if (this.accept) {
        var types = this.accept.replace(/\s+/g, '').split(',').map(function (MIME) {
          var _MIME$toLowerCase$spl = MIME.toLowerCase().split('/'),
              type = _MIME$toLowerCase$spl[0],
              subtype = _MIME$toLowerCase$spl[1];

          if (subtype === '*') {
            return TYPE2CN[type] || type;
          }

          return subtype.toUpperCase();
        }).join('/');
        return `仅支持${types}文件`;
      }

      return '无效的文件格式';
    },

    onError(error, gdFile) {
      this.removeFile(gdFile);

      if (error.message === 'stop') {
        gdFile.status = 'cancel';
        return;
      }

      gdFile.error = error;
      gdFile.status = 'error';
      this.$emit('error', error, gdFile);
    },

    onChange(e) {
      var _this = this;

      var files = []; // 如果使用 [...e.target.files] 编译到 lib 会转成 e.target.files.concat() 导致报错

      for (var _iterator = e.target.files, _isArray = (0, _isArray2.default)(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator2.default)(_iterator);;) {
        var _ref;

        if (_isArray) {
          if (_i >= _iterator.length) break;
          _ref = _iterator[_i++];
        } else {
          _i = _iterator.next();
          if (_i.done) break;
          _ref = _i.value;
        }

        var file = _ref;
        files.push(file);
      }

      if (this.limit && files.length + this.fileList.length > this.limit) {
        // 超出限上线触发
        this.$emit('exceed', files, this.fileList);
        return;
      }

      var gdFiles = files.map(function (file) {
        var gdFile = new _gdFile.default(file);

        if (!_this.verifyAccept(gdFile.type)) {
          var error = new Error(_this.accepterrorText());

          _this.onError(error, gdFile);

          return false;
        }

        return gdFile;
      }).filter(function (f) {
        return f;
      });
      this.$refs.input.value = null;
      this.$emit('change', gdFiles);
      gdFiles.forEach(function (gdFile) {
        _this.fileList.push(gdFile);

        if (_this.autoUpload) {
          _this.uplaodFile(gdFile);
        }

        if (_this.type === 'card') {
          gdFile.src = gdFile.toURL();
        }
      });
    },

    uplaodFile(gdFile) {
      var _this2 = this;

      return (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee() {
        var res, _res, type, key, num, files;

        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (/image\//.test(gdFile.type)) {
                  _context.next = 2;
                  break;
                }

                return _context.abrupt("return", _this2.onError(new Error('目前只支持上传图片文件'), gdFile));

              case 2:
                if (!_this2.beforeUpload) {
                  _context.next = 16;
                  break;
                }

                _context.prev = 3;
                _context.next = 6;
                return _this2.beforeUpload(gdFile);

              case 6:
                _res = _context.sent;

                if (_res) {
                  _context.next = 9;
                  break;
                }

                return _context.abrupt("return", _this2.removeFile(gdFile));

              case 9:
                _context.next = 14;
                break;

              case 11:
                _context.prev = 11;
                _context.t0 = _context["catch"](3);
                return _context.abrupt("return", _this2.removeFile(gdFile));

              case 14:
                type = Object.prototype.toString.call(res);

                if (type === '[object Blob]') {
                  gdFile = new File([res], gdFile.name, {
                    type: gdFile.type
                  });
                  gdFile.originFile = gdFile;
                } else if (type === '[object File]') {
                  for (key in res) {
                    if (res.hasOwnProperty(key)) {
                      gdFile[key] = res[key];
                      gdFile.originFile = gdFile;
                    }
                  }
                }

              case 16:
                if (!(_this2.concurrent && _this2.fileList.filter(function (f) {
                  return f.status === 'uploading';
                }).length >= _this2.concurrent)) {
                  _context.next = 18;
                  break;
                }

                return _context.abrupt("return", _this2.willUploadFileds.push(gdFile));

              case 18:
                _context.next = 20;
                return _this2.post(gdFile);

              case 20:
                num = _this2.concurrent - _this2.fileList.filter(function (f) {
                  return f.status === 'uploading';
                }).length;

                if (_this2.concurrent && num) {
                  files = _this2.willUploadFileds.splice(0, num);
                  files.forEach(function (file) {
                    return _this2.uplaodFile(file);
                  });
                }

              case 22:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[3, 11]]);
      }))();
    },

    removeFile(gdFile) {
      gdFile.status = 'error';
      var index = this.fileList.indexOf(gdFile);

      if (index > -1) {
        this.$emit('remove', gdFile, this.fileList);
        this.fileList.splice(index, 1);
      }
    },

    post(gdFile) {
      var _this3 = this;

      gdFile.status = 'uploading';
      var oss = new _oss.default();

      gdFile.cancel = function () {
        return oss.cancel('stop');
      };

      return oss.uploadFile(gdFile.originFile, {
        onProgress: function onProgress(e) {
          gdFile.percent = e.percent;

          _this3.$emit('progress', e, gdFile, _this3.fileList);
        }
      }).then(function (src) {
        gdFile.src = src;
        gdFile.status = 'done';
        gdFile.cancel = null;

        _this3.$emit('success', gdFile, _this3.fileList);
      }).catch(function (error) {
        _this3.onError(error, gdFile);
      });
    },

    /**
    * @vuese
    * 上传所有 status: 'ready' 的文件列表
    */
    uploadFiles() {
      var _this4 = this;

      return (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee2() {
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return _promise.default.all(_this4.fileList.filter(function (f) {
                  return f.status === 'ready';
                }).map(function (f) {
                  return _this4.uplaodFile(f);
                }));

              case 2:
                return _context2.abrupt("return", _this4.fileList);

              case 3:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }))();
    },

    cancel(gdFile) {
      var index = this.willUploadFileds.indexOf(gdFile);

      if (index > -1) {
        this.willUploadFileds.splice(index, 1);
      }

      if (gdFile.cancel) {
        gdFile.cancel();
        gdFile.cancel = null;
        gdFile.status = 'ready';
      }
    },

    cancelAll() {
      var _this5 = this;

      this.fileList.forEach(function (f) {
        return _this5.cancel(f);
      });
    },

    /**
    * @vuese
    * 清空文件列表
    */
    clearFiles() {
      this.fileList = [];
    }

  }
};
/* template */

var __vue_render__ = function __vue_render__() {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("div", {
    class: _vm.bem(),
    attrs: {
      disabled: _vm.disabled
    }
  }, [_vm.type === "card" ? _c("div", {
    class: _vm.bem("card-list")
  }, [_vm._l(_vm.fileList, function (file) {
    return _c("div", {
      key: file.id,
      class: _vm.bem("card")
    }, [_c("i", {
      class: _vm.bem("remove-btn"),
      on: {
        click: function click($event) {
          _vm.removeFile(file);
        }
      }
    }, [_c("icon", {
      attrs: {
        name: "close",
        color: "#fff",
        size: "small"
      }
    })], 1), _vm._v(" "), _c("img", {
      class: _vm.bem("thumbnail"),
      attrs: {
        src: file.src
      }
    })]);
  }), _vm._v(" "), !_vm.limit || _vm.limit !== _vm.fileList.length ? _c("div", {
    class: _vm.bem("card", ["input"]),
    on: {
      click: _vm.onClick
    }
  }, [_vm._t("default", [_c("div", [_c("Icon", {
    attrs: {
      name: "upload",
      size: "big"
    }
  }), _vm._v(" "), _c("div", [_vm._v("上传")])], 1)])], 2) : _vm._e()], 2) : _c("div", {
    on: {
      click: _vm.onClick
    }
  }, [_vm._t("default")], 2), _vm._v(" "), _c("input", {
    ref: "input",
    staticStyle: {
      display: "none"
    },
    attrs: {
      type: "file",
      webkitdirectory: _vm.directory,
      multiple: _vm.multiple,
      disabled: _vm.disabled,
      accept: _vm.accept
    },
    on: {
      change: _vm.onChange
    }
  })]);
};

var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;
/* style */

var __vue_inject_styles__ = undefined;
/* scoped */

var __vue_scope_id__ = undefined;
/* module identifier */

var __vue_module_identifier__ = undefined;
/* functional template */

var __vue_is_functional_template__ = false;
/* component normalizer */

/* style inject */

/* style inject SSR */
var _default = (0, _vueNormalizeComponent.default)({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);

exports.default = _default;