<script setup>
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

const props = defineProps({
  modelValue: {
    type: [Date, String, Number],
    default: () => new Date() // 默认当前日期
  },
  label: {
    type: String,
    default: '日期'
  },
  required: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择日期'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  minDate: {
    type: Date,
    default: () => new Date(1900, 0, 1)
  },
  maxDate: {
    type: Date,
    default: () => new Date(2100, 11, 31)
  },
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  }
})

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

// 显示文本
const displayText = computed(() => {
  return dayjs(props.modelValue).format(props.format)
})

// 默认值
const defaultValue = computed(() => {
  const date = props.modelValue || new Date()
  return [
    date.getFullYear(),
    date.getMonth() + 1,
    date.getDate()
  ]
})

// 确认选择
const onConfirm = ({ selectedValues }) => {
  show.value = false
  const date = new Date(selectedValues[0], selectedValues[1] - 1, selectedValues[2])
  emit('update:modelValue', date)
  emit('change', date)
}

// 取消选择
const onCancel = () => {
  show.value = false
}

// 重置为当前日期
const reset = () => {
  emit('update:modelValue', new Date())
}

defineExpose({
  reset
})
</script>

<template>
  <div>
    <van-field
        :model-value="displayText"
        @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"
    >
      <van-date-picker
          :min-date="minDate"
          :max-date="maxDate"
          :model-value="defaultValue"
          @confirm="onConfirm"
          @cancel="onCancel"
          title="选择日期"
      />
    </van-popup>
  </div>
</template>