<template>
  <a-time-picker
    v-model="selected"
    type="time-range"
    :format="format"
    :style="{ width: '200px' }"
    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;
      format?: string;
    }>(),
    {
      modelValue: () => {
        return {};
      },
      keys: () => {
        return { startTime: 'startTime', endTime: 'endTime' };
      },
      showTime: true,
      format: 'HH:mm',
    }
  );
  const emit = defineEmits(['update:modelValue', 'change']);
  const attrs = useAttrs();

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

  function onChange(value: any) {
    const { startTime, endTime } = props.keys;
    const dt: Record<string, string> = {};
    const vals = value as string[] | undefined;
    if (vals) {
      dt[startTime] = vals[0];
      dt[endTime] = vals[1];
    } else {
      dt[startTime] = '';
      dt[endTime] = '';
    }
    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 string, val[endTime] as string];
    },
    {
      immediate: true,
      deep: true,
    }
  );
</script>
