<template>
  <div class="date-range-filter">
    <el-date-picker
      style="flex: 1"
      v-model="beginDate"
      type="date"
      placeholder="开始日期"
      value-format="YYYY-MM-DD"
      :disabled-date="disableBeginDate"
    />
    <span style="margin: 0 5px">至</span>
    <el-date-picker
      style="flex: 1"
      v-model="endDate"
      type="date"
      placeholder="结束日期"
      value-format="YYYY-MM-DD"
      :disabled-date="disableEndDate"
    />
  </div>
</template>

<script setup lang="ts" name="selectFilter">
import { defineEmits, defineProps, computed } from "vue";
import dayjs from "dayjs";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(["update:modelValue"]);

const beginDate = computed<string | undefined>({
  get() {
    return props.modelValue?.[0] as string;
  },
  set(val) {
    const result = props.modelValue ? [...props.modelValue] : [];
    result[0] = val;
    emit("update:modelValue", result);
  }
});
const endDate = computed<string | undefined>({
  get() {
    return props.modelValue?.[1] as string;
  },
  set(val) {
    const result = props.modelValue ? [...props.modelValue] : [];
    result[1] = val || undefined;
    emit("update:modelValue", result);
  }
});

const disableBeginDate = (date: Date) => {
  const [, end] = props.modelValue || [];
  if (end) {
    return dayjs(end as string).isBefore(date);
  }
  return false;
};

const disableEndDate = (date: Date) => {
  const [begin] = props.modelValue || [];
  if (begin) {
    return dayjs(begin as string).isAfter(date);
  }
  return false;
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
