import { mdcCheckbox } from '../../configuration/constants'

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

  // 前面板html模板
  viewTemplate() {
    return `
      <div class="mdc-form-field" data-gjs-type="${mdcCheckbox}">
      </div>
    `
  },

  // 组件属性
  componentOptions() {
    return {
      name: mdcCheckbox,
      resizable: false,
      childrenSelectable: false,
      droppable: false,
      draggable: false,
      traits: [{
        name: 'checkboxName',
        label: 'Name',
        changeProp: 1
      }, {
        name: 'checkboxValue',
        label: 'Value',
        changeProp: 1
      }, {
        name: 'checkboxText',
        label: '文本',
        changeProp: 1
      }],
      'checkboxName': 'checkboxes',
      'checkboxValue': 'checkbox-1',
      'checkboxText': '多选 1'
    }
  },

  onModelScript() {
    const checkboxName = ('{[ checkboxName ]}').toString();
    const checkboxValue = ('{[ checkboxValue ]}').toString();
    const checkboxText = ('{[ checkboxText ]}').toString();

    const self = this;
    const $label = $(self).children('[data-gjs-type=label]').length ? $(self).children('[data-gjs-type=label]') : $(self).children('label');

    $(self).find('input[type=checkbox]').attr({id: `${checkboxName}-${checkboxValue}`, name: checkboxName, value: checkboxValue});
    $label.attr('for', `${checkboxName}-${checkboxValue}`).text(checkboxText);

    !!mdc && mdc.checkbox.MDCCheckbox.attachTo(self.querySelector('.mdc-checkbox'));
    !!mdc && mdc.formField.MDCFormField.attachTo(self);
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="mdc-checkbox">
          <input type="checkbox"
                class="mdc-checkbox__native-control"
                name="" />
          <div class="mdc-checkbox__background">
            <svg class="mdc-checkbox__checkmark"
                viewBox="0 0 24 24">
              <path class="mdc-checkbox__checkmark-path"
                    fill="none"
                    d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
            </svg>
            <div class="mdc-checkbox__mixedmark"></div>
          </div>
          <div class="mdc-checkbox__ripple"></div>
        </div>
        <label></label>
      `)
    }
    const evn = "change:checkboxName change:checkboxValue change:checkboxText"
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
