<template>
  <view>
    <view class="flex justify-end text-white" @click="onClick">
      <view>{{ valueFormat }}</view>
      <uv-icon color="white" size="16rpx" name="arrow-down-fill"></uv-icon>
    </view>
    <uv-datetime-picker
      ref="datetimePicker"
      v-model="value"
      :mode="mode"
      @confirm="confirm"
      :maxDate="Number(new Date())" 
      :minDate="Number(new Date(2020, 0, 1))"
    >
    </uv-datetime-picker>
  </view>
</template>
<script setup>
import { ref, watch, watchEffect, computed } from 'vue'
import { timeFormat } from '@climblee/uv-ui/libs/function/index'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: null,
  },
  mode: {
    type: String,
    default: 'year-month',
  },
  formatStr: {
    type: String,
    default: 'yyyy年mm月',
  },
})
const datetimePicker = ref(null)
const value = ref(props.modelValue || Number(new Date()))
const valueFormat = computed(() => {
  return timeFormat(value.value, props.formatStr)
})


const emit = defineEmits(['update:modelValue','confirm'])


const confirm = (e) => {
  value.value = e.value
  emit('confirm', e)
}

const onClick = () => {
  datetimePicker.value.open()
}


watchEffect(() => {
  value.value = props.modelValue || Number(new Date())
})

watch(
  () => value.value,
  (val) => {
    emit('update:modelValue', val)
  }
)
</script>
