import { pathImage, CATEGORIES } from '../../configuration/constants'

export default {

  // 组件名称
  name: pathImage,

  // 前面板html模板
  viewTemplate() {
    return `
      <img data-gjs-type="${pathImage}" class="${pathImage}" src='#' />
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${pathImage} {
          width: 400px;
          height: 300px;
        }
      </style>
    `
  },

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

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '路径图片',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/990140c1-d357-4d45-a35e-ee2747284216?# 《路径图片》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'string',
          description: {
            zh_CN: '输入1'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: pathImage,
      droppable: false,
      resizable: true,
      disableChildEdit: true,
      highlightable: false,
      traits: [{
        name: 'defaultPath',
        label: '默认路径',
        changeProp: 1
      }],
      "defaultPath": null,
    }
  },

  onModelScript() {
    const defaultPath = '{[ defaultPath ]}';

    const self = this;
    const eventName = `call-${self.getAttribute('id')}`;
    const $img = $(self);

    const isAbsolutePath = function(path) {
      return path.indexOf('studio/') !== 0
    };

    Boolean(defaultPath) && isAbsolutePath(defaultPath) ? $img.attr('src', defaultPath) : $img.attr('src', '#');
    const renderKeyPath = function(key) {
      window.spSocket && window.spSocket.oss.getSignedUrl(key).then(
        function(url) {
          $img.attr({"src": url})
        }
      )
    };
    
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let value = _data.data.in1;
          if (isAbsolutePath(value)) {
            $img.attr({"src": value})
          } else {
            renderKeyPath(value);
          }
        }
      });
    }
  },

  onViewInit() {
    const evn = "change:defaultPath";
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
