import { Button, CATEGORIES, iconFont } from '../../configuration/constants'

import icons from "../../assets/icon.txt";

export default {

  // 组件名称
  name: Button,

  // 前面板html模板
  viewTemplate() {
    return `
      <button data-gjs-type="${Button}" class="${Button}">按钮</button>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${Button} {
          position: relative;
          padding: 8px 16px;
          border: 1px solid rgba(0,0,0,0.3);
          border-radius: 3px;
          text-align: center;
          box-shadow: 0 1px 3px rgba(0,0,0,0.2);
          overflow: hidden;
        }
        .${Button}::after {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          top: 0;
          bottom: 0;
          background-color: rgba(255,255,255,0.2);
          opacity: 0;
          transform: scale(0.1);
          transition: all 0.4s ease;
        }
        .${Button}:not([disabled]):hover::after {
          transform: scale(1);
          opacity: 1;
        }
        .${Button}:not([disabled]):focus {
          transform: scale(1);
          opacity: 1;
          outline: none;
          box-shadow: inset 0 2px 3px rgba(0,0,0,0.3);
        }
        .${Button} > span {
          font-size: inherit;
        }
        .${Button} > .spicon {
          margin-right: 8px;
          font-size: inherit;
          line-height: 1;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label:'按钮',
      attributes: {class:'fa fa-square'},
    };
  },

  spOptions() {
    return {
      label: '按钮',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/41f95a50-dd9e-48a9-acf1-ff1b166f54d7?# 《按钮》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      outPorts: [
        {
          uuid: 'out1',
          subType: 'string',
          description: {
            zh_CN: '输出字符串'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      droppable: false,
      resizable: true,
      dmode: 'absolute',
      traits: [{
        name: 'label',
        label: '文本',
        changeProp: 1,
      }, {
        label: '图标名称',
        changeProp: 1,
        name: 'icon'
      }, {
        name: 'changeIcon',
        type: "button",
        text: "更换图标",
        full: true, // Full width button
        command(editor, model) {
          this.handleOpenModal(editor, model);
        },
      }, {
        label: 'Param',
        changeProp: 1,
        name: 'param'
      }, {
        label: '多状态',
        changeProp: 1,
        name: 'toggle',
        type: 'checkbox'
      }, {
        label: '关联目标',
        changeProp: 1,
        name: 'targetType',
        type: 'select',
        options: [{id: '', name: '无'}, {id: 'modal', name: '模态框'}, {id: 'table', name: '表格'}, {id: 'select', name: '选择框'}]
      }, {
        label: '目标Id',
        changeProp: 1,
        name: 'targetId',
      }],
      "label": '按钮',
      "icon": null,
      "param": '1',
      "toggle": false,
      "targetType": '',
      "targetId": null,
    }
  },

  handleSelectIcon(editor, e) {
    const target = e.target;
    if (target.matches(`button[class~=${iconFont}]`)) {
      const iconKey = target.dataset.type;
      const _prevVal = this.get("icon");
      const isMultiParam = this.get("toggle");
      console.log(isMultiParam)
      if (_prevVal && _prevVal !== "" && isMultiParam) {
        this.set("icon", _prevVal + ',' + iconKey);
      } else {
        this.set("icon", iconKey);
      }

      editor.Modal.close();
    }
  },

  handleOpenModal(editor, model) {
    const iconKeys = JSON.parse(icons)["icons"].map((icon) => icon.font_class);
    const modal = editor.Modal;
    const handleSelectIcon = this.handleSelectIcon.bind(this, editor);

    document.addEventListener("click", handleSelectIcon);

    modal
      .open({
        title: "选择图标",
        content: `
          <div class="icon-select-mdl">
            ${iconKeys
              .map(
                (iconKey) => `
                  <div class="icon-select-block" title=${iconKey}>
                    <button class="spicon icon-${iconKey}" data-type=${iconKey}></button>
                    <p class="icon-name">${iconKey}</p>
                  </div>
                `
              )
              .join("")}            
          </div>
      `,
      })
      .getModel()
      .once("change:open", () =>
        document.removeEventListener("click", handleSelectIcon)
      );
  },

  onModelScript() {
    const _label = ('{[ label ]}').toString();
    const _icon = ('{[ icon ]}').toString();
    const _param = ('{[ param ]}').toString();
    const targetType = '{[ targetType ]}';
    const targetId = ('{[ targetId ]}').toString();
    const toggle = Boolean('{[ toggle ]}');
    
    const self = this;
    const eventName = 'call-' + self.getAttribute('id');

    const getList = function (str) {
      return str.indexOf(',') > -1 ? str.split(',').map(function(item) {return item.trim()}) : [str];
    };
    const label = getList(_label);
    const icon = getList(_icon);
    const param = getList(_param);

    $(self).empty();
    if (Boolean(_label)) {
      $(self).append('<span>'+ label[0] +'</span>')
    }
    if (Boolean(_icon)) {
      $(self).prepend('<i class="spicon icon-' + icon[0] + '"></i>')
    }

    let count = 0;
    const handleClick = function (e) {
      if (window.spSocket) {
        window.spSocket.send({
          eventName: eventName,
          data: {
            success: true,
            out1: param[count]
          }
        });
      }
      if (Boolean(toggle)) {
        if (count < param.length - 1) {
          count += 1;
        } else {
          count = 0;
        }
        const nextLabel = label[count] || label[label.length - 1];
        $(self).children('span').text(nextLabel);
        if (Boolean(_icon)) {
          const nextIcon = icon[count] || icon[icon.length - 1];
          $(self).children('i').attr('class', 'spicon icon-' + nextIcon);
        }
      }
      if (Boolean(targetType) && Boolean(targetId)) {
        window.ee && window.ee.emit(targetType + '-' + targetId, param[0])
      }
    };
    $(self).on('click', handleClick);
    $(self).on('mouseup', function(e) {
      this.blur();
    });
  },

  onViewInit() {
    const evn = "change:label change:icon change:param change:toggle change:targetType change:targetId";
    const changeIconCmd = this.model.getTrait('changeIcon').get('command');
    
    this.model.getTrait('changeIcon').set('command', changeIconCmd.bind(this.model));

    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
