<template>
  <el-time-picker
    v-model="selected"
    is-range
    :format="format"
    range-separator="至"
    start-placeholder="开始时间"
    end-placeholder="结束时间"
    :style="{ width: '220px' }"
    v-bind="attrs"
    @change="onChange"
  />
</template>

<script setup lang="ts">
  import { ref, watch, useAttrs } from 'vue';

  import { ElTimePicker } from 'element-plus';

  defineOptions({
    name: 'SelectRangeTime', // Corrected component name
  });

  type TimeType = string | undefined;

  const props = withDefaults(
    defineProps<{
      startTime: TimeType;
      endTime: TimeType;
      format?: string;
    }>(),
    {
      format: 'HH:mm',
    }
  );
  const emit = defineEmits(['update:startTime', 'update:endTime', 'change']);
  const attrs = useAttrs();

  const selected = ref<[Date, Date] | undefined>(); // ElTimePicker with is-range expects an array of two Date objects or undefined

  function onChange(value: any) {
    if (value && value.length === 2) {
      const formatTime = (date: Date) => {
        if (!date) return undefined;
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        // Seconds are included if format string contains 'ss'
        return props.format.includes('ss')
          ? `${hours}:${minutes}:${date
              .getSeconds()
              .toString()
              .padStart(2, '0')}`
          : `${hours}:${minutes}`;
      };
      const startTimeStr = formatTime(value[0]);
      const endTimeStr = formatTime(value[1]);
      emit('update:startTime', startTimeStr);
      emit('update:endTime', endTimeStr);
      emit('change', [startTimeStr, endTimeStr]);
    } else {
      emit('update:startTime', undefined);
      emit('update:endTime', undefined);
      emit('change', [undefined, undefined]);
    }
  }

  watch(
    () => [props.startTime, props.endTime],
    (val) => {
      const parseTime = (timeStr: string | undefined): Date | undefined => {
        if (!timeStr) return undefined;
        const [hours, minutes, seconds] = timeStr.split(':').map(Number);
        const date = new Date();
        date.setHours(hours, minutes, seconds || 0, 0);
        return date;
      };
      const startDate = parseTime(val[0]);
      const endDate = parseTime(val[1]);

      if (startDate && endDate) {
        selected.value = [startDate, endDate];
      } else {
        selected.value = undefined;
      }
    },
    {
      immediate: true,
    }
  );
</script>
