<template>
  <div class="cu-timeRange">
    <el-date-picker
      :value="value"
      :value-format="format"
      :format="format"
      :type="type"
      range-separator="至"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      unlink-panels="true"
      :default-time="['00:00:00', '23:59:59']"
      :clearable="false"
      @input="dayChange"
    />
    <div v-if="showButtons" v-cloak class="time-btn">
      <el-radio-group v-model.trim="checktime" @change="handelDay">
        <el-radio-button v-for="(item) in listObj" :key="item" :label="item" />
      </el-radio-group>
    </div>
  </div>

</template>

<script>
import { parseTime } from '@/utils'
export default {
  name: 'TimeRange',
  props: {
    value: {
      type: Array || String,
      default: () => ([])
    },
    showButtons: {
      type: Boolean,
      default: false
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd HH:mm:ss'
    },
    type: {
      type: String,
      default: 'datetimerange'
    },
    listObj: {
      type: Array,
      default: () => { return ['一月', '半年', '一年', '三年', '永久'] }
    }
  },
  data() {
    return {
      timeObj: {},
      checktime: ''
    }
  },
  created() {
    this.getTimeObj()
  },
  methods: {
    timeFormat(date) {
      const newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)
      return newDate[0]
    },
    dayChange(val) {
      this.checktime = val || ''
      this.$emit('input', val)
    },
    getTimeObj() { // 获取时间
      const startDate = new Date()
      const endDate = new Date()
      const today = parseTime(startDate)
      const oneMonth = parseTime(endDate.setDate(endDate.getDate() + 30))
      // const threeMonth = parseTime(endDate.setDate(endDate.getDate() + 30))
      const sixMonth = parseTime(new Date(endDate.setMonth(endDate.getMonth() + 6)))
      const oneYear = parseTime(new Date(endDate.setFullYear(endDate.getFullYear() + 1)))
      const threeYear = parseTime(new Date(endDate.setFullYear(endDate.getFullYear() + 3)))
      const allYear = parseTime(new Date('2099-12-31 00:00:00'))
      this.timeObj = {
        '一月': [today, oneMonth],
        '半年': [today, sixMonth],
        '一年': [today, oneYear],
        '三年': [today, threeYear],
        '永久': [today, allYear]
      }
    },
    handelDay(e) {
      this.$emit('input', this.getDateRange(e))
      this.dayChange(e)
    },
    getDateRange(type) {
      return this.timeObj[type]
    }
  }
}
</script>

<style scoped>
.time-btn{
  margin-top: 5px;
}
</style>
