export default function (editor) {
  const getRotation = (transform = '') => {
    const transArray = transform.trim().split(' ');
    const rotation = _.get(transArray.filter(trans => _.startsWith(trans, 'rotate')), '[0]', '');

    if (!rotation) {
      return 0
    }
    return parseInt(rotation.split('rotate(')[1]);
  }
  editor.TraitManager.addType('basic-traits-rotation', {
    noLabel: true,

    // Return a simple HTML string or an HTML element
    createInput({ component, trait }) {
      // Here we can decide to use properties from the trait
      const { transform = '' } = component.getStyle();
      const rotation = transform ? getRotation(transform) : 0;

      // Create a new element container add some content
      const traitEl = document.createElement('div');
      traitEl.innerHTML = `
        <div class="basic-traits-position">
          <label class="basic-traits-size-label">旋转角度</label>
          <input type="number" id="basic-trait-rotation" class="basic-traits-rotation" value=${rotation} />
        </div>
      `;
      return traitEl;
    },

    // Update the component based element changes
    onEvent({ elInput, component }) {
      const rotation = elInput.querySelector('#basic-trait-rotation').value;
      const oldStyle = component.getStyle() || {};
      const transform = oldStyle.transform || '';
      component.setStyle({
        ...oldStyle,
        transform: `${transform.replace(/rotate\(.*\)/ig, '')} rotate(${rotation}deg)`
      });
      component.em.handleUpdates.call(component.em);
    },

    onUpdate({ elInput, component }) {
      const { transform = '' } = component.getStyle();
      const rotation = transform ? getRotation(transform) : 0;

      const $rotation = elInput.querySelector('#basic-trait-rotation');

      $rotation.value = parseInt(rotation);

      $rotation.dispatchEvent(new CustomEvent('change:basic-trait:rotation'));
    },
  });
}
