<script setup>
import "./services/date.js"

// 常用属性：
//    name <string> 字段名
//
// 常用事件：
//   @change 有日期变化
//
// TODO 表头修改为YYYY年M月（注意locale设置）
import DatePicker from "primevue/datepicker";
import {onMounted, ref, watch} from "vue";

const emits = defineEmits(["change", "update:modelValue"])
const props = defineProps(["name", "modelValue"])

const valueRef = ref()

onMounted(() => {
	if (typeof props.modelValue === "string" && props.modelValue.length > 0) {
		valueRef.value = parseDate(props.modelValue) // TODO 需要根据 format 进行不同的格式化
	}
})

const parseDate = (v) => {
	if (v == null) {
		return new Date()
	}

	if (v instanceof Date) {
		return v
	}

	if (typeof v === "string" && v.length > 0) {
		const format1 = v.match(/^(\d+)-(\d+)-(\d+)$/)
		if (format1) {
			const date = new Date()
			date.setFullYear(parseInt(format1[1], 10))
			date.setMonth(parseInt(format1[2]) - 1)
			date.setDate(parseInt(format1[3]))
			return date
		}
	}

	return new Date()
}

const onChange = (date) => {
	if (date == null) {
		emits("update:modelValue", "")
		emits("change", "")
		return
	}

	emits("update:modelValue", date.format("Y-m-d"))
	emits("change", date.format("Y-m-d")) // TODO 需要根据 format 进行不同的格式化
}

watch(() => props.modelValue, (v) => {
	if (typeof v === "string" && v.length > 0) {
		valueRef.value = parseDate(v)
	}
})

</script>

<template>
	<DatePicker @update:modelValue="onChange" :name="name" v-model="valueRef" showButtonBar></DatePicker>
</template>

<style scoped>
:deep(.p-datepicker-input) {
	width: 7.5em !important;
}
</style>