<template>
	<div>
		<ion-datetime-button :datetime="fromId" :class="{ 'empty-value': !valueFrom }">
			<span slot="date-target" class="slot-datatime-target">{{ getDisplayText('from') }}</span>
		</ion-datetime-button>
		<span class="bar">~</span>
		<ion-datetime-button :datetime="toId" :class="{ 'empty-value': !valueTo }">
			<span slot="date-target" class="slot-datatime-target">{{ getDisplayText('to') }}</span>
		</ion-datetime-button>
	</div>
	<ion-modal :keepContentsMounted="true">
		<ion-datetime
			:id="fromId"
			v-model="valueFrom"
			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>

	<ion-modal :keepContentsMounted="true">
		<ion-datetime
			:id="toId"
			v-model="valueTo"
			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: 'SgcDatetimeRange',
	props: ['from', 'to', 'hideClearButton'],
	emits: ['update:from', 'update:to', 'sgcChange', 'sgcBlur'],
	components: {
		IonDatetime,
		IonDatetimeButton,
		IonModal,
	},
	mounted() {
		this.onLoad();
	},
	watch: {
		from() {
			this.updateValue();
		},
		to() {
			this.updateValue();
		},
	},
	data(): {
		fromId: string;
		toId: string;
		disabled: boolean;
		maxDate: string;
		minDate: string;
		valueFrom: string;
		valueTo: string;
	} {
		return {
			fromId: commonService.getUuid('datetime_from'),
			toId: commonService.getUuid('datetime_to'),
			disabled: false,
			maxDate: '2028-12-31',
			minDate: '2022-01-01',
			valueFrom: null,
			valueTo: null,
		};
	},
	methods: {
		/** 안전한 날자 가져오기 */
		_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;
		},
		/** 비활성화  */
		setDisabled(disabled: boolean) {
			this.disabled = disabled;
		},
		/** 값 업데이트 */
		updateValue() {
			this.valueFrom = this._getSafeDate(this.from);
			this.valueTo = this._getSafeDate(this.to);
		},
		/** 값 가져오기 */
		getValue(type: string) {
			switch (type) {
				case 'from':
					return this._getSafeFormat(this.valueFrom, 'yyyyMMdd');
				case 'to':
					return this._getSafeFormat(this.valueTo, 'yyyyMMdd');
				default:
					break;
			}
			return '';
		},
		/** 디스플레이 정보 가져오기 */
		getDisplayText(type: string) {
			switch (type) {
				case 'from':
					return this._getSafeFormat(this.valueFrom, 'yyyy-MM-dd', '____-__-__');
				case 'to':
					return this._getSafeFormat(this.valueTo, 'yyyy-MM-dd', '____-__-__');
				default:
					break;
			}
			return '____-__-__';
		},
		/** 값 설정하기 */
		setValue() {
			const dataFrom = this.getValue('from');
			const dataTo = this.getValue('to');
			if (dataFrom !== null && dataFrom !== '' && dataTo !== null && dataTo !== '' && dataFrom > dataTo) {
				commonService.openToast('MSG_ERROR_DATERANGE', null, null, null, 'warning');
				return;
			}
			this.$emit('update:from', dataFrom);
			this.$emit('update:to', dataTo);
			this.$emit('sgcChange', [dataFrom, dataTo]);
		},
		/** 로그시 실행 */
		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">
div {
	display: block;
	margin-top: 0.4em;
	width: 100%;

	> span.bar {
		font-size: 0.7em;
		display: inline-block;
		vertical-align: middle;
		margin-right: 0.2em;
	}

	ion-datetime-button {
		max-width: calc(50% - 6px);
		position: relative;
		display: inline-block;
		vertical-align: middle;
		overflow: hidden;
		&.empty-value {
			span.slot-datatime-target {
				color: rgba(var(--ion-color-base-rgb), 0.3);
			}
		}

		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);
			}
		}
		&::part(native) {
			background-color: transparent;
			font-size: 0.9rem;
			margin-left: 0;
			padding-left: 0;
			padding-right: 0;
		}
	}
}
</style>
