<template>
  <div class="time-range-picker">
    <div class="time-picker-section">
      <el-date-picker
        style="width: 200px;"
        v-model="startTime"
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择开始时间"
        @change="handleTimeChange"
      />
      <span class="separator">至</span>
      <el-date-picker
        style="width: 200px;"
        v-model="endTime"
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择结束时间"
        @change="handleTimeChange"
      />
    </div>
    <div class="quick-options">
      <el-button size="small" @click="setQuickTime('prevDay')">前一天</el-button>
      <el-button size="small" @click="setQuickTime('today')">今天</el-button>
      <el-button size="small" @click="setQuickTime('nextDay')">后一天</el-button>
      <el-button size="small" @click="setQuickTime('last7Days')">近7天</el-button>
      <el-button size="small" @click="setQuickTime('last15Days')">近15天</el-button>
      <el-button size="small" @click="setQuickTime('last30Days')">近30天</el-button>
      <el-button size="small" @click="setQuickTime('thisWeek')">本周</el-button>
      <el-button size="small" @click="setQuickTime('thisMonth')">本月</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TimeRangePicker',
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    startKey: {
      type: String,
      default: 'byCreateTimeStart'
    },
    endKey: {
      type: String,
      default: 'byCreateTimeEnd'
    },
    defaultStartTime: {
      type: String,
      default: ''
    },
    defaultEndTime: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      startTime: '',
      endTime: ''
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          this.startTime = newVal[this.startKey] || ''
          this.endTime = newVal[this.endKey] || ''
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    if (this.defaultStartTime && this.defaultEndTime) {
      this.startTime = this.defaultStartTime
      this.endTime = this.defaultEndTime
      this.handleTimeChange()
    }
  },
  methods: {
    addZero(num) {
      return num.toString().padStart(2, '0')
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = this.addZero(date.getMonth() + 1)
      const day = this.addZero(date.getDate())
      return `${year}-${month}-${day}`
    },
    // 从时间字符串中提取时分秒部分
    getTimePart(timeStr) {
      if (!timeStr) return '07:00:00'
      const parts = timeStr.split(' ')
      return parts.length > 1 ? parts[1] : '07:00:00'
    },
    // 将日期和时间组合
    combineDateTime(dateStr, timeStr) {
      return `${dateStr} ${timeStr}`
    },
    handleTimeChange() {
      this.$emit('input', {
        ...this.value,
        [this.startKey]: this.startTime,
        [this.endKey]: this.endTime
      })
      this.$emit('change', {
        ...this.value,
        [this.startKey]: this.startTime,
        [this.endKey]: this.endTime
      })
    },
    setQuickTime(type) {
      // 保留当前选中的时分秒
      const startHourMinSec = this.getTimePart(this.startTime)
      const endHourMinSec = this.getTimePart(this.endTime)
      
      // 获取当前选择的开始和结束时间对应的日期对象
      let currentStartDate = this.startTime ? new Date(this.startTime.replace(/-/g, '/')) : new Date()
      let currentEndDate = this.endTime ? new Date(this.endTime.replace(/-/g, '/')) : new Date()
      
      let newStartDate = new Date(currentStartDate)
      let newEndDate = new Date(currentEndDate)

      switch (type) {
        case 'prevDay':
          newStartDate.setDate(newStartDate.getDate() - 1)
          newEndDate.setDate(newEndDate.getDate() - 1)
          break
        case 'today':
          const todayNow = new Date()
          newStartDate = todayNow
          newEndDate = todayNow
          break
        case 'nextDay':
          newStartDate.setDate(newStartDate.getDate() + 1)
          newEndDate.setDate(newEndDate.getDate() + 1)
          break
        case 'last7Days':
          const now1 = new Date()
          const sevenDaysAgo = new Date(now1)
          sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
          newStartDate = sevenDaysAgo
          newEndDate = now1
          break
        case 'last15Days':
          const now2 = new Date()
          const fifteenDaysAgo = new Date(now2)
          fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 15)
          newStartDate = fifteenDaysAgo
          newEndDate = now2
          break
        case 'last30Days':
          const now3 = new Date()
          const thirtyDaysAgo = new Date(now3)
          thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
          newStartDate = thirtyDaysAgo
          newEndDate = now3
          break
        case 'thisWeek':
          const now4 = new Date()
          const dayOfWeek = now4.getDay() || 7
          const weekStart = new Date(now4)
          weekStart.setDate(weekStart.getDate() - dayOfWeek + 1)
          const weekEnd = new Date(weekStart)
          weekEnd.setDate(weekEnd.getDate() + 6)
          newStartDate = weekStart
          newEndDate = weekEnd
          break
        case 'thisMonth':
          const now5 = new Date()
          const monthStart = new Date(now5.getFullYear(), now5.getMonth(), 1)
          const monthEnd = new Date(now5.getFullYear(), now5.getMonth() + 1, 0)
          newStartDate = monthStart
          newEndDate = monthEnd
          break
      }

      // 组合新的日期和保留的时分秒
      this.startTime = this.combineDateTime(this.formatDate(newStartDate), startHourMinSec)
      this.endTime = this.combineDateTime(this.formatDate(newEndDate), endHourMinSec)
      
      this.handleTimeChange()
      
      // 快捷选择后触发查询事件
      this.$emit('quick-select')
    }
  }
}
</script>

<style scoped>
.time-range-picker {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.time-picker-section {
  display: flex;
  align-items: center;
  gap: 8px;
}
.separator {
  color: #606266;
}
.quick-options {
  display: flex;
  gap: 2px;
  flex-wrap: wrap;
}

.el-button + .el-button {
  margin-left: 4px
}
</style>
