import { mdcCheckboxGroup, mdcCheckbox, CATEGORIES } from '../../configuration/constants'

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

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${mdcCheckboxGroup}" class="${mdcCheckboxGroup}">
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
      .${mdcCheckboxGroup} {
        width: 450px;
        padding: 10px;
        display: flex;
        flex-wrap: wrap;
        align-items: flex-start;
      }
      .${mdcCheckboxGroup} > .mdc-form-field {
        flex-grow: 1;
        flex-shrink: 1;
        flex-basis: auto;
        font-size: inherit;
        color: currentColor;
      }
      .${mdcCheckboxGroup} > .mdc-form-field > label {
        margin-bottom: 0!important;
      }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `多选`,
      attributes: {class:'fa fa-check-circle'},
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '多选',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/dbefa1d2-b7b4-4706-8ae5-45c122561dd2?# 《多选》',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      outPorts: [
        {
          uuid: 'out1',
          subType: 'all',
          description: {
            zh_CN: '输出1'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: mdcCheckboxGroup,
      resizable: true,
      highlightable: false,
      droppable: false,
      isFormItem: true,
      traits: [{
        name: 'columns',
        label: '列数',
        changeProp: 1,
        type: 'number',
        min: 1,
        step: 1
      }, {
        name: 'borderColor',
        label: '默认颜色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'selectedColor',
        label: '选中颜色',
        changeProp: 1,
        type: 'color'
      }, {
        name: 'initChecked',
        label: '默认选中项Id',
        changeProp: 1
      }],
      'columns': 3,
      'initChecked': null
    }
  },

  onModelScript() {
    const columns = Number('{[ columns ]}');
    let initChecked = '{[ initChecked ]}';
    const borderColor = '{[ borderColor ]}';
    const selectedColor = '{[ selectedColor ]}';
    
    const self = this;
    const eventName = `call-` + self.getAttribute('id');

    const width = Math.floor(100 / columns) + '%';
    $(self).children('.mdc-form-field').css({'flex-basis': width});

    if (initChecked.indexOf(',') > 0) {
      initChecked = initChecked.split(',').forEach(function(item) { return item.trim(); })
    } else if (Boolean(initChecked)) {
      initChecked = [initChecked];
    }

    const sendOut = function() {
      const $checked = $(self).find('input[type=checkbox]:checked');
      if ($checked) {
        const checkedArr = [];
        $checked.each(function(i, e) {
          checkedArr.push($(e).val())
        });
        window.spSocket.send({
          eventName: eventName,
          data: {
            success: true,
            out1: JSON.stringify(checkedArr)
          }
        });
      }
    };
    
    let timer = null;
    const onMounted = function() {
      const mounted = $(self).find('input[type=checkbox]').attr('name');
      if (mounted) {
        if (borderColor || selectedColor) {
          let style = $('style#mdc-checkbox');
          if (style) {
            $(style).remove();
          }
          style = document.createElement('style'); 
          style.id = 'mdc-checkbox'; 
          style.type = 'text/css'; 
          const notChecked = borderColor ? `
            .mdc-checkbox__native-control:enabled:not(:checked):not(:indeterminate) ~ .mdc-checkbox__background { border-color: ${borderColor} }
          ` : ''; 
          const checked = selectedColor ? `
            .mdc-checkbox__native-control:enabled:checked ~ .mdc-checkbox__background, .mdc-checkbox__native-control:enabled:indeterminate ~ .mdc-checkbox__background { border-color: ${selectedColor}; background-color: ${selectedColor} }
          ` : ''; 
          style.innerHTML = `${notChecked} ${checked}`; 
          document.getElementsByTagName('HEAD').item(0).append(style); 
        }
        if (Boolean(initChecked)) {
          initChecked.forEach(function(item){
            const $checkedBox = $(self).find('input[value=' + initChecked + ']');
            $checkedBox.attr({checked: true});
          });
          if (!($(self).parent().attr('class') && $(self).parent().attr('class').indexOf('form-panel') > -1) && window.spSocket ) {
            sendOut();
          }
        } else {
          $(self).find('input[type=checkbox]').attr('checked', false);
        }
        if(timer) {
          clearTimeout(timer);
          timer = null;
        }
      } else {
        timer = setTimeout(onMounted, 300);
      }
    }
    onMounted();

    if (!($(self).parent().attr('class') && $(self).parent().attr('class').indexOf('form-panel') > -1) && window.spSocket ) {
      $(self).on("change", "input[type=checkbox]", function(event) {
        sendOut()
      })
    }
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="mdc-form-field" data-gjs-type="${mdcCheckbox}">
        </div>
        <div class="mdc-form-field" data-gjs-type="${mdcCheckbox}">
        </div>
        <div class="mdc-form-field" data-gjs-type="${mdcCheckbox}">
        </div>
      `)
    }
    const evn = "change:columns change:initChecked change:selectedColor change:borderColor";
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
