<template>
  <a-range-picker v-bind="$attrs" v-model:value="dateArr" allowClear />
</template>
<script setup lang="ts">
// import type { Dayjs } from 'dayjs'
import dayjs, { Dayjs } from 'dayjs'
const startModal = defineModel<string | number | null>('start', { default: null })
const endModal = defineModel<string | number | null>('end', { default: null })
const props = defineProps({
  format: { type: String, default: 'YYYY-MM-DD' },
})

type RangeValue = [Dayjs, Dayjs]  | [string, string]
let dateArr = ref<RangeValue>()
if (startModal.value && endModal.value) {
  dateArr = ref<RangeValue>([dayjs(startModal.value, props.format), dayjs(endModal.value, props.format)])
}
watch(
  startModal,
  (newValue) => {
    console.log('---- start ----', );
    if (!newValue) {
      dateArr.value = ['', '']
    }else {
      if(endModal.value){
        dateArr.value = [dayjs(startModal.value), dayjs(endModal.value)]
      }
    }
  },
  { deep: true }
)
watch(
  endModal,
  (newValue) => {
    console.log('---- end ----', );
    if (!newValue) {
      dateArr.value = ['', '']
    }else {
      if(startModal.value){
        dateArr.value = [dayjs(endModal.value), dayjs(endModal.value)]
      }
    }
  },
  { deep: true }
)
const arrayRefDeepWatch = watch(
  dateArr,
  (newValue) => {
    if(newValue){
      if(newValue.every( item => typeof item === 'string')){
        startModal.value = ''
        endModal.value = ''
      }else {
        startModal.value = toRaw(newValue[0]).format(props.format)
        endModal.value = toRaw(newValue[1]).format(props.format)
      }
    }
  },
  { deep: true }
)
</script>

