<template>
  <div
    class="el-slider"
    :class="{ 'is-vertical': vertical, 'el-slider--with-input': showInput, 'is-horizental': !vertical }"
    role="slider"
    :aria-valuemin="min"
    :aria-valuemax="max"
    :aria-orientation="vertical ? 'vertical': 'horizontal'"
    :aria-disabled="sliderDisabled"
    @mouseenter="enterSlider"
    @mouseleave="leaveSlider"
  >
    <div class="el-slider-left-content">
      <div class="input-left" v-if="rangeInput">
        <el-input-number
          v-model="firstValue"
          ref="input"
          style="width:88px"
          @change="emitChange(firstValue, 'left')"
          :step="step"
          :disabled="sliderDisabled"
          :controls="showInputControls"
          controls-position="right"
          :min="min"
          :max="max"
          :debounce="debounce"
          :size="inputSize">
        </el-input-number>
      </div>
    </div>
    
    <div
      class="el-slider__runway"
      :class="{ 'show-input': showInput, 'disabled': sliderDisabled }"
      :style="runwayStyle"
      @click="onSliderClick"
      ref="slider">
      <span v-if="showBoundary" class="el-slider-range min-range">{{min}}</span>
      <span v-if="showBoundary" class="el-slider-range max-range">{{max}}</span>
      <div
        class="el-slider__bar"
        :style="barStyle">
      </div>
      <slider-button
        :vertical="vertical"
        :allwaysTooltip="allwaysTooltip"
        v-model="firstValue"
        :tooltip-class="tooltipClass"
        ref="button1">
      </slider-button>
      <slider-button
        :vertical="vertical"
        :allwaysTooltip="allwaysTooltip"
        v-model="secondValue"
        :tooltip-class="tooltipClass"
        ref="button2"
        v-if="range">
      </slider-button>
      <template v-if="showStops">
        <div
          class="el-slider__stop"
          v-for="(item, key) in stops"
          :key="key"
          :style="getStopStyle(item, 'stops')"
        />
      </template>
      <template v-if="markList.length > 0">
        <div>
          <div
            v-for="(item, key) in markList"
            :style="getStopStyle(item.position, 'mark-stop')"
            class="el-slider__stop el-slider__marks-stop"
            :key="key">
          </div>
        </div>
        <div class="el-slider__marks">
          <slider-marker
            :mark="item.mark" v-for="(item, key) in markList"
            :key="key"
            :style="getStopStyle(item.position)">
          </slider-marker>
        </div>
      </template>
    </div>
    <div class="el-slider-right-content">
      <div class="el-slider--range-input">
        <el-input-number
          v-if="showInput && !rangeInput"
          v-model="firstValue"
          style="width:88px; margin-left: 8px;"
          ref="input"
          @change="emitChange(firstValue, 'left')"
          :step="step"
          :disabled="sliderDisabled"
          :controls="showInputControls"
          controls-position="right"
          :min="min"
          :max="max"
          :debounce="debounce"
          :size="inputSize">
        </el-input-number>
        <span v-if="range && showInput" class="split-line"> - </span>
        <el-input-number
          v-if="(range && showInput) || rangeInput"
          v-model="secondValue"
          style="width:88px; margin-left: 8px;"
          ref="input"
          @change="emitChange(secondValue, 'right')"
          :step="step"
          :disabled="sliderDisabled"
          :controls="showInputControls"
          controls-position="right"
          :min="min"
          :max="max"
          :debounce="debounce"
          :size="inputSize">
        </el-input-number>
      </div>
    </div>
  </div>
</template>

<script type="text/babel">
  import ElInputNumber from 'modesign-ui/packages/input-number';
  import ElInput from 'modesign-ui/packages/input'
  import SliderButton from './button.vue';
  import SliderMarker from './marker';
  import Emitter from 'modesign-ui/src/mixins/emitter';

  export default {
    name: 'ElSlider',

    mixins: [Emitter],

    inject: {
      elForm: {
        default: ''
      }
    },

    props: {
      min: {
        type: Number,
        default: 0
      },
      max: {
        type: Number,
        default: 100
      },
      step: {
        type: Number,
        default: 1
      },
      value: {
        type: [Number, Array],
        default: 0
      },
      showInput: {
        type: Boolean,
        default: false
      },
      showInputControls: {
        type: Boolean,
        default: true
      },
      inputSize: {
        type: String,
        default: 'medium'
      },
      showStops: {
        type: Boolean,
        default: false
      },
      showTooltip: {
        type: Boolean,
        default: true
      },
      formatTooltip: Function,
      disabled: {
        type: Boolean,
        default: false
      },
      range: {
        type: Boolean,
        default: false
      },
      vertical: {
        type: Boolean,
        default: false
      },
      height: {
        type: String
      },
      debounce: {
        type: Number,
        default: 300
      },
      label: {
        type: String
      },
      tooltipClass: String,
      marks: Object,
      rangeInput: {
        type: Boolean,
        default: false
      },
      showBoundary: {
        type: Boolean,
        default: false
      },
      allwaysTooltip: {
        type: Boolean,
        default: false
      },
      ignoreStep: {
        type: Boolean,
        default: false
      },
      // 区间配置
      intervalConfig:{
        type: Array,
        default: ()=>{
          return []
        }
      }
    },

    components: {
      ElInputNumber,
      SliderButton,
      SliderMarker
    },

    data() {
      return {
        firstValue: null,
        secondValue: null,
        oldValue: null,
        dragging: false,
        sliderSize: 1,
        isEnter: false
      };
    },

    watch: {
      value(val, oldVal) {
        if (this.dragging ||
          Array.isArray(val) &&
          Array.isArray(oldVal) &&
          val.every((item, index) => item === oldVal[index])) {
          return;
        }
        this.setValues();
      },

      dragging(val) {
        if (!val) {
          this.setValues();
        }
      },

      firstValue(val) {
        if (this.range) {
          this.$emit('input', [this.minValue, this.maxValue]);
        } else {
          this.$emit('input', val);
        }
      },

      secondValue() {
        if (this.range) {
          this.$emit('input', [this.minValue, this.maxValue]);
        }
      },

      min() {
        this.setValues();
      },

      max() {
        this.setValues();
      }
    },

    methods: {
      valueChanged() {
        if (this.range) {
          return ![this.minValue, this.maxValue]
            .every((item, index) => item === this.oldValue[index]);
        } else {
          return this.value !== this.oldValue;
        }
      },
      setValues() {
        if (this.min > this.max) {
          console.error('[Element Error][Slider]min should not be greater than max.');
          return;
        }
        const val = this.value;
        if (this.range && Array.isArray(val)) {
          if (val[1] < this.min) {
            this.$emit('input', [this.min, this.min]);
          } else if (val[0] > this.max) {
            this.$emit('input', [this.max, this.max]);
          } else if (val[0] < this.min) {
            this.$emit('input', [this.min, val[1]]);
          } else if (val[1] > this.max) {
            this.$emit('input', [val[0], this.max]);
          } else {
            this.firstValue = val[0];
            this.secondValue = val[1];
            if (this.valueChanged()) {
              this.dispatch('ElFormItem', 'el.form.change', [this.minValue, this.maxValue]);
              this.oldValue = val.slice();
            }
          }
        } else if (!this.range && typeof val === 'number' && !isNaN(val)) {
          if (val < this.min) {
            this.$emit('input', this.min);
          } else if (val > this.max) {
            this.$emit('input', this.max);
          } else {
            this.firstValue = val;
            if (this.valueChanged()) {
              this.dispatch('ElFormItem', 'el.form.change', val);
              this.oldValue = val;
            }
          }
        }
      },

      setPosition(percent) {
        // if(typeof percent !== 'number' || !isNaN(percent) || !percent) percent = 0
        const targetValue = this.min + percent * (this.max - this.min) / 100;
        if (!this.range) {
          this.$refs.button1.setPosition(percent);
          return;
        }
        let button;
        if (Math.abs(this.minValue - targetValue) < Math.abs(this.maxValue - targetValue)) {
          button = this.firstValue < this.secondValue ? 'button1' : 'button2';
        } else {
          button = this.firstValue > this.secondValue ? 'button1' : 'button2';
        }
        this.$refs[button].setPosition(percent);
      },

      onSliderClick(event) {
        if (this.sliderDisabled || this.dragging) return;
        this.resetSize();
        if (this.vertical) {
          const sliderOffsetBottom = this.$refs.slider.getBoundingClientRect().bottom;
          this.setPosition((sliderOffsetBottom - event.clientY) / this.sliderSize * 100);
        } else {
          const sliderOffsetLeft = this.$refs.slider.getBoundingClientRect().left;
          this.setPosition((event.clientX - sliderOffsetLeft) / this.sliderSize * 100);
        }
        this.emitChange();
      },

      resetSize() {
        if (this.$refs.slider) {
          this.sliderSize = this.$refs.slider[`client${ this.vertical ? 'Height' : 'Width' }`];
        }
      },

      emitChange(val, type) {
        if(val !== undefined || val !== null || val !== '') {
          if(!this.range) this.setPosition(val)
          if (this.range && this.firstValue > this.secondValue && type === 'left'){
            let range = [this.secondValue, this.firstValue]
            this.firstValue = null
            this.secondValue = null
            this.$nextTick(()=>{
              this.firstValue = range[0]
              this.secondValue = range[0]
            })
          } else if (this.range && this.firstValue > this.secondValue && type === 'right'){
            let range = [this.secondValue, this.firstValue]
            this.firstValue = null
            this.secondValue = null
            this.$nextTick(()=>{
              this.firstValue = range[1]
              this.secondValue = range[1]
            })
          }
          this.$nextTick(() => {
            // this.$emit('change', this.range ? [this.minValue, this.maxValue] : this.value);
            this.$emit('change', this.range ? [this.minValue, this.maxValue] : val);
          });
        }
      },

      getStopStyle(position, value) {
        const barSize = this.range ? 100 * (this.maxValue - this.minValue) / (this.max - this.min) : 100 * (this.firstValue - this.min) / (this.max - this.min)
        const barStart = this.range ? 100 * (this.minValue - this.min) / (this.max - this.min) : 0
        if (value === 'stops') {
          if (this.range) {
            if ((position > barStart) && (position < barSize + barStart)) {
              return this.vertical ? { 'bottom': position + '%', 'backgroundColor': '#165DFF' } : { 'left': position + '%', 'backgroundColor': '#165DFF' };
            }
          } else {
            if (position < barSize) {
              return this.vertical ? { 'bottom': position + '%', 'backgroundColor': '#165DFF' } : { 'left': position + '%', 'backgroundColor': '#165DFF' };
            }
          }
        }
        if (value === 'mark-stop') {
          if (this.range) {
            if ((position > barStart) && (position < barSize + barStart) && (!this.disabled)) {
              return this.vertical ? { 'bottom': position + '%', 'borderColor': '#165DFF' } : { 'left': position + '%', 'borderColor': '#165DFF' };
            }else if ((position <= barStart) && (position > barSize + barStart) && (!this.disabled)){
              return this.vertical ? { 'bottom': position + '%', 'borderColor': '#94BFFF' } : { 'left': position + '%', 'borderColor': '#94BFFF' };
            }
          } else {
            if ((position < barSize) && !this.disabled){
              return this.vertical ? { 'bottom': position + '%', 'borderColor': '#165DFF' } : { 'left': position + '%', 'borderColor': '#165DFF' };
            }else if (position <= barSize && this.disabled) {
              return this.vertical ? { 'bottom': position + '%', 'borderColor': '#94BFFF' } : { 'left': position + '%', 'borderColor': '#94BFFF' };
            }
          }
        }
        return this.vertical ? { 'bottom': position + '%' } : { 'left': position + '%' };
      },

      enterSlider() {
        this.isEnter = true;
      },
      leaveSlider() {
        this.isEnter = false;
      }
    },

    computed: {
      stops() {
        const result = [];
        // 如果有区间配置，则单独使用每个区间配置里面的step，不使用props的step
        // 如果没有区间配置，则使用props的step
        if(this.intervalConfig.length == 0){
          if (!this.showStops || this.min > this.max) return [];
          if (this.step === 0) {
            process.env.NODE_ENV !== 'production' &&
            console.warn('[Element Warn][Slider]step should not be 0.');
            return [];
          }
          // const stopCount = (this.max - this.min) / this.step;
          // const stepWidth = 100 * this.step / (this.max - this.min);
          const stopCount = (this.max ) / this.step;
          const stepWidth = 100 * this.step / this.max
          for (let i = 1; i < stopCount; i++) {
            result.push(i * stepWidth);
          }
          // if (this.range) {
          //   return result.filter(step => {
          //     return step < 100 * (this.minValue - this.min) / (this.max - this.min) ||
          //       step > 100 * (this.maxValue - this.min) / (this.max - this.min);
          //   });
          // } else {
          //   return result.filter(step => step > 100 * (this.firstValue - this.min) / (this.max - this.min));
          // }
        }else{
          if (!this.showStops) return [];
          this.intervalConfig.forEach(item=>{
            const {step, min, max} = item;
            const count = Math.floor((max - min) / step);
            for (let i = 1; i < count; i++) {
              const stepVal = i * step + min;
              if (stepVal <= this.min || stepVal >= this.max) continue;
              result.push(stepVal);
            }
          })
        }
        
        return result
      },

      markList() {
        if (!this.marks) {
          return [];
        }

        const marksKeys = Object.keys(this.marks);
        return marksKeys.map(parseFloat)
          .sort((a, b) => a - b)
          .filter(point => point <= this.max && point >= this.min)
          .map(point => ({
            point,
            position: (point - this.min) * 100 / (this.max - this.min),
            mark: this.marks[point]
          }));
      },

      minValue() {
        if(isNaN(this.firstValue)) {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.firstValue = 0
        }
        return Math.min(this.firstValue, this.secondValue);
      },

      maxValue() {
        if(isNaN(this.secondValue)) {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.secondValue = this.firstValue
        }
        return Math.max(this.firstValue, this.secondValue);
      },

      barSize() {
        return this.range
          ? `${ 100 * (this.maxValue - this.minValue) / (this.max - this.min) }%`
          : `${ 100 * (this.firstValue - this.min) / (this.max - this.min) }%`;
      },

      barStart() {
        return this.range
          ? `${ 100 * (this.minValue - this.min) / (this.max - this.min) }%`
          : '0%';
      },

      precision() {
        let precisions = [this.min, this.max, this.step].map(item => {
          let decimal = ('' + item).split('.')[1];
          return decimal ? decimal.length : 0;
        });
        return Math.max.apply(null, precisions);
      },

      runwayStyle() {
        let style = {}
        if (this.vertical) {
          style.height = this.height
        }
        // if (this.range && this.showInput) {
        //   style.marginRight = '8px'
        // }
        // if (this.range && !this.showInput) {
        //   style.marginLeft = '160px'
        // }
        return style
        // return this.vertical ? { height: this.height } : {};
      },

      barStyle() {
        return this.vertical
          ? {
            height: this.barSize,
            bottom: this.barStart
          } : {
            width: this.barSize,
            left: this.barStart
          };
      },

      sliderDisabled() {
        return this.disabled || (this.elForm || {}).disabled || (this.elForm || {}).readable;
      }
    },

    mounted() {
      let valuetext;
      if (this.range) {
        if (Array.isArray(this.value)) {
          this.firstValue = Math.max(this.min, this.value[0]);
          this.secondValue = Math.min(this.max, this.value[1]);
        } else {
          this.firstValue = this.min;
          this.secondValue = this.max;
        }
        this.oldValue = [this.firstValue, this.secondValue];
        valuetext = `${this.firstValue}-${this.secondValue}`;
      } else {
        if (typeof this.value !== 'number' || isNaN(this.value)) {
          this.firstValue = this.min;
        } else {
          this.firstValue = Math.min(this.max, Math.max(this.min, this.value));
        }
        this.oldValue = this.firstValue;
        valuetext = this.firstValue;
      }
      this.$el.setAttribute('aria-valuetext', valuetext);

      // label screen reader
      this.$el.setAttribute('aria-label', this.label ? this.label : `slider between ${this.min} and ${this.max}`);

      this.resetSize();
      window.addEventListener('resize', this.resetSize);
    },

    beforeDestroy() {
      window.removeEventListener('resize', this.resetSize);
    }
  };
</script>
