<template>
  <div class="function">
    <el-button v-for="btn of buttonList" :key="btn.value" round size="mini" :class="checked==btn.value?'btn-checked':''" @click="changeTime(btn.value)">
      {{ btn.label }}
    </el-button>
  </div>
</template>

<script>
import {
  getSearch1YearTime,
  getSearch3MonthTime,
  getSearch6MonthTime,
  getSearchLastMonthTime,
  getSearchLastWeekTime
} from '@/utils/dateutils'

export default {
  name: 'TimeButtons',
  props: {
    buttons: {
      type: Array,
      default: () => {
        return ['3month', 'month', 'week']
      }
    }, // 支持的按钮
    defaultChecked: {
      type: String,
      default: 'week'
    } // 默认选中
  },
  data() {
    return {
      timeRange: [], // 时间范围
      checked: '',
      buttonDict: [
        { label: '近1年', value: 'year' },
        { label: '近6月', value: 'halfyear' },
        { label: '近3月', value: '3month' },
        { label: '近1月', value: 'month' },
        { label: '近1周', value: 'week' }
      ] // 按钮字典
    }
  },
  computed: {
    buttonList() {
      return this.buttonDict.filter(item => this.buttons.indexOf(item.value) > -1)
    }
  },
  created() {
    this.checked = this.defaultChecked
  },
  mounted() {
  },
  methods: {
    // 时间发生切换
    changeTime(type) {
      this.checked = type
      let timeRange = []
      switch (type) {
        case 'year':
          timeRange = getSearch1YearTime()
          break
        case 'halfyear':
          timeRange = getSearch6MonthTime()
          break
        case '3month':
          timeRange = getSearch3MonthTime()
          break
        case 'month':
          timeRange = getSearchLastMonthTime()
          break
        case 'week':
          timeRange = getSearchLastWeekTime()
          break
      }
      this.$emit('change', timeRange)
    },
    // 强制触发
    initTime() {
      this.changeTime(this.defaultChecked)
    }
  }
}
</script>

<style lang="scss" scoped>
.function{
  display: inline-block;
  padding: 0px 10px;
  .btn-checked{
    color: #409EFF;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }
}
</style>
