import "./upload-panel.css";
import "core-js/modules/web.dom.iterable";
import _Promise from "@babel/runtime-corejs2/core-js/promise";

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import Qrcode from '@xkeshi/vue-qrcode';
import Panel from './panel';
import { createComponentName, componentMixin } from '../../utils/base';
import Upload from '../upload';
import Button from '../button';
import Modal from '../modal';
import Progress from '../progress';
import Icon from '../icon';
import tips from '../tips';
import request from '../../service/request'; // request.post('/api/sessions', { guest_finger: 'guest' });

const __vue_script__ = {
  name: createComponentName('editor-upload-panel'),
  components: {
    Panel,
    Icon,
    Modal,
    Upload,
    Qrcode,
    Button,
    Progress
  },
  mixins: [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() {
      return Math.max(this.files.reduce((value, file) => value + file.percent / this.files.length, 0));
    }

  },
  methods: {
    log(error) {
      tips(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) {
        tips('图片文件过大，最大支持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) {
      const index = this.files.indexOf(file);

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

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

    async addElement(src) {
      const {
        width,
        height
      } = await this.getImageSize(src);
      this.$emit('addElement', {
        type: 'image',
        url: src,
        width,
        height
      });
    },

    async onUploaded(file) {
      if (this.files.every(f => f.status === 'done')) {
        this.files = [];
        if (this.$refs.upload) this.$refs.upload.clearFiles();
      }

      this.addElement(file.src);
    },

    getImageSize(src) {
      return new _Promise((resolve, reject) => {
        const image = new Image();
        image.src = src;

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

        image.onerror = error => reject(error);
      });
    },

    generateQrCode() {
      return request.post('/api/attachments/qrcode_token').then(res => {
        this.qrcode_url = res.data.url;
        this.qrcode_token = res.data.token;
        this.setQrcodeInterval();
      });
    },

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

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

        this.toPc();
      });
    },

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

        if (retImgs.length > 0) {
          _Promise.all(retImgs.map(item => {
            /**
                 * 添加元素
                 * @arg elemnt: Elemnt
                 * @Example: this.editor.addImage(element.url);
                 * */
            this.addElement(item.url);
            return request.put(`/api/attachments/${item.id}`, {
              status: 1,
              qrcode_token: self.qrcode_token
            });
          })).then(() => {
            this.imgUploadInterval();
          }).catch(err => {
            tips(err);
          });
        } else {
          this.imgUploadInterval();
        }
      }).catch(err => {
        if (err.message === '请求超时，请重试或检查网络状态') {
          this.imgUploadInterval();
        }
      });
    },

    forwardEvent(name, ...args) {
      this.$emit(name, ...args);
    },

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

      if (!rImgPath.test(externalImg)) {
        tips(errMsg);
        return;
      }

      tips.loading('正在加载图片...');
      return request.post('/api/files', {
        url: externalImg,
        type: 'image',
        module: '/design/image'
      }).then(res => {
        tips.close();
        this.addElement(res.data);
      }).catch(() => {
        tips(errMsg);
      });
    }

  }
};
/* template */

var __vue_render__ = function () {
  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 (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 ($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 ($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 ($event) {
        if ($event.target.composing) {
          return;
        }

        _vm.externalImg = $event.target.value.trim();
      },
      blur: function ($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 */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../../utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);