import $ from 'jquery';
import Vue from 'vue';
import VueSlider from 'vue-slider-component';

const Slider = Vue.extend(VueSlider);
export default function (editor) {
  editor.TraitManager.addType('basic-traits-opacity', {
    noLabel: true,

    // Return a simple HTML string or an HTML element
    createInput({ component, trait }) {
      const { opacity = 0 } = component.getStyle('opacity');
      const $sliderContainer = $('<div class="basic-traits-opacity"><label class="basic-traits-opacity-label">透明度</label></div>');
      const $slider = $('<div class="slider"></div>');

      // 滑动事件
      const $sliderInst = new Slider({ propsData: { min: 0, max: 1, interval: 0.1 } }).$mount();
      $sliderInst.setValue(opacity);
      $sliderInst.$on('change', ev => this.onChange(ev));

      // 输入框输入事件
      const $sliderInput = $(`<input type="number" step="0.1" min="0" max="1" class="slider-input" value=${opacity}>`);
      $sliderInput.on('change', ev => {
        $sliderInst.setValue($sliderInput.val());
      });

      this.$sliderInst = $sliderInst;
      this.$sliderInput = $sliderInput;

      $slider.append($sliderInst.$el);
      $sliderContainer.append($slider).append(this.$sliderInput);

      return $sliderContainer[0];
    },

    // Update the component based element changes
    onEvent({ component }) {
      const opacity = this.$sliderInst.getValue() || 0;
      this.$sliderInput.val(opacity);
      const oldStyle = component.getStyle() || {};
      component.addStyle({
        ...oldStyle,
        opacity
      });

      component.em.handleUpdates.call(component.em);
    },

    onUpdate({ component }) {
      const { opacity = 1 } = component.getStyle();
      this.$sliderInst.setValue(opacity);
      this.$sliderInput.val(opacity);
    }
  });
}
