"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("regenerator-runtime/runtime");

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

require("./upload-panel.css");

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

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

var _vueQrcode = _interopRequireDefault(require("@xkeshi/vue-qrcode"));

var _panel = _interopRequireDefault(require("./panel"));

var _base = require("../../utils/base");

var _upload = _interopRequireDefault(require("../upload"));

var _button = _interopRequireDefault(require("../button"));

var _modal = _interopRequireDefault(require("../modal"));

var _progress = _interopRequireDefault(require("../progress"));

var _icon = _interopRequireDefault(require("../icon"));

var _tips = _interopRequireDefault(require("../tips"));

var _request = _interopRequireDefault(require("../../service/request"));

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

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// request.post('/api/sessions', { guest_finger: 'guest' });
var __vue_script__ = {
  name: (0, _base.createComponentName)('editor-upload-panel'),
  components: {
    Panel: _panel.default,
    Icon: _icon.default,
    Modal: _modal.default,
    Upload: _upload.default,
    Qrcode: _vueQrcode.default,
    Button: _button.default,
    Progress: _progress.default
  },
  mixins: [_base.componentMixin],
  props: {
    // 默认标题
    desc: {
      type: String,
      default: '支持5M以下JPG\\PNG\\GIF格式图片'
    },
    beforeUpload: {
      type: Function
    },
    accept: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      status: 'pc',
      // pc | mobile | qr | url
      qrcode_url: '',
      qrcodeOption: {
        size: 148
      },
      title: {
        pc: '上传本地图片',
        qr: '上传手机图片',
        mobile: '已连接 \n 请在手机上操作'
      },
      files: [],
      externalImg: '',
      showModal: false
    };
  },

  computed: {
    progress() {
      var _this = this;

      return Math.max(this.files.reduce(function (value, file) {
        return value + file.percent / _this.files.length;
      }, 0));
    }

  },
  methods: {
    log(error) {
      (0, _tips.default)(error);
    },

    toPc() {
      this.status = 'pc';
      this.showModal = false;
    },

    toQr() {
      this.status = 'qr';
      this.generateQrCode();
    },

    handleBeforeUpload(gdFile) {
      if (this.beforeUpload) {
        return this.beforeUpload(gdFile);
      }

      if (gdFile.size > 1024 * 1024 * 5) {
        (0, _tips.default)('图片文件过大，最大支持5M');
        return false;
      }

      return gdFile;
    },

    cancelUpload() {
      if (this.$refs.upload) {
        this.$refs.upload.cancelAll();
        this.$refs.upload.clearFiles();
      }

      this.files = [];
    },

    onError(error, file) {
      this.onRemove(file);
      this.log(error);
    },

    onRemove(file) {
      var index = this.files.indexOf(file);

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

    onChange(files) {
      this.files = files;
    },

    addElement(src) {
      var _this2 = this;

      return (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee() {
        var _ref, width, height;

        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return _this2.getImageSize(src);

              case 2:
                _ref = _context.sent;
                width = _ref.width;
                height = _ref.height;

                _this2.$emit('addElement', {
                  type: 'image',
                  url: src,
                  width,
                  height
                });

              case 6:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }))();
    },

    onUploaded(file) {
      var _this3 = 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:
                if (_this3.files.every(function (f) {
                  return f.status === 'done';
                })) {
                  _this3.files = [];
                  if (_this3.$refs.upload) _this3.$refs.upload.clearFiles();
                }

                _this3.addElement(file.src);

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

    getImageSize(src) {
      return new _promise.default(function (resolve, reject) {
        var image = new Image();
        image.src = src;

        image.onload = function () {
          resolve({
            width: image.width,
            height: image.height
          });
        };

        image.onerror = function (error) {
          return reject(error);
        };
      });
    },

    generateQrCode() {
      var _this4 = this;

      return _request.default.post('/api/attachments/qrcode_token').then(function (res) {
        _this4.qrcode_url = res.data.url;
        _this4.qrcode_token = res.data.token;

        _this4.setQrcodeInterval();
      });
    },

    setQrcodeInterval() {
      var _this5 = this;

      _request.default.get('/api/qrcodes/' + this.qrcode_token, {
        params: {
          client_type: 'desktop'
        }
      }).then(function (ret) {
        if (ret.data.scaned > 0) {
          // 已被扫描。给二维码设置遮罩、清除状态轮询
          _this5.status = 'mobile';

          _this5.imgUploadInterval();
        }

        if (!ret.data) {
          _this5.setQrcodeInterval();
        }
      }).catch(function (ret) {
        if (ret.message === '请求超时，请重试或检查网络状态') {
          _this5.setQrcodeInterval();
        }

        _this5.toPc();
      });
    },

    imgUploadInterval() {
      var _this6 = this;

      _request.default.get(`/api/attachments/${this.qrcode_token}/images`).then(function (ret) {
        // 有新的图片上传。执行插入操作.插入完成更新附件状态
        var retImgs = ret.data;

        if (retImgs.length > 0) {
          _promise.default.all(retImgs.map(function (item) {
            /**
                 * 添加元素
                 * @arg elemnt: Elemnt
                 * @Example: this.editor.addImage(element.url);
                 * */
            _this6.addElement(item.url);

            return _request.default.put(`/api/attachments/${item.id}`, {
              status: 1,
              qrcode_token: self.qrcode_token
            });
          })).then(function () {
            _this6.imgUploadInterval();
          }).catch(function (err) {
            (0, _tips.default)(err);
          });
        } else {
          _this6.imgUploadInterval();
        }
      }).catch(function (err) {
        if (err.message === '请求超时，请重试或检查网络状态') {
          _this6.imgUploadInterval();
        }
      });
    },

    forwardEvent(name) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      this.$emit.apply(this, [name].concat(args));
    },

    uploadExternalImg() {
      var _this7 = this;

      var rImgPath = /^https?:\/\//;
      var errMsg = '无法加载图片，请检查图片地址是否正确';
      var externalImg = this.externalImg.trim();

      if (!rImgPath.test(externalImg)) {
        (0, _tips.default)(errMsg);
        return;
      }

      _tips.default.loading('正在加载图片...');

      return _request.default.post('/api/files', {
        url: externalImg,
        type: 'image',
        module: '/design/image'
      }).then(function (res) {
        _tips.default.close();

        _this7.addElement(res.data);
      }).catch(function () {
        (0, _tips.default)(errMsg);
      });
    }

  }
};
/* template */

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

  var _h = _vm.$createElement;

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

  return _c("Panel", {
    class: _vm.bem(),
    attrs: {
      name: "upload"
    },
    on: {
      close: _vm.toPc
    },
    scopedSlots: _vm._u([{
      key: "tab",
      fn: function fn(ref) {
        var active = ref.active;
        return [_vm._t("label", [_c("Icon", {
          attrs: {
            name: "upload"
          }
        }), _vm._v(" "), _c("span", [_vm._v("传图片")])], {
          active: active
        })];
      }
    }])
  }, [_c("template", {
    slot: "title"
  }, [_vm._t("title")], 2), _vm._v(" "), _vm._t("default", [_c("div", {
    class: _vm.bem("header")
  }, [_vm._t("header", [_c("pre", {
    class: _vm.bem("title")
  }, [_vm._v(_vm._s(_vm.title[_vm.status]))]), _vm._v(" "), _c("sub", {
    class: _vm.bem("desc")
  }, [_vm._v(_vm._s(_vm.desc))])])], 2), _vm._v(" "), _c("div", {
    class: _vm.bem("body")
  }, [_vm.status === "pc" ? [_vm._t("local-upload", [_c("upload", {
    ref: "upload",
    attrs: {
      autoUpload: "",
      multiple: "",
      beforeUpload: _vm.handleBeforeUpload,
      accept: _vm.accept,
      concurrent: 1
    },
    on: {
      change: _vm.onChange,
      remove: _vm.onRemove,
      success: _vm.onUploaded,
      error: _vm.onError
    }
  }, [_c("Button", {
    class: _vm.bem("upload-btn"),
    attrs: {
      rect: "",
      size: "large",
      type: "primary"
    }
  }, [_vm._v("上传")])], 1)], {
    onUploaded: _vm.onUploaded,
    log: _vm.log
  }), _vm._v(" "), _c("Button", {
    attrs: {
      type: "text",
      size: "small"
    },
    on: {
      click: _vm.toQr
    }
  }, [_vm._v("上传手机图片")])] : _vm.status === "qr" ? [_c("qrcode", {
    class: _vm.bem("qrcode"),
    attrs: {
      value: _vm.qrcode_url,
      options: _vm.qrcodeOption
    }
  }), _vm._v(" "), _c("div", {
    class: _vm.bem("qrcode-desc")
  }, [_vm._v("扫一扫二维码上传")]), _vm._v(" "), _c("Button", {
    class: _vm.bem("back-pc"),
    attrs: {
      type: "text",
      size: "small"
    },
    on: {
      click: _vm.toPc
    }
  }, [_vm._v("\n                    <返回本地上传\n                ")])] : _vm.status === "mobile" ? [_c("img", {
    class: _vm.bem("qrcode-scaned"),
    attrs: {
      src: require("../../assets/img/editor/qrcode-scaned.png"),
      alt: ""
    }
  }), _vm._v(" "), _c("Button", {
    class: _vm.bem("back-pc"),
    attrs: {
      type: "text",
      size: "small"
    },
    on: {
      click: _vm.toQr
    }
  }, [_vm._v("\n                    <重新扫描二维码\n                ")])] : _vm._e()], 2), _vm._v(" "), _vm.status === "pc" ? _c("div", {
    class: _vm.bem("footer")
  }, [_c("Button", {
    attrs: {
      type: "text",
      size: "small"
    },
    on: {
      click: function click($event) {
        _vm.showModal = !_vm.showModal;
      }
    }
  }, [_vm._v("网址上传 / 剪贴板上传 / 拖拽上传")])], 1) : _vm._e(), _vm._v(" "), _c("Modal", {
    class: [_vm.bem("upload-modal")],
    attrs: {
      theme: "dark",
      visible: _vm.showModal,
      "append-body": false,
      transitionName: "gd-upload-modal-fade",
      "transition-duration": {
        enter: 300,
        leave: 300
      },
      width: "100%",
      top: "auto",
      bottom: "0"
    },
    on: {
      "update:visible": function updateVisible($event) {
        _vm.showModal = $event;
      }
    }
  }, [_c("div", {
    class: _vm.bem("upload-modal-title")
  }, [_vm._v("拖拽上传")]), _vm._v(" "), _c("div", {
    class: _vm.bem("upload-modal-desc")
  }, [_vm._v("将图片"), _c("u", [_vm._v("拖拽到画布")]), _vm._v("，完成上传。")]), _vm._v(" "), _c("div", {
    class: _vm.bem("upload-modal-title")
  }, [_vm._v("剪贴板上传")]), _vm._v(" "), _c("div", {
    class: _vm.bem("upload-modal-desc")
  }, [_vm._v("使用"), _c("u", [_vm._v("CTRL+V")]), _vm._v("，可直接粘贴剪贴板图片到画布。")]), _vm._v(" "), _c("div", {
    class: _vm.bem("upload-modal-title")
  }, [_vm._v("网址上传")]), _vm._v(" "), _c("div", {
    class: _vm.bem("url-upload")
  }, [_c("input", {
    directives: [{
      name: "model",
      rawName: "v-model.trim",
      value: _vm.externalImg,
      expression: "externalImg",
      modifiers: {
        trim: true
      }
    }],
    attrs: {
      type: "input",
      placeholder: "http://"
    },
    domProps: {
      value: _vm.externalImg
    },
    on: {
      input: function input($event) {
        if ($event.target.composing) {
          return;
        }

        _vm.externalImg = $event.target.value.trim();
      },
      blur: function blur($event) {
        _vm.$forceUpdate();
      }
    }
  }), _vm._v(" "), _c("Button", {
    attrs: {
      rect: "",
      size: "small"
    },
    on: {
      click: _vm.uploadExternalImg
    }
  }, [_vm._v("上传")])], 1)])]), _vm._v(" "), _c("Modal", {
    class: _vm.bem("importer"),
    attrs: {
      visible: !!_vm.files.length,
      showClose: false,
      top: "25%"
    }
  }, [_c("h3", {
    class: _vm.bem("importer-title")
  }, [_vm._v("正在上传图片...")]), _vm._v(" "), _c("Progress", {
    attrs: {
      value: _vm.progress
    }
  }), _vm._v(" "), _c("div", {
    attrs: {
      slot: "footer"
    },
    slot: "footer"
  }, [_c("Button", {
    attrs: {
      type: "text"
    },
    on: {
      click: _vm.cancelUpload
    }
  }, [_vm._v("取消")])], 1)], 1)], 2);
};

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;