<template>
  <div>
    <el-date-picker
      ref="datePicker"
      v-model="value"
      v-bind="trimAttrs($attrs)"
      :arrow-control="hasArrowsInPanel"
      :align="datePickerTextAlign"
      :picker-options="datePickerOptions"
      :unlink-panels="!isPanelsLinked"
      @focus="$emit('focus')"
      @blur="$emit('blur')"
    >
      <slot />
    </el-date-picker>
  </div>
</template>

<script>
import { DatePicker } from 'element-ui';
export default {
  name: 'JskDatePicker',
  components: {
    ElDatePicker: DatePicker
  },
  inheritAttrs: false,
  model: {
    prop: 'vModel',
    event: 'change'
  },
  props: {
    vModel: [Date, String, Array],
    datePickerOptions: {
      type: Object
    },
    hasArrowsInPanel: {
      type: Boolean,
      default: false
    },
    datePickerTextAlign: {
      type: String,
      default: 'left'
    },
    isPanelsLinked: {
      type: Boolean,
      default: true
    }
  },
  data: function() {
    return {
      value: ''
    };
  },
  watch: {
    value: function(newValue, oldValue) {
      this.$emit('change', newValue);
      if (this.isValueEmpty(newValue) && !this.isValueEmpty(oldValue)) {
        this.$emit('clear');
      }
      this.$nextTick(() => {
        if (this.value !== this.vModel) {
          this.value = this.vModel;
        }
      });
    },
    vModel: function() {
      this.value = this.vModel;
    }
  },
  created: function() {
    this.value = this.vModel;
  },
  methods: {
    trimAttrs: function(attrs) {
      Object.keys(attrs).forEach((key) => {
        let prefixes = ['is-', 'has-', 'date-picker-'];
        prefixes.forEach((prefix) => {
          if (key.substr(0, prefix.length) === prefix) {
            attrs[key.substr(prefix.length)] = attrs[key];
          }
        })
      })
      return attrs;
    },
    focus: function() {
      this.$refs.datePicker.focus();
    },
    isValueEmpty: function(value) {
      return value == null || value === '' || (Array.isArray(value) && value.length === 0);
    }
  }
}
</script>
<style lang="scss" src="../../theme/date-picker.scss"></style>
