import _extends from "@babel/runtime/helpers/esm/extends";
import create from "../utils/create"; // Utils

import { addUnit } from "../utils/format/unit";
import { noop, isPromise, isDef } from "../utils";
import { toArray, readFile as _readFile, isOversize, isImageFile } from "./utils"; // Mixins

import { FieldMixin } from "../mixins/field"; // Components

import Icon from "../icon";
import Image from "../image";
import Loading from "../loading";
import ImagePreview from "../image-preview";
export default create({
  render: function render() {
    var _vm = this;

    var _h = _vm.$createElement;

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

    return _c('div', {
      class: _vm.b()
    }, [_c('div', {
      class: _vm.b('wrapper', {
        disabled: _vm.disabled
      })
    }, [_vm.previewImage ? _vm._l(_vm.fileList, function (item, index) {
      return _c('div', {
        key: index,
        class: _vm.b('preview'),
        on: {
          "click": function click($event) {
            return _vm.onClick(item, index);
          }
        }
      }, [_vm.isImageFile(item) ? _c('vm-image', {
        class: _vm.b('preview-image'),
        attrs: {
          "fit": _vm.imageFit,
          "src": item.content || item.url,
          "width": _vm.previewSize,
          "height": _vm.previewSize,
          "lazyLoad": _vm.lazyLoad
        },
        on: {
          "click": function click($event) {
            return _vm.onPreviewImage(item);
          }
        }
      }, [_vm.$slots['preview-cover'] ? _c('div', {
        class: _vm.b('preview-cover')
      }, [_vm._t("preview-cover")], 2) : _vm._e()]) : _c('div', {
        class: _vm.b('file'),
        style: {
          width: _vm.previewSizeWithUnit,
          height: _vm.previewSizeWithUnit
        }
      }, [_c('Icon', {
        class: _vm.b('file-icon'),
        attrs: {
          "name": "description"
        }
      }), _c('div', {
        class: [_vm.b('file-name'), 'vm-ellipsis']
      }, [_vm._v("\n            " + _vm._s(item.file ? item.file.name : item.url) + "\n          ")]), _vm.$slots['preview-cover'] ? _c('div', {
        class: _vm.b('preview-cover')
      }, [_vm._t("preview-cover")], 2) : _vm._e()], 1), item.status === 'uploading' || item.status === 'failed' ? _c('div', {
        class: _vm.b('mask')
      }, [item.status === 'failed' ? _c('Icon', {
        class: _vm.b('mask-icon'),
        attrs: {
          "name": "close"
        }
      }) : _c('Loading', {
        staticClass: "b('loading')"
      }), _vm.isDef(item.message) && item.message !== '' ? _c('div', {
        class: _vm.b('mask-message')
      }, [_vm._v("\n            " + _vm._s(item.message) + "\n          ")]) : _vm._e()], 1) : _vm._e(), _c('div', {
        class: _vm.b('preview-delete'),
        on: {
          "click": function click($event) {
            $event.preventDefault();
            $event.stopPropagation();
            return _vm.onDelete(item, index);
          }
        }
      }, [_c('Icon', {
        class: _vm.b('preview-delete-icon'),
        attrs: {
          "name": "close"
        }
      })], 1)], 1);
    }) : _vm._e(), _vm.$slots['default'] ? _c('div', {
      class: _vm.b('input-wrapper')
    }, [_vm._t("default"), _c('input', _vm._b({
      ref: "input",
      class: _vm.b('input'),
      attrs: {
        "type": "file",
        "accept": _vm.accept,
        "disabled": _vm.disabled
      },
      on: {
        "change": _vm.onChange
      }
    }, 'input', _vm.$attrs, false))], 2) : [_vm.showUpload && _vm.fileList.length < this.maxCount ? _c('div', {
      class: _vm.b('upload'),
      style: _vm.style
    }, [_c('Icon', {
      class: _vm.b('upload-icon'),
      attrs: {
        "name": _vm.uploadIcon
      }
    }), _vm.uploadText ? _c('span', {
      class: _vm.b('upload-text')
    }, [_vm._v("\n          " + _vm._s(_vm.uploadText) + "\n        ")]) : _vm._e(), _c('input', _vm._b({
      ref: "input",
      class: _vm.b('input'),
      attrs: {
        "type": "file",
        "accept": _vm.accept,
        "disabled": _vm.disabled
      },
      on: {
        "change": _vm.onChange
      }
    }, 'input', _vm.$attrs, false))], 1) : _vm._e()]], 2)]);
  },
  components: {
    Icon: Icon,
    "vm-image": Image,
    Loading: Loading,
    ImagePreview: ImagePreview
  },
  name: "uploader",
  inheritAttrs: false,
  mixins: [FieldMixin],
  model: {
    prop: "fileList"
  },
  props: {
    disabled: Boolean,
    lazyLoad: Boolean,
    uploadText: String,
    afterRead: Function,
    beforeRead: Function,
    beforeDelete: Function,
    previewSize: [Number, String],
    previewOptions: Object,
    name: {
      type: [Number, String],
      default: ""
    },
    accept: {
      type: String,
      default: "image/*"
    },
    fileList: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    maxSize: {
      type: [Number, String],
      default: Number.MAX_VALUE
    },
    maxCount: {
      type: [Number, String],
      default: Number.MAX_VALUE
    },
    deletable: {
      type: Boolean,
      default: true
    },
    showUpload: {
      type: Boolean,
      default: true
    },
    previewImage: {
      type: Boolean,
      default: true
    },
    previewFullImage: {
      type: Boolean,
      default: true
    },
    imageFit: {
      type: String,
      default: "cover"
    },
    resultType: {
      type: String,
      default: "dataUrl"
    },
    uploadIcon: {
      type: String,
      default: "camera"
    }
  },
  computed: {
    style: function style() {
      var style;

      if (this.previewSize) {
        var size = this.previewSizeWithUnit;
        style = {
          width: size,
          height: size
        };
      }

      return style;
    },
    previewSizeWithUnit: function previewSizeWithUnit() {
      return addUnit(this.previewSize);
    },
    // for form
    value: function value() {
      return this.fileList;
    }
  },
  methods: {
    isImageFile: isImageFile,
    isDef: isDef,
    onClick: function onClick(item, index) {
      this.$emit("click-preview", item, this.getDetail(index));
    },
    getDetail: function getDetail(index) {
      if (index === void 0) {
        index = this.fileList.length;
      }

      return {
        name: this.name,
        index: index
      };
    },
    onChange: function onChange(event) {
      var _this = this;

      var files = event.target.files;

      if (this.disabled || !files.length) {
        return;
      }

      files = files.length === 1 ? files[0] : [].slice.call(files);

      if (this.beforeRead) {
        var response = this.beforeRead(files, this.getDetail());

        if (!response) {
          this.resetInput();
          return;
        }

        if (isPromise(response)) {
          response.then(function (data) {
            if (data) {
              _this.readFile(data);
            } else {
              _this.readFile(files);
            }
          }).catch(this.resetInput);
          return;
        }
      }

      this.readFile(files);
    },
    readFile: function readFile(files) {
      var _this2 = this;

      var oversize = isOversize(files, this.maxSize);

      if (Array.isArray(files)) {
        var maxCount = this.maxCount - this.fileList.length;

        if (files.length > maxCount) {
          files = files.slice(0, maxCount);
        }

        Promise.all(files.map(function (file) {
          return _readFile(file, _this2.resultType);
        })).then(function (contents) {
          var fileList = files.map(function (file, index) {
            var result = {
              file: file,
              status: "",
              message: ""
            };

            if (contents[index]) {
              result.content = contents[index];
            }

            return result;
          });

          _this2.onAfterRead(fileList, oversize);
        });
      } else {
        _readFile(files, this.resultType).then(function (content) {
          var result = {
            file: files,
            status: "",
            message: ""
          };

          if (content) {
            result.content = content;
          }

          _this2.onAfterRead(result, oversize);
        });
      }
    },
    onAfterRead: function onAfterRead(files, oversize) {
      var _this3 = this;

      this.resetInput();
      var validFiles = files;

      if (oversize) {
        var oversizeFiles = files;

        if (Array.isArray(files)) {
          oversizeFiles = [];
          validFiles = [];
          files.forEach(function (item) {
            if (item.file) {
              if (item.file.size > _this3.maxSize) {
                oversizeFiles.push(item);
              } else {
                validFiles.push(item);
              }
            }
          });
        } else {
          validFiles = null;
        }

        this.$emit("oversize", oversizeFiles, this.getDetail());
      }

      var isValidFiles = Array.isArray(validFiles) ? Boolean(validFiles.length) : Boolean(validFiles);

      if (isValidFiles) {
        this.$emit("input", [].concat(this.fileList, toArray(validFiles)));

        if (this.afterRead) {
          this.afterRead(validFiles, this.getDetail());
        }
      }
    },
    onDelete: function onDelete(file, index) {
      var _this4 = this;

      if (this.beforeDelete) {
        var response = this.beforeDelete(file, this.getDetail(index));

        if (!response) {
          return;
        }

        if (isPromise(response)) {
          response.then(function () {
            _this4.deleteFile(file, index);
          }).catch(noop);
          return;
        }
      }

      this.deleteFile(file, index);
    },
    deleteFile: function deleteFile(file, index) {
      var fileList = this.fileList.slice(0);
      fileList.splice(index, 1);
      this.$emit("input", fileList);
      this.$emit("delete", file, this.getDetail(index));
    },
    resetInput: function resetInput() {
      /* istanbul ignore else */
      if (this.$refs.input) {
        this.$refs.input.value = "";
      }
    },
    onPreviewImage: function onPreviewImage(item) {
      var _this5 = this;

      if (!this.previewFullImage) {
        return;
      }

      var imageFiles = this.fileList.filter(function (item) {
        return isImageFile(item);
      });
      var imageContents = imageFiles.map(function (item) {
        return item.content || item.url;
      });
      this.imagePreview = ImagePreview(_extends({
        images: imageContents,
        startPosition: imageFiles.indexOf(item),
        onClose: function onClose() {
          _this5.$emit("close-preview");
        }
      }, this.previewOptions));
    },
    // @exposed-api
    closeImagePreview: function closeImagePreview() {
      if (this.imagePreview) {
        this.imagePreview.close();
      }
    },
    // @exposed-api
    chooseFile: function chooseFile() {
      if (this.disabled) {
        return;
      }
      /* istanbul ignore else */


      if (this.$refs.input) {
        this.$refs.input.click();
      }
    }
  }
});