<template>
    <div class="app-datepicker">
        <div @click="show = true">
            <slot>
                <span class="app-datepicker__placeholder">{{ modelValue || placeholder }}</span>
            </slot>
        </div>
        <Popup v-model:show="show" position="bottom" round>
            <DatePicker v-model="currentDate" title="选择日期" @cancel="onCancel" @confirm="onConfirm" />
        </Popup>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { Popup, DatePicker } from 'vant'
import moment from 'moment'

const props = defineProps({
    modelValue: {
        type: String,
        required: true
    },
    // 分隔符
    separator: {
        type: String,
        default: '-'
    },
    // 占位符文本
    placeholder: {
        type: String,
        default: '日期选择'
    }
})

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

const show = ref(false)
const currentDate = ref<string[]>([])

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

const onConfirm = () => {
    emit('update:modelValue', currentDate.value.join(props.separator))
    onCancel()
}

onMounted(() => {
    if (props.modelValue) {
        currentDate.value = props.modelValue.split(props.separator)
    } else {
        const now = moment()
        const dateArray = [now.format('YYYY'), now.format('MM'), now.format('DD')]
        currentDate.value = dateArray
    }
})
</script>

<style lang="less">
@import './index.less';
</style>