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

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

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${select}" class="${select}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${select} {
          width: 450px;
          padding: 10px;
        }
        .${select}-2 {
          top: 0!important;
          left: 0!important;
        }
        .${select} .select2-container {
          display: block!important;
          width: 100%!important;
          height: 100%;
        }
        .${select} .select2-container .selection {
          height: 100%;
        }
        .select2-container--default .select2-selection--single:focus, .select2-container--default .select2-selection--multiple:focus {
          border-color: #0084ff;
        }
        .select2-container--default .select2-selection--single, .select2-container--default .select2-selection--multiple {
          border-color: #d9d9d9;
          border-radius: 2px;
          height: 100%;
        }
        .select2-container--default .select2-selection--multiple .select2-selection__rendered {
          padding-left: 4px;
          padding-right: 4px;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
          color: rgba(0,0,0,0.6);
          line-height: inherit;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
          height: 100%;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow b {
          border-top-color: rgba(0, 0, 0, 0.45);
        }
        .select2-container--default .select2-selection--multiple .select2-selection__choice {
          background-color: #f5f5f5;
          border-color: #f0f0f0;
          margin-right: 3px;
          margin-top: 3px;
          height: 24px;
          color: rgba(0,0,0,0.6);
          line-height: 22px;
        }
        .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
          color: rgba(0, 0, 0, 0.45);
        }

        .${select}.dark .select2-container--default .select2-selection--single,
        .${select}.dark .select2-container--default .select2-selection--multiple {
          background-color: #363739;
          border-color: #454648;
        }
        .${select}.dark .select2-container--default .select2-search--inline .select2-search__field,
        .${select}.dark .select2-container--default .select2-selection--single .select2-selection__rendered {
          color: rgba(255, 255, 255, 0.4);
        }
        .${select}.dark .select2-container--default .select2-selection--single .select2-selection__arrow b {
          border-top-color: #828282;
        }
        .${select}.dark .select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
          border-bottom-color: #828282;
        }
        .${select}.dark .select2-dropdown {
          background-color: #19181D;
          border-color: #454648;
          color: rgba(255,255,255,0.6);
          font-size: inherit;
        }
        .${select}.dark .select2-container--default .select2-search--dropdown .select2-search__field {
          background-color: #363739;
          border-color: #454648;
          color: rgba(255, 255, 255, 0.6);
          outline: none;
        }
        .${select}.dark .select2-container--default .select2-search--dropdown .select2-search__field:focus {
          border-color: #0084FF;
        }
        .${select}.dark .select2-container--default .select2-results__option[aria-disabled=true] {
          background-color: unset;
          color: rgba(255,255,255,0.2);
        }
        .${select}.dark .select2-container--default .select2-results__option--highlighted[aria-selected] {
          background-color: #0084FF;
          color: rgba(255, 255, 255, 0.6);
          border-radius: 0;
        }
        .${select}.dark .select2-container--default .select2-selection--multiple .select2-selection__choice {
          background-color: #1B1C1E;
          border-color: #454648;
          color: rgba(255, 255, 255, 0.6);
        }
        .${select}.dark .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
          color: rgba(255,255,255,0.4);
        }
        .${select}.dark .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
          color: #0084FF;
        }
        .${select}.dark .select2-container--default .select2-results__option[aria-selected=true] {
          background-color: #363739;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg class="gjs-block-svg" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path class="gjs-block-svg-path" d="M22,9 C22,8.4 21.5,8 20.75,8 L3.25,8 C2.5,8 2,8.4 2,9 L2,15 C2,15.6 2.5,16 3.25,16 L20.75,16 C21.5,16 22,15.6 22,15 L22,9 Z M21,15 L3,15 L3,9 L21,9 L21,15 Z" fill-rule="nonzero"></path>
          <polygon class="gjs-block-svg-path" transform="translate(18.500000, 12.000000) scale(1, -1) translate(-18.500000, -12.000000) " points="18.5 11 20 13 17 13"></polygon>
          <rect class="gjs-block-svg-path" x="4" y="11.5" width="11" height="1"></rect>
        </svg>
        <div class="gjs-block-label">选择框</div>
      `
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '选择框',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/f02e9ddd-b6a2-4100-b75b-c23107774c31?# 《选择框》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'all',
          description: {
            zh_CN: '输入1'
          }
        }
      ],
      outPorts: [
        {
          uuid: 'out1',
          subType: 'all',
          description: {
            zh_CN: '输出1'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: select,
      resizable: true,
      dmode: 'absolute',
      droppable: true,
      isFormItem: true,
      childrenSelectable: false,
      traits: [{
        name: 'multi',
        label: '多选',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'key',
        label: '名称属性',
        changeProp: 1
      }, {
        name: 'options',
        label: '选项',
        changeProp: 1,
        type: 'textarea'
      }, {
        name: 'tags',
        label: '动态创建',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'onChangeEvent',
        label: '实时发送选中值',
        changeProp: 1,
        type: 'checkbox'
      }, {
        name: 'dark',
        label: '暗黑风格',
        type: 'checkbox',
        changeProp: 1
      }],
      'multi': false,
      'onChangeEvent': true,
      'key': 'string',
      'options': '\[\{\\\"id\\\": \\\"a\\\", \\\"text\\\": \\\"选项A\\\"\},\{\\\"id\\\": \\\"b\\\", \\\"text\\\": \\\"选项B\\\"\},\{\\\"id\\\": \\\"c\\\", \\\"text\\\": \\\"选项C\\\", \\\"disabled\\\": true\}\]',
      'dark': false
    }
  },

  onModelScript() {
    const multi = Boolean('{[ multi ]}');
    const onChangeEvent = Boolean('{[ onChangeEvent ]}');
    const tags = Boolean('{[ tags ]}');
    const name = ('{[ key ]}').toString();
    const options = '{[ options ]}';
    const dark = Boolean('{[ dark ]}');
    const self = this;
    const _id = self.getAttribute('id');
    const eventName = 'call-' + _id;
    let data = [];
    let selector
    try {
      data = JSON.parse(options);
      if (data.length) {
        data = data.map(function (opt) {
          const row = {};
          for (let prop in opt) {
            row[prop.trim()] = opt[prop];
          }
          return row;
        })
      }
    } catch (err) {
      console.error(options, err)
    }

    const multiProp = multi ? 'multiple="multiple"' : '';
    dark ? $(self).addClass('dark') : $(self).removeClass('dark');
    const onChange = function (e) {
      const { id, text, selected } = e.params.data;
      const data = { id, text, selected };

      window.spSocket && window.spSocket.send({
        eventName: eventName,
        data: {
          success: true,
          out1: JSON.stringify(data)
        }
      });
    };
    const renderSelector = function (data) {
      $(self).empty();
      const selectedIndex = data.findIndex((item) => item.selected);
      const $select = $('<select class="select-comp-2" name="' + name + '"' + multiProp + '></select>');
      $(self).append($select);
      selector = $select.select2({
        dropdownParent: $(self),
        placeholder: "请选择",
        language: "zh-CN",
        tags: tags,
        data: data
      });

      if ($(self).parent().attr('data-gjs-type') !== 'form' && onChangeEvent) {
        $select.on('select2:select', onChange);
        $select.on('select2:unselect', onChange);
      } else {
        $select.off('select2:select', onChange);
        $select.off('select2:unselect', onChange);
      } 
      if (selectedIndex > -1) {
        $select.trigger({
          type: 'select2:select',
          params: {
            data: data[selectedIndex]
          }
        })
      } else if (!multi) {
        $select.trigger({
          type: 'select2:select',
          params: {
            data: data[0]
          }
        })
      }
    };

    renderSelector(data);

    window.ee && window.ee.on('select-' + _id, function(param) {
      const selected = selector.val();
      let data
      if (multi) {
        data = selected.map(id => {
          const text = selector.children('option[value=' + id + ']').text();
          return { id, text }
        })
      } else {
        const text = selector.children('option[value=' + selected + ']').text();
        data = { id: selected, text }
      }

      window.spSocket && window.spSocket.send({
        eventName: eventName,
        data: {
          success: true,
          out1: JSON.stringify(data)
        }
      });
    })

    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          const value = _data.data.in1;
          let data;
          if (value) {
            try {
              data = JSON.parse(value);
              renderSelector(data);
            } catch (err) {
              console.error(options, err)
            }
          }
        }
      });
    }
  },

  onViewInit() {
    const evn = "change:multi change:key change:options change:tags change:dark change:onChangeEvent"
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
