<template>
  <a-range-picker
    v-model="selected"
    :show-time="showTime"
    value-format="timestamp"
    format="YYYY-MM-DD HH:mm"
    :time-picker-props="{
      defaultValue: '00:00:00',
    }"
    :style="{ width: '340px' }"
    unmount-on-close
    v-bind="attrs"
    @change="onChange"
  />
</template>

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

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

  type TimeType = number | undefined;

  const props = withDefaults(
    defineProps<{
      startTime: TimeType;
      endTime: TimeType;
      showTime?: boolean;
    }>(),
    {
      showTime: true,
    }
  );
  const emit = defineEmits(['update:startTime', 'update:endTime', 'change']);
  const attrs = useAttrs();

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

  function onChange(value: any) {
    const vals = (value || []) as TimeType[];
    emit('update:startTime', vals[0]);
    emit('update:endTime', vals[1]);
    emit('change', vals);
  }

  watch(
    () => [props.startTime, props.endTime],
    (val) => {
      selected.value = (val || []) as number[];
    },
    {
      immediate: true,
    }
  );
</script>
