export default function (editor) {
  editor.TraitManager.addType('basic-traits-position', {
    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 $el = component.getEl();
      const { left = 0, top = 0 } = $el ? $el.getBoundingClientRect() : {};

      // 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>
          <div class="basic-traits-pair"><input type="number" min="0" step="1" id="basic-trait-left" class="basic-traits-size-left" value="${left}" />px</div>
          <div class="basic-traits-pair"><input type="number" min="0" step="1" id="basic-trait-top" class="basic-traits-size-top" value="${top}" />px</div>
        </div>
      `;
      return traitEl;
    },

    // Update the component based element changes
    onEvent({ elInput, component }) {
      const left = elInput.querySelector('#basic-trait-left').value;
      const top = elInput.querySelector('#basic-trait-top').value;
      const oldStyle = component.getStyle() || {};
      if (!oldStyle.width || !oldStyle.height) {
        const { width = 0, height = 0 } = component.getEl().getBoundingClientRect();
        oldStyle.width = Math.ceil(width);
        oldStyle.height = Math.ceil(height);
      }
      component.setStyle({ ...oldStyle, position: 'absolute', left: `${parseInt(left)}px`, top: `${parseInt(top)}px` });
      component.em.handleUpdates.call(component.em);
    },

    onUpdate({ elInput, component }) {
      const $el = component.getEl();
      const { left = 0, top = 0 } = $el ? $el.getBoundingClientRect() : {};

      const $leftEl = elInput.querySelector('#basic-trait-left');
      const $topEl = elInput.querySelector('#basic-trait-top');

      $leftEl.value = parseInt(left);
      $topEl.value = parseInt(top);

      $leftEl.dispatchEvent(new CustomEvent('change:basic-trait:left'));
      $topEl.dispatchEvent(new CustomEvent('change:basic-trait:top'));
    },
  });
}
