<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import dayjs, { type Dayjs } from 'dayjs';

defineOptions({
  name: 'DateTimePicker',
});

interface DateOption {
  label: string;
  date: Dayjs;
  dateStr: string;
  displayDate: string;
  isToday: boolean;
}

interface Props {
  visible: boolean;
  pickerType?: 'date' | 'time';
  initialDate?: string | null;
  initialTime?: string | null;
  isFromTimeButton?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  pickerType: 'date',
  initialDate: null,
  initialTime: null,
  isFromTimeButton: false,
});

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'date-select': [date: Dayjs];
  'time-select': [time: string, date: Dayjs];
  'date-confirm': [date: Dayjs];
  'close': [];
}>();

const internalPickerType = ref<'date' | 'time'>(props.pickerType);
const selectedDate = ref<Dayjs>(dayjs());
const selectedTime = ref<string>('');
// 起始日期
const startDate = ref<Dayjs>(dayjs());

const dateUpdateKey = ref(0);
const datePickerVisible = ref(false);
const datePickerValue = ref<Dayjs | undefined>(undefined);

// 初始化选中日期
function initializeSelectedDate() {
  if (props.initialDate) {
    const initialDate = dayjs(props.initialDate);
    selectedDate.value = initialDate;
    startDate.value = initialDate; 
  } else {
    const today = dayjs();
    selectedDate.value = today; // 默认今天
    startDate.value = today; 
  }
}

// 初始化选中时间
function initializeSelectedTime() {
  selectedTime.value = props.initialTime || '';
}


watch(() => props.visible, (newVal) => {
  if (newVal) {
    internalPickerType.value = props.pickerType;
    initializeSelectedDate();
    initializeSelectedTime();
  }
});


watch(() => props.initialDate, () => {
  if (props.visible) {
    initializeSelectedDate();
  }
}, { immediate: true });

watch(() => props.pickerType, (newVal) => {
  internalPickerType.value = newVal;
});

// 获取5天的日期列表
const dateOptions = computed(() => {
  const dates: DateOption[] = [];
  const today = dayjs();
  const tomorrow = today.add(1, 'day');
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const start = dayjs(startDate.value);

  for (let i = 0; i < 5; i++) {
    const date = start.clone().add(i, 'day');
    const dayOfWeek = date.day();
    const isToday = date.isSame(today, 'day');
    const isTomorrow = date.isSame(tomorrow, 'day');

    let label = '';
    if (isToday) {
      label = '今天';
    } else if (isTomorrow) {
      label = '明天';
    } else {
      label = weekdays[dayOfWeek];
    }

    dates.push({
      label,
      date: date.clone(), 
      dateStr: date.format('YYYY-MM-DD'),
      displayDate: date.format('M月D日'),
      isToday: isToday,
    });
  }

  return dates;
});


const timeOptions = computed(() => {
  const times: string[] = [];
  for (let hour = 8; hour <= 20; hour++) {
    times.push(`${hour.toString().padStart(2, '0')}:00`);
    if (hour < 20) {
      times.push(`${hour.toString().padStart(2, '0')}:30`);
    }
  }
  return times;
});

// 判断某个时间是否被禁用
function isTimeDisabled(time: string): boolean {
  if (!selectedDate.value) return false;
  
  const now = dayjs();
  const selectedDateStr = selectedDate.value.format('YYYY-MM-DD');
  const todayStr = now.format('YYYY-MM-DD');
  
  // 如果选择的日期是今天，禁用当前时间之前的时间点
  if (selectedDateStr === todayStr) {
    const [hour, minute] = time.split(':').map(Number);
    const timeDate = now.hour(hour).minute(minute).second(0).millisecond(0);
    // 如果时间早于当前时间，禁用
    return timeDate.isBefore(now);
  }
  
  // 如果选择的日期是过去的日期，禁用
  if (selectedDate.value.isBefore(now, 'day')) {
    return true;
  }
  
  return false;
}


function handleDateSelect(dateItem: DateOption) {
  selectedDate.value = dateItem.date;
  const selectedDateStr = dateItem.dateStr;
  const currentStartStr = startDate.value.format('YYYY-MM-DD');
  const currentEnd = startDate.value.add(4, 'day');
  const currentEndStr = currentEnd.format('YYYY-MM-DD');
  

  if (selectedDateStr < currentStartStr || selectedDateStr > currentEndStr) {
    startDate.value = dateItem.date;
    dateUpdateKey.value += 1;
  }
}

// 打开日期选择弹窗
function handleOpenDatePicker() {
  datePickerValue.value = selectedDate.value.clone();
  datePickerVisible.value = true;
}

// 日期选择
function handleDatePickerChange(value: string | Dayjs | null) {
  if (value) {
    const date = dayjs.isDayjs(value) ? value : dayjs(value);
    datePickerValue.value = date;
  } else {
    datePickerValue.value = undefined;
  }
}

// 确认日期选择
function handleConfirmDatePicker() {
  if (!datePickerValue.value) {
    message.warning('请先选择日期');
    return;
  }
  
  // 获取选中的日期值
  const selectedDateValue = datePickerValue.value;
  
  let dateStr: string;
  if (dayjs.isDayjs(selectedDateValue)) {
    dateStr = selectedDateValue.format('YYYY-MM-DD');
  } else if (typeof selectedDateValue === 'string') {
    dateStr = selectedDateValue;
  } else {
    dateStr = dayjs(selectedDateValue).format('YYYY-MM-DD');
  }
  
  // 创建新的日期对象
  const newDate = dayjs(dateStr);
  
  startDate.value = newDate.clone();
  

  selectedDate.value = newDate.clone();

  dateUpdateKey.value += 1;
  
  datePickerVisible.value = false;
  
  emit('date-select', newDate.clone());
  
  if (props.isFromTimeButton) {
    internalPickerType.value = 'time';
  }
}

// 关闭日期选择弹窗
function handleCloseDatePicker() {
  datePickerVisible.value = false;
}

// 处理时间选择
function handleTimeSelect(time: string) {
  if (isTimeDisabled(time)) {
    return;
  }
  selectedTime.value = time;
}

// 确认时间选择
function handleConfirmTimeSelect() {
  if (!selectedDate.value) {
    message.warning('请先选择日期');
    return;
  }
  
  if (!selectedTime.value) {
    message.warning('请先选择时间');
    return;
  }
  
  emit('date-select', selectedDate.value.clone());
  
  emit('time-select', selectedTime.value, selectedDate.value);
  handleClose();
}

// 关闭弹窗
function handleClose() {
  emit('update:visible', false);
  emit('close');
}
</script>

<template>
  <a-modal 
    :open="visible" 
    title="请选择开始服务时间" 
    :width="internalPickerType === 'date' ? 600 : 800"
    @cancel="handleClose" 
    @ok="handleConfirmTimeSelect"
    class="date-time-picker-modal">
    <div class="date-time-picker-content">
      <!-- 时间选择区域 -->
      <div class="time-selection-section">
        <div class="date-header">
          <div class="date-options-header" :key="`${startDate.format('YYYY-MM-DD')}-${dateUpdateKey}`">
            <div v-for="dateItem in dateOptions" :key="dateItem.dateStr" class="date-option-header"
              :class="{ active: selectedDate.format('YYYY-MM-DD') === dateItem.dateStr }"
              @click="handleDateSelect(dateItem)">
              <div class="date-label">{{ dateItem.label }}</div>
              <div class="date-value">{{ dateItem.displayDate }}</div>
            </div>
          </div>
          <div class="calendar-icon" @click="handleOpenDatePicker">📅</div>
        </div>
        <div class="time-grid">
          <template v-if="timeOptions && timeOptions.length > 0">
            <div v-for="time in timeOptions" :key="time" class="time-slot" 
              :class="{ 
                active: selectedTime === time,
                disabled: isTimeDisabled(time)
              }"
              @click="handleTimeSelect(time)">
              {{ time }}
            </div>
          </template>
          <div v-else class="time-grid-empty">暂无时间选项</div>
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 日期选择弹窗 -->
  <a-modal
    :open="datePickerVisible"
    title="请选择日期"
    :width="400"
    @cancel="handleCloseDatePicker"
    @ok="handleConfirmDatePicker"
    class="date-picker-modal">
    <div class="date-picker-content">
      <a-date-picker
        v-model:value="datePickerValue"
        format="YYYY-MM-DD"
        placeholder="请选择日期"
        style="width: 100%"
        @change="handleDatePickerChange" />
    </div>
  </a-modal>
</template>

<style scoped lang="scss">
.date-time-picker-content {
  .date-selection-section {
    .date-options {
      display: flex;
      gap: 12px;
      margin-bottom: 24px;
      justify-content: center;

      .date-option {
        flex: 1;
        padding: 16px 12px;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        background: #fff;

        .date-label {
          font-size: 14px;
          color: #333;
          margin-bottom: 4px;
          font-weight: 500;
        }

        .date-value {
          font-size: 13px;
          color: #666;
        }

        &:hover {
          border-color: #8bc34a;
          background: #f9fff9;
        }

        &.active {
          background: #8bc34a;
          border-color: #8bc34a;

          .date-label,
          .date-value {
            color: #fff;
          }
        }
      }
    }

    .picker-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
    }
  }

  .time-selection-section {
    .date-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      .date-options-header {
        display: flex;
        gap: 12px;
        flex: 1;

        .date-option-header {
          flex: 1;
          padding: 12px 8px;
          border: 1px solid #e8e8e8;
          border-radius: 4px;
          text-align: center;
          cursor: pointer;
          transition: all 0.3s;
          background: #fff;

          .date-label {
            font-size: 13px;
            color: #333;
            margin-bottom: 2px;
            font-weight: 500;
          }

          .date-value {
            font-size: 12px;
            color: #666;
          }

          &:hover {
            border-color: #8bc34a;
            background: #f9fff9;
          }

          &.active {
            background: #8bc34a;
            border-color: #8bc34a;

            .date-label,
            .date-value {
              color: #fff;
            }
          }
        }
      }

      .calendar-icon {
        font-size: 20px;
        margin-left: 16px;
        cursor: pointer;
        transition: transform 0.2s;

        &:hover {
          transform: scale(1.1);
        }
      }
    }

    .time-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;
      min-height: 200px;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background: #d9d9d9;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: #bfbfbf;
      }

      .time-slot {
        padding: 12px 8px;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        text-align: center;
        font-size: 14px;
        color: #333;
        cursor: pointer;
        transition: all 0.3s;
        background: #fff;
        min-height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;

        &:hover:not(.disabled) {
          border-color: #8bc34a;
          background: #f9fff9;
        }

        &.active {
          background: #8bc34a;
          border-color: #8bc34a;
          color: #fff;
        }

        &.disabled {
          opacity: 0.4;
          cursor: not-allowed;
          background: #f5f5f5;
          color: #999;
          border-color: #e8e8e8;

          &:hover {
            border-color: #e8e8e8;
            background: #f5f5f5;
          }
        }
      }

      .time-grid-empty {
        grid-column: 1 / -1;
        text-align: center;
        padding: 40px;
        color: #999;
      }
    }
  }
}
</style>

<style lang="scss">
.date-time-picker-modal {
  .ant-modal-header {
    padding: 16px 24px;
    border-bottom: 1px solid #f0f0f0;

    .ant-modal-title {
      font-size: 16px;
      font-weight: 500;
      text-align: center;
      position: relative;
    }
  }

  .ant-modal-body {
    padding: 24px;
  }

  .date-time-picker-content {
    .time-selection-section {
      .time-grid {
        display: grid !important;
        grid-template-columns: repeat(5, 1fr) !important;
        gap: 8px !important;
        max-height: 400px;
        overflow-y: auto;
        padding-right: 8px;
        min-height: 200px;

        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-thumb {
          background: #d9d9d9;
          border-radius: 3px;
        }

        &::-webkit-scrollbar-thumb:hover {
          background: #bfbfbf;
        }

        .time-slot {
          padding: 12px 8px !important;
          border: 1px solid #e8e8e8 !important;
          border-radius: 4px !important;
          text-align: center !important;
          font-size: 14px !important;
          color: #333 !important;
          cursor: pointer !important;
          transition: all 0.3s;
          background: #fff !important;
          min-height: 40px;
          display: flex !important;
          align-items: center !important;
          justify-content: center !important;
          box-sizing: border-box;

          &:hover:not(.disabled) {
            // border-color: #8bc34a !important;
            // background: #f9fff9 !important;
          }

          &.active {
            background: #8bc34a !important;
            border-color: #8bc34a !important;
            color: #fff !important;
          }

          &.disabled {
            opacity: 0.4 !important;
            cursor: not-allowed !important;
            background: #f5f5f5 !important;
            color: #999 !important;
            border-color: #e8e8e8 !important;

            &:hover {
              border-color: #e8e8e8 !important;
              background: #f5f5f5 !important;
            }
          }
        }

        .time-grid-empty {
          grid-column: 1 / -1;
          text-align: center;
          padding: 40px;
          color: #999;
        }
      }
    }
  }
}

.date-picker-content {
  padding: 20px 0;
}
</style>

<style lang="scss">
.date-picker-modal {
  .ant-modal-body {
    padding: 24px;
  }
}
</style>
