<template>
  <div style="display: flex;align-items: center;">
    <a-date-picker
      :size="size"
      v-model="startValue"
      :disabled-date="disabledStartDate"
      :show-time="false"
      format="YYYY-MM-DD"
      placeholder="开始时间"
      @openChange="handleStartOpenChange"
    />
    <span>&nbsp;&nbsp;至&nbsp;&nbsp;</span>
    <a-date-picker
      :size="size"
      v-model="endValue"
      :disabled-date="disabledEndDate"
      :show-time="false"
      format="YYYY-MM-DD"
      placeholder="结束时间"
      :open="endOpen"
      @openChange="handleEndOpenChange"
    />
  </div>
</template>
<script>
import moment from 'moment'
export default {
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    size: {
      type: String,
      default: 'default'
    },
    showTime: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      startValue: this.value[0],
      endValue: this.value[1],
      endOpen: false
    }
  },
  watch: {
    startValue (val) {
      this.changeInput()
    },
    endValue (val) {
      this.changeInput()
    }
  },
  methods: {
    disabledStartDate (startValue) {
      const endValue = this.endValue
      const oMinYearVs = moment(endValue, 'YYYY-MM-DD').subtract(1, 'years')
      const maxYearVs = moment().endOf('day') //  今天，包含今天
      if (endValue) {
        return startValue.valueOf() < oMinYearVs.valueOf() || startValue.valueOf() > maxYearVs.valueOf()
      } else {
        return startValue.valueOf() > maxYearVs.valueOf()
      }
    },
    disabledEndDate (endValue) {
      const maxYearVs = moment().endOf('day') //  今天，包含今天
      return endValue && endValue.valueOf() > maxYearVs.valueOf()
    },
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    changeInput () {
      const startValue = this.startValue
      const endValue = this.endValue
      console.log(startValue, endValue)
      let dateStrings = [startValue, endValue]
      if (!dateStrings[0] || !dateStrings[1]) {
        dateStrings = []
      } else {
        if (this.showTime) {
          dateStrings[0] = moment(dateStrings[0]).format('YYYY-MM-DD 00:00:00')
          dateStrings[1] = moment(dateStrings[1]).format('YYYY-MM-DD 23:59:59')
        } else {
          dateStrings[0] = moment(dateStrings[0]).format('YYYY-MM-DD')
          dateStrings[1] = moment(dateStrings[1]).format('YYYY-MM-DD')
        }
      }
      this.$emit('change', dateStrings)
    },
    resetDate (val) {
      this.startValue = val && val[0] || ''
      this.endValue = val && val[1] || ''
      this.$emit('change', [])
    }
  }
}
</script>
