import { imgBase64Ref, CATEGORIES } from "../../configuration/constants";

export default {
  // 组件名称
  name: imgBase64Ref,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${imgBase64Ref}" class="${imgBase64Ref}"></div>
    `;
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${imgBase64Ref} {
          overflow: hidden;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .${imgBase64Ref}.bgColor-none {
          background: none;
        }
        .${imgBase64Ref}.bgColor-default {
          background-color: #f5f5f5;
        }
        .${imgBase64Ref}.bgColor-white {
          background-color: #fff;
        }
        .${imgBase64Ref}.bgColor-light {
          background-color: rgba(0,0,0,0.1);
        }
        .${imgBase64Ref}.bgColor-dark {
          background-color: rgba(255,255,255,0.06);
        }
        .${imgBase64Ref}.bgColor-none.bd {
          border: 1px solid rgba(0,0,0,0.1);
        }
        .${imgBase64Ref}.bgColor-default.bd {
          border: 1px solid #d9d9d9;
        }
        .${imgBase64Ref}.bgColor-light.bd {
          border: 1px solid rgba(0,0,0,0.1);
        }
        .${imgBase64Ref}.bgColor-dark.bd {
          border: 1px solid rgba(255,255,255,0.1);
        }
        .${imgBase64Ref}.radius-none {
          border-radius: 0;
        }
        .${imgBase64Ref}.radius-xs {
          border-radius: 3px;
        }
        .${imgBase64Ref}.radius-sm {
          border-radius: 5px;
        }
        .${imgBase64Ref}.radius-md {
          border-radius: 8px;
        }
        .${imgBase64Ref}.radius-lg {
          border-radius: 12px;
        }
        .${imgBase64Ref}.radius-xl {
          border-radius: 20px;
        }
        .${imgBase64Ref}.radius-xxl {
          border-radius: 50%;
        }
        .${imgBase64Ref} > .gjs-plh-image{
          background: none;
          outline: none;
        }
        .${imgBase64Ref} > .xly-image-flex{
          max-width: 100%;
          max-height: 100%;
          width: auto;
          height: auto;
          background: none;
        }
      </style>
    `;
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: "图片",
      category: CATEGORIES.MEDIA,
      attributes: { class: "fa fa-image" },
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: "Base64图片",
      icon: "globe",
      author: "宗介",
      email: "zongjie.wxt@xuelangyun.com",
      inPorts: [
        {
          uuid: "in1",
          type: "data",
          ioType: "in",
          subType: "string",
          display: true,
          description: {
            zh_CN: "输入1",
          },
        },
      ],
    };
  },

  // 组件属性
  componentOptions() {
    return {
      resizable: true,
      dmode: "absolute",
      childrenSelectable: false,
      highlightable: false,
      droppable: false,
      style: { width: "600px", height: "400px", "align-items": "stretch" },
      traits: [
        {
          name: "data",
          type: "text",
          label: "图片路径",
          changeProp: 1,
        },
        {
          name: 'selectedButton',
          type: "button",
          text: "上传图片",
          full: true, // Full width button
          command: (editor, model) =>
            editor.trigger(`reselect-${model.target.cid}`),
        },
        {
          name: "border",
          label: "边框",
          changeProp: 1,
          type: "checkbox",
        },
        {
          name: "bgColor",
          label: "背景色",
          changeProp: 1,
          type: "select",
          options: ["none", "default", "light", "white", "dark"],
        },
        {
          name: "radius",
          label: "圆角",
          changeProp: 1,
          type: "select",
          options: ["none", "xs", "sm", "md", "lg", "xl", "xxl"],
        },
      ],
      data: "",
      bgColor: "none",
      border: true,
      radius: "xs",
    };
  },

  onModelScript() {
    const data = "{[ data ]}";
    const border = Boolean("{[ border ]}");
    const bgColor = "{[ bgColor ]}";
    const radius = "{[ radius ]}";
    const self = this;
    $(self).attr(
      "class",
      "xly-imgBase64 radius-" + radius + " bgColor-" + bgColor
    );
    border ? $(self).addClass("bd") : $(self).removeClass("bd");
    $(self).children("img").width("100%").height("100%").attr("src", data);

    const convertBase64StringToBlob = function (data) {
      var mime = "image/",
        bstr = window.atob(data),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      if (data.indexOf("iVB") == 0) {
        mime += "png";
      } else if (data.indexOf("/9j") == 0) {
        mime += "jpg";
      } else {
        mime += "png";
      }
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    };

    const renderImg = function (str) {
      var blob = convertBase64StringToBlob(str);
      var src = URL.createObjectURL(blob);
      $(self)
        .children("img")
        .attr("src", src)
        .on("load", function () {
          URL.revokeObjectURL(src);
        });
    };

    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      var name = `call-` + self.getAttribute("id");
      window.spSocket.subscribe({
        eventName: name,
        callback: function (data) {
          if (data.data.in1) {
            var base64String = data.data.in1;
            if (base64String.indexOf('"') > -1) {
              base64String = base64String.replace(/\"/g, "");
            }
            renderImg(base64String);
          }
        },
      });
    }
  },

  openAssetsModal() {
    const self = this;
    const editor = this.em.getEditor();
    if (editor) {
      editor.runCommand("open-assets", {
        target: this.model,
        types: ["image"],
        accept: "image/*",
        onSelect(model) {
          const $img = self.$el.children("img");
          if (model && $img.length) {
            const src = model.get("src");
            $($img.get(0)).attr("src", src);
            self.model.set("data", src);
            self.model.trigger("change:data", self.model, src);
          }
          editor.Modal.close();
          editor.AssetManager.setTarget(null);
        },
      });
    }
  },

  onViewInit() {
    const self = this;
    const evn = "change:data change:border change:radius change:bgColor";
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
    const comps = this.model.get("components");
    const currentId = this.model.ccid;
    const editor = this.em.getEditor();

    editor.on(`reselect-${this.model.cid}`, () => {
      this.model.openAssetsModal.call(this);
    });
    
    editor.on('component:update:traits', (model) => {
      const { ccid } = model;
      if (currentId === ccid) {
        const { data } = model.getTrait('data').target.attributes;
        if (data && data !== '') {
          $('#style-container').find('.gjs-trt-trait__wrp-selectedButton').find('button').html('更换图片');
        } else {
          $('#style-container').find('.gjs-trt-trait__wrp-selectedButton').find('button').html('上传图片');
        }
       }
    });

    if (!comps.length) {
      comps.reset();
      comps.add(
        `<img class="xly-imgBase64-image" src="" style="pointer-events: none;" />`
      );
    }

    setTimeout(function () {
      $(self.$el.children("img").get(0)).dblclick(
        self.model.openAssetsModal.bind(self)
      );
    }, 1000);
  },

  onViewRemoved() {
    const editor = this.em.getEditor();

    editor.off(`reselect-${this.model.cid}`);
  },
};
