<template>
  <el-date-picker
    v-model="selected"
    type="datetimerange"
    :default-time="defaultTimeVar"
    range-separator="至"
    start-placeholder="开始日期时间"
    end-placeholder="结束日期时间"
    value-format="x"
    format="YYYY-MM-DD HH:mm"
    :style="{ width: '380px' }"
    v-bind="attrs"
    @change="onChange"
  />
</template>

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

  // import { ElDatePicker } from 'element-plus';

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

  type TimeType = number | undefined;

  const props = withDefaults(
    defineProps<{
      startTime: TimeType;
      endTime: TimeType;
      // showTime prop is implicit in datetimerange type of el-date-picker
    }>(),
    {}
  );
  const emit = defineEmits(['update:startTime', 'update:endTime', 'change']);
  const attrs = useAttrs();

  const selected = ref<number[]>();

  // Helper for default-time prop in ElDatePicker
  // It expects an array of two Date objects
  const defaultTimeVar = ref([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 1, 1, 23, 59, 59),
  ]);

  function onChange(value: any) {
    const vals = (value || []) as TimeType[];
    // Element Plus with value-format="x" returns timestamps in milliseconds
    // Arco's timestamp might be seconds, ensure consistency or convert if needed.
    // Assuming timestamps are compatible for now.
    emit('update:startTime', vals[0]);
    emit('update:endTime', vals[1]);
    emit('change', vals);
  }

  watch(
    () => [props.startTime, props.endTime],
    (val) => {
      // Ensure that null/undefined values are handled correctly for el-date-picker
      if (
        val[0] !== undefined &&
        val[1] !== undefined &&
        val[0] !== null &&
        val[1] !== null
      ) {
        selected.value = [val[0], val[1]] as number[];
      } else {
        selected.value = undefined; // Or an empty array [], depending on desired behavior for empty state
      }
    },
    {
      immediate: true,
    }
  );
</script>
