<script setup>
import {ref, computed} from 'vue'
import dayjs from 'dayjs'
const props = defineProps({
  modelValue: {
    type: [Date, String, Number]
  },
  label: {
    type: String,
    default: '日期'
  },
  required: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择日期'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  minDate: {
    type: Date,
    default: () => dayjs('1900-01-01').toDate()
  },
  maxDate: {
    type: Date,
    default: () => dayjs('2100-12-31').toDate()
  },
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])
const show = ref(false)

const defaultValue = computed(() => {
  let date
  if (props.modelValue) {
    date = dayjs(props.modelValue)
  } else {
    date = dayjs()
  }

  if (!date.isValid()) {
    date = dayjs()
  }

  return [
    date.year(),
    date.month() + 1,
    date.date()
  ]
})

const formatDate = (dateArr) => {
  const [year, month, day] = dateArr
  return dayjs(`${year}-${month}-${day}`).format(props.format)
}

const displayValue = computed(() => {
  if (!props.modelValue) return ''
  const date = dayjs(props.modelValue)
  return date.isValid() ? date.format(props.format) : ''
})

const onConfirm = ({selectedValues}) => {
  show.value = false
  const formattedDate = formatDate(selectedValues)
  emit('update:modelValue', formattedDate)
  emit('change', formattedDate)
}

const onCancel = () => {
  show.value = false
}
</script>

<template>
  <div>
    <van-field
        :model-value="displayValue"
        @click="show = true"
        readonly
        :disabled="disabled"
        :required="required"
        :placeholder="placeholder"
        :label="label"
        class="mb-10px"
        is-link
    />

    <van-popup
        v-model:show="show"
        position="bottom"
        teleport="#__nuxt"
        destroy-on-close
        safe-area-inset-bottom
    >
      <van-date-picker
          :min-date="minDate"
          :max-date="maxDate"
          :model-value="defaultValue"
          @confirm="onConfirm"
          @cancel="onCancel"
          title="选择日期"
      />
    </van-popup>
  </div>
</template>