<script lang="ts" setup>
import enLocale from 'element-plus/es/locale/lang/en';
import dayjs from 'dayjs';
import { nextTick, ref } from 'vue';
import { ElMessage } from 'element-plus';

const datePicker = ref();
const dateModel = defineModel({
  type: Array,
});
const temp = dateModel.value || [];
const today = dayjs();

function disabledDate(date: Date) {
  const day = date.getDay();
  // 禁用非周六和周日的日期
  if (day !== 0 && day !== 6) {
    return true;
  }
  // 禁用超过当前日期的日期
  return date.getTime() > today.toDate().getTime();
}

function handleCalendarChange(data: Date[]) {
  if (data && data.length === 2) {
    const [startDate, endDate] = data.map((date: Date) => dayjs(date).format('YYYY-MM-DD'));
    // 不允许选择相同时间段
    if (startDate === endDate) {
      nextTick(() => {
        dateModel.value = temp;
        datePicker.value.handleOpen();
      });
      ElMessage.warning({ message: '请勿选择相同时间段!', plain: true });
    }
  }
}
</script>

<template>
  <el-config-provider :locale="enLocale">
    <el-date-picker
      ref="datePicker"
      v-model="dateModel"
      :disabled-date="disabledDate"
      @calendar-change="handleCalendarChange"
      :clearable="false"
      type="daterange"
      format="YYYY-MM-DD"
      value-format="YYYY-MM-DD"
      range-separator="To"
      placeholder="Select a date range"
      style="width: 270px">
    </el-date-picker>
  </el-config-provider>
</template>
