<template>
  <a-range-picker
    v-model="selected"
    :show-time="showTime"
    value-format="timestamp"
    :format="format"
    :style="{ width: '340px' }"
    v-bind="attrs"
    @change="onChange"
  />
</template>

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

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

  interface KeysType {
    startTime: string;
    endTime: string;
  }

  const props = withDefaults(
    defineProps<{
      modelValue: Record<string, any>;
      keys?: KeysType;
      showTime?: boolean;
      format?: string;
    }>(),
    {
      modelValue: () => {
        return {};
      },
      keys: () => {
        return { startTime: 'startTime', endTime: 'endTime' };
      },
      showTime: true,
      format: 'YYYY-MM-DD HH:mm',
    }
  );
  const emit = defineEmits(['update:modelValue', 'change']);
  const attrs = useAttrs();

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

  function onChange(value: any) {
    const { startTime, endTime } = props.keys;
    const dt: Record<string, number | undefined> = {};
    const vals = value as number[] | undefined;
    if (vals) {
      dt[startTime] = vals[0];
      dt[endTime] = vals[1];
    } else {
      dt[startTime] = undefined;
      dt[endTime] = undefined;
    }
    objModifyAssign(props.modelValue, dt);
    emit('update:modelValue', props.modelValue);
    emit('change', props.modelValue);
  }

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