<template>
  <div class="ele-color-hue-slider">
    <div
      ref="bar"
      class="ele-color-hue-slider-bar"
      @click="handleClick">
    </div>
    <div
      ref="thumb"
      class="ele-color-hue-slider-thumb"
      :style="{left: thumbLeft + 'px'}">
    </div>
  </div>
</template>

<script>
import draggable from '../draggable';

export default {
  name: 'EleHueSlider',
  emits: ['update:hue'],
  props: {
    // 选中的色相
    hue: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      // 滑块位置
      thumbLeft: 0
    };
  },
  mounted() {
    // 获取滑块的默认位置
    this.thumbLeft = this.getThumbLeft();
    // 滑块、滑轨绑定鼠标移动事件
    const {bar, thumb} = this.$refs;
    const dragConfig = {
      drag: (event) => {
        this.handleDrag(event);
      },
      end: (event) => {
        this.handleDrag(event);
      }
    };
    draggable(bar, dragConfig);
    draggable(thumb, dragConfig);
  },
  methods: {
    /* 滑轨点击事件 */
    handleClick(event) {
      if (event.target !== this.$refs.thumb) {
        this.handleDrag(event);
      }
    },
    /* 颜色选中改变事件 */
    handleDrag(event) {
      const el = this.$el,
        thumb = this.$refs.thumb,
        rect = el.getBoundingClientRect();
      let left = event.clientX - rect.left;
      left = Math.min(left, rect.width - thumb.offsetWidth / 2);
      left = Math.max(thumb.offsetWidth / 2, left);
      const hue = Math.round((left - thumb.offsetWidth / 2) / (rect.width - thumb.offsetWidth) * 360);
      this.$emit('update:hue', hue);
    },
    /* 计算滑块位置 */
    getThumbLeft() {
      const el = this.$el,
        thumb = this.$refs.thumb;
      return Math.round(this.hue * (el.offsetWidth - thumb.offsetWidth / 2) / 360);
    }
  },
  watch: {
    hue() {
      this.thumbLeft = this.getThumbLeft();
    }
  }
};
</script>

<style>
.ele-color-picker .ele-color-hue-slider {
  height: 12px;
  padding: 0 2px;
  margin-top: 12px;
  position: relative;
  box-sizing: border-box;
  background-color: #f00;
}

.ele-color-picker .ele-color-hue-slider .ele-color-hue-slider-bar {
  height: 100%;
  background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);
  position: relative;
}

.ele-color-picker .ele-color-hue-slider .ele-color-hue-slider-thumb {
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: #fff;
  box-sizing: border-box;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.6);
  border: 1px solid #f0f0f0;
  border-radius: 1px;
  cursor: pointer;
  z-index: 1;
}
</style>
