<template>
  <div class="mx-date-picker">
    <el-date-picker
      ref="startPicker"
      v-model="start"
      :size="size"
      :placeholder="startPlaceholder"
      :value-format="valueFormat"
      :picker-options="startOptions"
      :type="intelligentType"
      :style="{ width: intelligentWidth + 'px' }"
      @change="dateChange"
    ></el-date-picker>
    <span style="margin: 0 10px">{{ rangeSeparator }}</span>
    <el-date-picker
      ref="endPicker"
      v-model="end"
      :size="size"
      :placeholder="endPlaceholder"
      :value-format="valueFormat"
      :picker-options="endOptions"
      :type="intelligentType"
      :style="{ width: intelligentWidth + 'px' }"
      @change="dateChange"
    ></el-date-picker>
  </div>
</template>
<script>
export default {
  model: {
    prop: 'timeRange',
    event: 'change'
  },
  props: {
    timeRange: {
      type: Array,
      default: () => []
    },
    startPlaceholder: {
      type: String,
      default: ''
    },
    endPlaceholder: {
      type: String,
      default: ''
    },
    rangeSeparator: {
      type: String,
      default: '-'
    },
    valueFormat: {
      type: String,
      default: 'yyyy-MM-dd'
    },
    size: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'date'
    },
    emitAllChanges: {
      // TODO: hht 22.1.26 是否外抛所有变化，因为原来不外抛，现在需要，防止有不好的影响，所以加了这个属性控制
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      start: '',
      end: ''
    }
  },
  watch: {
    'timeRange': {
      immediate: true,
      handler: function(range) {
        if (range?.length > 0) this.start = range[0]
        if (range?.length > 1) this.end = range[1]
      }
    }
  },
  computed: {
    intelligentType() {
      return this.type.replace('range', '')
    },
    intelligentWidth() {
      return this.type.startsWith('datetime') ? 180 : 150
    },
    startOptions() {
      return {
        disabledDate: (time) => {
          if (!this.end) return false
          let formatDate = this.$refs.startPicker.formatToValue(time)
          formatDate = formatDate.split(' ')[0]
          let endDate = this.end.split(' ')[0]
          return formatDate > endDate
        }
      }
    },
    endOptions() {
      return {
        disabledDate: (time) => {
          if (!this.start) return false
          let formatDate = this.$refs.endPicker.formatToValue(time)
          formatDate = formatDate.split(' ')[0]
          let startDate = this.start.split(' ')[0]
          return formatDate < startDate
        }
      }
    }
  },
  methods: {
    dateChange() {
      if (this.start && this.end) {
        this.$emit('change', [this.start, this.end])
      } else if (!this.start && !this.end) {
        this.$emit('change', [])
      } else if (this.emitAllChanges) {
        this.$emit('change', [this.start, this.end])
      }
    }
  }
}
</script>
<style scoped>
</style>
