<template>
	<ion-datetime-button :datetime="datetimeId" :class="{ 'empty-value': !value }" ref="datetimeBtn" :disabled="readonly || false">
		<span slot="date-target" class="slot-datatime-target">{{ getDisplayText() }}</span>
	</ion-datetime-button>
	<ion-modal :keepContentsMounted="true">
		<ion-datetime
			:id="datetimeId"
			v-model="value"
			presentation="date"
			:min="minDate"
			:max="maxDate"
			:showClearButton="!hideClearButton"
			:showDefaultButtons="true"
			:doneText="$t('BTN_DONE')"
			:cancelText="$t('BTN_CANCEL')"
			:clearText="$t('BTN_CLEAR')"
			@ionChange="setValue()"
		></ion-datetime>
	</ion-modal>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { IonDatetime, IonDatetimeButton, IonModal } from '@ionic/vue';
import { format as dateFormat, parseISO as dateParseISO } from 'date-fns';
import commonService from './../../services/common.service';

export default defineComponent({
	name: 'SgcDatetime',
	props: ['modelValue', 'readonly', 'hideClearButton'],
	emits: ['update:modelValue', 'sgcChange', 'sgcBlur'],
	components: {
		IonDatetime,
		IonDatetimeButton,
		IonModal,
	},
	mounted() {
		this.onLoad();
	},
	watch: {
		modelValue() {
			this.updateValue();
		},
	},
	data(): {
		datetimeId: string;
		disabled: boolean;
		maxDate: string;
		minDate: string;
		value: string;
	} {
		return {
			datetimeId: commonService.getUuid('datetime'),
			maxDate: '2028-12-31',
			minDate: '2022-01-01',
			disabled: false,
			value: null,
		};
	},
	methods: {
		/** 포커스 지정 */
		setFocus() {
			commonService.getRef(this.$refs, 'datetimeBtn', 'handleDateClick')?.handleDateClick();
		},
		/** 비 활성화 */
		setDisabled(disabled: boolean) {
			this.disabled = disabled;
		},
		/** 안전한 날자 형태로 변환 */
		_getSafeDate(date: string): string {
			if (typeof date === 'string') {
				if (date.includes('T')) {
					return date.split('T')[0];
				} else if (date.length === 8) {
					return date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8);
				} else if (date.length === 6) {
					return '20' + date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8);
				}
			}
			return null;
		},
		/** 안전한 날자 형태로 변환 */
		_getSafeFormat(date: string, format: string, defaultTxt = ''): string {
			if (date !== null && date !== undefined && date !== '') {
				return dateFormat(dateParseISO(date), format);
			}
			return defaultTxt;
		},
		/** 값 업데이트 */
		updateValue() {
			this.value = this._getSafeDate(this.modelValue);
		},
		/** 값 가져오기 */
		getValue() {
			return this._getSafeFormat(this.value, 'yyyyMMdd');
		},
		/** 표시 정보 가져오기 */
		getDisplayText() {
			return this._getSafeFormat(this.value, 'yyyy-MM-dd', '____-__-__');
		},
		/** 값 설정 */
		setValue() {
			const dataValue = this.getValue();
			this.$emit('update:modelValue', dataValue);
			this.$emit('sgcChange', dataValue);
			this.$emit('sgcBlur', this.value);
		},
		/** 로그시 실행 */
		onLoad() {
			const today = new Date();
			this.maxDate = dateFormat(new Date(today).setFullYear(today.getFullYear() + 2), 'yyyy-MM-dd');
			this.minDate = dateFormat(new Date(today).setFullYear(today.getFullYear() - 78), 'yyyy-MM-dd');
			this.updateValue();
		},
	},
});
</script>
<style scoped lang="scss">
ion-datetime-button {
	position: relative;
	display: inline-block;
	span.slot-datatime-target {
		display: inline-block;
		padding-right: 1.2em;
		position: relative;
		&:after {
			content: '';
			position: absolute;
			display: inline-block;
			width: 1em;
			height: 1em;
			right: 0;
			top: 50%;
			margin-top: -0.5em;
			mask-image: url(../../assets/calendar-number-outline.svg);
			background-color: var(--sgc-color-tertiary-50, #9382e1);
		}
	}

	&.empty-value {
		span.slot-datatime-target {
			color: var(--border-color);
		}
	}

	&::part(native) {
		background-color: transparent;
		--ion-text-color: var(--sgc-background-light-font);
		font-size: 0.9rem;
		padding: 0 1rem 0 0;
		margin: 0;
	}
}
</style>
