<template>
  <div class="flex items-center">
    <div class="quick-select">
      <el-check-tag
        class="ml-3"
        :checked="activeValue == item.value"
        @change="onChange(item)"
        v-for="item in checkList"
        >{{ item.label }}</el-check-tag
      >
    </div>

    <div class="ml-3">
      <el-date-picker
        :style="{ width: dateType == 'daterange' ? '260px' : '360px' }"
        style="max-width: 360px; margin-right: 16px"
        v-model="dataRange"
        :type="dateType"
        range-separator="-"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        @change="handleDateChange"
      />
      <el-button style="width: 80px" type="primary" @click="search"
        >查询</el-button
      >
      <el-button style="width: 80px" type="info" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script setup>
  const props = defineProps({
    startKey: { type: String, default: 'startTime' },
    endKey: { type: String, default: 'endTime' },
    formatterKey: { type: String, default: 'YYYY-MM-DD' },
    dateType: { type: String, default: 'daterange' }
  });

  import { dayjs } from 'element-plus';

  const activeValue = ref(0);
  let checkList = reactive([
    { label: '7日', value: 1, number: 7 },
    { label: '15日', value: 2, number: 15 },
    { label: '30日', value: 3, number: 30 }
  ]);

  const emit = defineEmits(['search']);
  function onChange(item) {
    activeValue.value = item.value;
    dataRange.value = getLastDays(item.number);
  }

  function getLastDays(number = 7) {
    const endDate = dayjs();
    const startDate = endDate.subtract(number - 1, 'day');
    return [
      startDate.format(props.formatterKey),
      endDate.format(props.formatterKey)
    ];
  }

  const dataRange = ref([]);

  function search() {
    let date = {};
    date[props.startKey] = dataRange.value[0] || '';
    date[props.endKey] = dataRange.value[1] || '';
    emit('search', date);
  }

  function reset() {
    dataRange.value = [];
    activeValue.value = 0;
    emit('search', {});
  }

  function handleDateChange(value) {
    activeValue.value = 0;
  }
</script>
