import { navTags, CATEGORIES } from '../../configuration/constants'
import { throttle } from '../../utils'
import { data } from 'jquery'
export default {

  // 组件名称
  name: navTags,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${navTags}" class="${navTags}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${navTags} {
          display: flex;
          flex-wrap: wrap;
          width: 600px;
        }
        .${navTags} > .${navTags}-item {
          display: inline-block;
          align-items: center;
          margin: 8px;
          padding: 8px 16px;
          border-radius: 3px;
          border: 1px solid #d9d9d9;
          background-color: #fafafa;
          color: rgba(0,0,0,.65);
        }
        .${navTags} > .${navTags}-item.selected {
          background-color: #1890ff;
          border-color: #1890ff;
          color: #fff;
        }
        .${navTags} > .${navTags}-item > .${navTags}-item__remove {
          font-style: normal;
          margin: 0 -8px 0 8px;
          padding: 0 4px;
          display: inline-block;
          cursor: pointer;
        }
        .${navTags} > .${navTags}-item > .${navTags}-item__remove:hover {
          color: #1890ff;
        }
        .${navTags} > .${navTags}-item.selected > .${navTags}-item__remove:hover {
          color: rgba(255,255,255,0.8);
        }
        .${navTags} > .${navTags}-item__add {
          display: inline-block;
          margin: 8px;
          height: 40px;
          overflow: hidden;
        }
        .${navTags} > .${navTags}-item__add > .${navTags}-item__add__button {
          display: inline-block;
          padding: 8px 24px;
          border: 1px dashed #d9d9d9;
          border-radius: 3px;
          background-color: #fafafa;
          color: rgba(0,0,0,.65);
          text-align: center;
        }
        .${navTags} > .${navTags}-item__add > .${navTags}-item__add__button:hover {
          border-color: #1890ff;
          color: #1890ff;
        }
        .${navTags} > .${navTags}-item__add > .${navTags}-item__add__inputs {
          padding: 4px 0;
          display: none;
        }
        .${navTags} > .${navTags}-item__add > .${navTags}-item__add__inputs > input {
          width: 80px;
          height: 32px;
          padding 4px 8px;
          border: 1px solid #d9d9d9;
        }
        .${navTags} > .${navTags}-item__add > .${navTags}-item__add__inputs > input:first {
          border-radius: 3px 0 0 3px;
        }
        .${navTags} > .${navTags}-item__add > .${navTags}-item__add__inputs > input:last {
          margin-left: -1px;
          border-radius: 0 3px 3px 0;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: "标签组",
      attributes: { class: 'fa fa-tasks' },
    };
  },

  spOptions() {
    return {
      label: '标签组',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/ae0beac4-25a3-47e1-99dc-e584bd0bbd9e?# 《标签组》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入Json'
        }
      }],
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出Json'
        }
      }],
    }
  },

  // 组件属性
  componentOptions() {
    return {
      droppable: true,
      resizable: true,
      dmode: 'absolute',
      // highlightable: true,
      childrenSelectable: false,
      traits: [{
        name: 'keyValues',
        label: '默认数据',
        changeProp: 1,
        type: 'key-value'
      }, {
        name: 'closable',
        label: '动态删除',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'addable',
        label: '动态添加',
        changeProp: 1,
        type: 'checkbox'
      }],
      "keyValues": "标签1: 1, 标签2: 2",
      "closable": true,
      "addable": true,
    }
  },

  onModelScript() {
    const closable = Boolean("{[ closable ]}");
    const addable = Boolean("{[ addable ]}");
    const keyValues = "{[ keyValues ]}";
    let dataset = keyValues.split(',').map(function (item) {
      const _key_value = item.split(':');
      const name = _key_value[0].trim();
      const value = _key_value[1].trim();
      return { name, value };
    });
    const eventName = `call-${this.getAttribute('id')}`;
    const self = this;

    const render = function (data) {
      $(self).empty();
      let selectedIndex = data.findIndex(item => item.status == 'selected');
      if (selectedIndex == -1) {
        selectedIndex = 0;
      }
      data.forEach(function (item, index) {
        $(self).append(`<a data-gjs-type="default" class="nav-tags-item${index == selectedIndex ? ' selected' : ''}" data-asset="${item.name}:${item.value}">${item.name}${closable ? '<i class="nav-tags-item__remove">×</i>' : ''}</a>`);
      });
      if (addable) {
        $(self).append(`<div class="nav-tags-item__add"><a class="nav-tags-item__add__button">＋</a><div class="nav-tags-item__add__inputs"><input type="text" name="name" placeholder="名称" /><input type="text" name="value" placeholder="值" /></div></div>`);
      }
      data[selectedIndex]['status'] = 'selected';
      onSpSockedSend(data[selectedIndex]);
    };

    const onSpSockedSend = function (out) {
      if (window.spSocket) {
        window.spSocket.send({
          eventName: eventName,
          data: {
            success: true,
            out1: JSON.stringify(out)
          }
        });
      }
    };

    const onSend = function (e) {
      const removed = $(e.target).attr('class') == "nav-tags-item__remove";
      const $item = removed ? $(e.target).parent() : $(e.target);
      const _v = $item.attr('data-asset').split(':');
      const status = removed ? 'removed' : 'selected';
      const name = _v[0];
      const value = _v[1];
      if (status === 'selected') {
        $item.addClass('selected').siblings().removeClass('selected');
        dataset.forEach(item => {
          if (name == item.name && value == item.value) {
            item['status'] = 'selected';
            onSpSockedSend(item);
          } else if (item.status && item.status == 'selected') {
            delete item.status;
          }
        });
      } else {
        $item.remove();
        const _index = dataset.findIndex(item => name == item.name && value == item.value);
        if (_index > -1) {
          const item = dataset.splice(_index, 1)[0];
          onSpSockedSend(Object.assign({}, item, {status: status}));
          if (item['status'] && item['status'] == 'selected') {
            const selectedIndex = _index == dataset.length ? _index - 1 : _index;
            dataset[selectedIndex]['status'] = 'selected';
            $(self).children('.nav-tags-item').eq(selectedIndex).addClass('selected');
            onSpSockedSend(dataset[selectedIndex]);
          }
        }
      }
    };

    const onClickAddButton = function () {
      $(this).fadeOut('fast').siblings().fadeIn();
    };
    const onAddItem = function (e) {
      const name = $(self).find('input[name=name]').val();
      const value = $(self).find('input[name=value]').val();
      if (value && name) {
        const item = { name: name, value: value, status: 'created' };
        onSpSockedSend(item);
        dataset.forEach(tag => {
          if (tag.status && tag.status == 'selected') {
            delete tag.status;
          }
        });
        item.status = 'selected';
        dataset.push(item);
        render(dataset);
      }
    };
    $(self).on('click', '.nav-tags-item__remove', onSend);
    $(self).on('click', '.nav-tags-item', onSend);
    $(self).on('click', '.nav-tags-item__add__button', onClickAddButton);
    $(self).on('blur', '.nav-tags-item__add__inputs input', onAddItem);
    render(dataset);
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          if (_data.data && _data.data.in1) {
            dataset = JSON.parse(_data.data.in1);
            render(dataset);
          }
        }
      });
    }
  },

  onViewInit() {
    this.listenTo(this.em, 'update:component:style:height update:component:style:width', throttle.bind(this, this.updateScript.bind(this)));
    const evn = 'change:keyValues change:closable change:addable';
    this.listenTo(this.model, evn, this.updateScript);
  }
}
