<template>
  <el-form :inline="true" size="small" class="order-date-filter">
    <el-form-item label="统计周期">
      <el-radio-group v-model="periodType" size="small" @change="handlePeriodChange">
        <el-radio-button label="day">日报</el-radio-button>
        <el-radio-button label="month">月报</el-radio-button>
        <el-radio-button label="year">年报</el-radio-button>
        <el-radio-button label="all">全量</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="日期范围">
      <span class="date-action-row">
        <el-date-picker
        v-model="dateRange"
        type="daterange"
        :popper-class="popperClass"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :clearable="periodType !== 'all'"
        :disabled="periodType === 'all'"
        :editable="false"
        :picker-options="pickerOptions"
        />
        <span class="filter-actions">
      <el-button type="primary" icon="el-icon-search" size="mini" @click="emitChange">查询</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
          <slot name="actions" :params="queryParams" />
        </span>
      </span>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'OrderDateRangeFilter',
  props: {
    maxDate: {
      type: String,
      default: ''
    },
    defaultPeriod: {
      type: String,
      default: 'day'
    },
    storageKey: {
      type: String,
      default: ''
    },
    fullRangeStart: {
      type: String,
      default: '1900-01-01'
    },
    popperClass: {
      type: String,
      default: 'order-date-popper'
    }
  },
  data() {
    return {
      periodType: this.defaultPeriod,
      dateRange: []
    }
  },
  computed: {
    queryParams() {
      const params = {
        periodType: this.periodType
      }
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
      }
      return params
    },
    pickerOptions() {
      return {
        disabledDate: time => {
          if (!this.maxDate) return false
          return time.getTime() > new Date(`${this.maxDate}T23:59:59`).getTime()
        }
      }
    }
  },
  watch: {
    maxDate: {
      immediate: true,
      handler(value) {
        if (value && (!this.dateRange || this.dateRange.length === 0)) {
          const stored = this.loadStoredFilter()
          if (stored) {
            this.periodType = stored.periodType || this.defaultPeriod
            this.dateRange = this.periodType === 'all' ? this.buildRange('all') : stored.dateRange
          } else {
            this.dateRange = this.buildRange(this.periodType)
          }
          this.emitChange()
        }
      }
    }
  },
  methods: {
    pad2(value) {
      return String(value).padStart(2, '0')
    },
    toDate(value) {
      if (value instanceof Date) return new Date(value.getTime())
      if (!value) return new Date()
      return new Date(`${value}T00:00:00`)
    },
    formatYmd(value) {
      const date = this.toDate(value)
      return `${date.getFullYear()}-${this.pad2(date.getMonth() + 1)}-${this.pad2(date.getDate())}`
    },
    startOfMonth(value) {
      const date = this.toDate(value)
      return new Date(date.getFullYear(), date.getMonth(), 1)
    },
    endOfMonth(value) {
      const date = this.toDate(value)
      return new Date(date.getFullYear(), date.getMonth() + 1, 0)
    },
    startOfYear(value) {
      const date = this.toDate(value)
      return new Date(date.getFullYear(), 0, 1)
    },
    endOfYear(value) {
      const date = this.toDate(value)
      return new Date(date.getFullYear(), 11, 31)
    },
    buildRange(type) {
      const baseDate = this.toDate(this.maxDate || new Date())
      if (type === 'all') {
        return [this.fullRangeStart, this.formatYmd(baseDate)]
      }
      if (type === 'year') {
        return [this.formatYmd(this.startOfYear(baseDate)), this.formatYmd(this.endOfYear(baseDate))]
      }
      if (type === 'month') {
        return [this.formatYmd(this.startOfMonth(baseDate)), this.formatYmd(this.endOfMonth(baseDate))]
      }
      const day = this.formatYmd(baseDate)
      return [day, day]
    },
    handlePeriodChange() {
      this.dateRange = this.buildRange(this.periodType)
      this.emitChange()
    },
    reset() {
      this.periodType = this.defaultPeriod
      this.dateRange = this.maxDate ? this.buildRange(this.periodType) : []
      this.emitChange()
    },
    loadStoredFilter() {
      if (!this.storageKey) {
        return null
      }
      try {
        const raw = window.sessionStorage.getItem(this.storageKey)
        if (!raw) {
          return null
        }
        const parsed = JSON.parse(raw)
        if (!parsed || !Array.isArray(parsed.dateRange) || parsed.dateRange.length !== 2) {
          return null
        }
        return parsed
      } catch (error) {
        return null
      }
    },
    saveStoredFilter() {
      if (!this.storageKey) {
        return
      }
      window.sessionStorage.setItem(this.storageKey, JSON.stringify({
        periodType: this.periodType,
        dateRange: this.dateRange
      }))
    },
    emitChange() {
      this.saveStoredFilter()
      this.$emit('change', this.queryParams)
    }
  }
}
</script>

<style scoped>
.order-date-filter {
  padding: 16px 16px 0;
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
}
</style>
