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

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

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

  // 组件属性
  componentOptions() {
    return {
      name: mdcRadio,
      resizable: false,
      childrenSelectable: false,
      droppable: false,
      draggable: false,
      traits: [{
        name: 'radioName',
        label: 'Name',
        changeProp: 1
      }, {
        name: 'radioValue',
        label: 'Value',
        changeProp: 1
      }, {
        name: 'radioText',
        label: '文本',
        changeProp: 1
      }],
      'radioName': 'radios',
      'radioValue': 'radio-1',
      'radioText': '单选 1'
    }
  },

  onModelScript() {
    const radioName = ('{[ radioName ]}').toString();
    const radioValue = ('{[ radioValue ]}').toString();
    const radioText = ('{[ radioText ]}').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=radio]').attr({id: `${radioName}-${radioValue}`, name: radioName, value: radioValue});
    $label.attr('for', `${radioName}-${radioValue}`).text(radioText);

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

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="mdc-radio">
          <input class="mdc-radio__native-control" type="radio" name="">
          <div class="mdc-radio__background">
            <div class="mdc-radio__outer-circle"></div>
            <div class="mdc-radio__inner-circle"></div>
          </div>
          <div class="mdc-radio__ripple"></div>
        </div>
        <label> </label>
      `)
    }
    const evn = "change:radioName change:radioValue change:radioText"
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
