<template>
	<u-input :value="year" v-if="readonly" readonly></u-input>
	<simple-select v-else v-model="year" load-type="local" :data="options" :readonly="readonly" @on-change="changed"></simple-select>
</template>

<script>
	import simpleSelect from './simpleSelect.vue';
	import { strOrNull } from '@/utils/tools';
	export default {
		name:"yearSelect",
		props: {
			value: {
				type: [String, Number],
				required: false,
				default: null,
			},
			range: {
				type: Number,
				required: false,
				default: 10,
			},
			readonly: {
				type: Boolean,
				required: false,
				default: false,
			}
		},
		components: {
			simpleSelect
		},
		data() {
			return {
				year: this.parseValue(this.value),
				options: [],
			};
		},
		watch: {
			value(n, o) {
				this.year = this.parseValue(n)
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				const now = new Date()
				const year = now.getFullYear()
				for(let i = this.range; i > 0; i --) {
					const o = `${year - i}`
					this.options.push({
						text: o,
						value: o,
					})
				}
				this.options.push({
					text: year + '',
					value: year + '',
				})
				for(let i = 1; i <= this.range; i ++) {
					const o = `${year + i}`
					this.options.push({
						text: o,
						value: o,
					})
				}
			
			},
			parseValue(v) {
				let ret = strOrNull(v)
				if(typeof v === 'string') {
					if(v.includes('-')) {
						const [date, time] = v.split(' ')
						const [y, ... other] = date.split('-')
						ret = strOrNull(y)
					}
				}
				this.appendOptions(ret)
				return ret
			},
			appendOptions(v) {
				if(! this.options) return 
				const n = this.options.find(d => d.value === v)
				if(! n) {
					this.options = [{
						text: v,
						value: v,
					}, ... this.options]
				}
			},
			changed(n) {
				this.year = n
				this.$emit('input', strOrNull(this.year))
			}
		}
	}
</script>

<style>

</style>