<template>
	<v-row class="search-box" align="center" no-gutters>
		<v-col v-if="label" :cols="labelCols">
			<label for="" class="search-box-label">
				<v-icon v-if="iconShow" small color="primary" 
				:class="['mr-1', required ? 'icon-orange' : 'icon-blue']"
				>$icoBulletPoint</v-icon>
				{{ label }}
			</label>
		</v-col>
		<v-col :cols="label ? textCols : ''">
			<div :class="['datepicker-container', customClass]"  >
				<v-text-field
					id="startpicker"
					ref="startpicker"
					v-model="fromDtValue"
					:class="isRange ? 'v-input__custom half' : 'v-input__custom'"
					:hide-details="true"
					readonly
					outlined
				>
					<!-- <template #append >
						<v-icon size="20" v-show="!isRange">$icoCalendar</v-icon>
					</template> -->
					<template v-slot:append>
						<a-icon class="v-icon" type="calendar" style="width: 14px; height: 14px;" />
					</template>
					<template #append-outer>
						<div ref="startpicker-container" id="startpicker-container"></div>
					</template>
				</v-text-field>
				<div v-if="isRange" class="mx-3" :style="{ lineHeight: 0 }">
					<img :src="arrowIcon" alt="">
				</div>
				<v-text-field
					v-show="isRange"
					id="endpicker"
					ref="endpicker"
					v-model="toDtValue"
					:class="isRange ? 'v-input__custom half' : 'v-input__custom'"
					:hide-details="true"
					readonly
					outlined
				>
					<template #append>
						<v-icon size="20" class="icon-datepicker-color" style="color: red;">$icoCalendar</v-icon>
					</template>
					<template #append-outer>
						<div ref="endpicker-container" id="endpicker-container" class="icon-datepicker-color"></div>
					</template>
				</v-text-field>
			</div>
		</v-col>
	</v-row>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import TuiDatepicker from 'tui-date-picker';
import Utility from '~/plugins/utility';
export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		label: {
			type: String,
			require: false,
		},
		timePicker: {
			type: Boolean,
			require: false,
			default: false,
		},
		labelCols: {
			type: Number,
			require: false,
			default: 12,
		},
		textCols: {
			type: Number,
			require: false,
			default: 12,
		},
		required: {
			type: Boolean,
			require: false,
			default: false,
		},
		iconShow: {
			type: Boolean,
			require: false,
			default: true,
		},
		isRangeOption:{
			type:Boolean,
			require:false,
			default: true
		},
		customClass: {
			type: String,
			require: false,
		},

	},
	data() {
		return {
			today: new Date(),
			startDatepickerInstance: null,
			endDatepickerInstance: null,
			startDtValue: null,
			endDtValue: null,
			cmCycleFlag: false,
		};
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: "isDarkMode",
		}),
		myCmCycle() {
			return this.searchParam.cmCycle;
		},
		myOptions() {
			let returnObj = {};
			switch (this.myCmCycle) {
				case 'CYC_YEAR':
					returnObj = {
						type: 'year',
						viewFormat: 'YYYY',
						pickerFormat: 'YYYY',
						sendFormat: 'YYYY',
					};
					break;

				case 'CYC_MONTH':
					returnObj = {
						type: 'month',
						viewFormat: 'YYYY-MM',
						pickerFormat: 'YYYY-MM',
						sendFormat: 'YYYYMM',
					};
					break;

				case 'CYC_DAY':
					returnObj = {
						type: 'date',
						viewFormat: 'YYYY-MM-DD',
						pickerFormat: 'yyyy-MM-dd',
						sendFormat: 'YYYYMMDD',
					};
					break;

				case 'CYC_HOUR':
					returnObj = {
						type: 'date',
						viewFormat: 'YYYY-MM-DD' + (this.timePicker ? ' HH:mm:ss' : ''),
						pickerFormat: 'yyyy-MM-dd' + (this.timePicker ? ' HH:mm A' : ''),
						sendFormat: this.timePicker ? 'YYYY-MM-DD HH:mm:ss' : 'YYYYMMDD',
					};
					// returnObj = { type: "day", format: "YYYY-MM-DD HH:mm:ss" };
					break;

				default:
					break;
			}
			return returnObj;
		},
		// maxDate() {
		//   return Utility.setFormatDate("today", this.myOptions.format);
		// },
		fromDtValue() {
			return Utility.setFormatDate(
				this.searchParam.fromDt,
				this.myOptions.viewFormat,
			);
		},
		toDtValue() {
			return Utility.setFormatDate(
				this.searchParam.toDt,
				this.myOptions.viewFormat,
			);
		},
		toDtChange(){
			return {
				isCheck:this.searchParam.isCheck ,
				toDt : Utility.setFormatDate(
				this.searchParam.toDt,
				this.myOptions.viewFormat,
			)};
		},
		fromDtChange(){
			return {
				isCheck:this.searchParam.isCheck ,
				fromDt : Utility.setFormatDate(
					this.searchParam.fromDt,
					this.myOptions.viewFormat,
			)};
		},
		defaultRange() {
			return this.searchParam.defaultRange
				? this.searchParam.defaultRange[this.myCmCycle]
				: null;
		},
		isRange() {
			return (
				(this.defaultRange !== null && this.defaultRange > 0 && this.isRangeOption) ||
				this.defaultRange === 'no limite'
			);
		},
		arrowIcon() {
			if(this.isDarkMode){
				return require('@/assets/images/arrow_datepicker_dm.png');
			}
			return require('@/assets/images/arrow_datepicker.png');
		}
	},
	watch: {
		myCmCycle() {
			this.cmCycleFlag = false;
			this.startDatepickerInstance.setDate(new Date(this.fromDtValue));
			this.startDatepickerInstance.setType(this.myOptions.type);
			this.endDatepickerInstance.setType(this.myOptions.type);
		},
		fromDtValue(newVal, oldVal) {
			if (
				this.isRange &&
				this.defaultRange !== 'no limite' &&
				newVal !== 'Invalid Date' &&
				newVal !== oldVal
			) {
				this.toDtValueChkRang(newVal);
				this.startDatepickerInstance.setDate(new Date(newVal));
			} else {
				this.setPageData({ isFind: true });
			}
		},
		toDtValue(newVal, oldVal) {
			if (
				this.isRange &&
				this.defaultRange !== 'no limite' &&
				newVal !== 'Invalid Date' &&
				newVal !== oldVal
			) {
				this.fromDtValueChkRang(newVal);
				this.endDatepickerInstance.setDate(new Date(newVal));
			}
		},
		fromDtChange:{
			deep:true,
			handler(){
				if(this.fromDtChange.isCheck){
					this.fromDtChanged(this.fromDtChange.fromDt);
					this.setPageData({
						isCheck : false
					})
				}
			}
		},
		toDtChange:{
			deep:true,
			handler(){
				if(this.toDtChange.isCheck){
					this.toDtChanged(this.toDtChange.toDt);
					this.setPageData({
						isCheck : false
					})
				}
			}
		}
	},
	created() {
		if (this.timePicker) {
			this.setPageData({
				fromDt: Utility.setFormatDate(this.today, 'YYYY-MM-DD') + ' 00:00:00',
				toDt: Utility.setFormatDate(this.today, 'YYYY-MM-DD') + ' 23:59:59',
			});
		}
	},
	mounted() {
		const startContainer = document.getElementById('startpicker-container');
		// const startContainer = document.getElementById('datepicker-container');
		const startTarget = document.getElementById('startpicker');
		const endContainer = document.getElementById('endpicker-container');
		// const endContainer = document.getElementById('datepicker-container');
		const endTarget = document.getElementById('endpicker');

		// datepicker 생성
		this.startDatepickerInstance = new TuiDatepicker(startContainer, {
			date: this.today,
			language: 'ko',
			type: this.myOptions.type, // "date", // type: date || month || year
			input: {
				element: startTarget,
				format: this.myOptions.pickerFormat, //"YYYY-MM-DD" //this.format
			},
			timePicker: this.timePicker,
			calendar: {
				showToday: false,
			},
		});
		// datepicker 생성
		this.endDatepickerInstance = new TuiDatepicker(endContainer, {
			date: this.today,
			language: 'ko',
			type: this.myOptions.type, // "date", // type: date || month || year
			input: {
				element: endTarget,
				format: this.myOptions.pickerFormat, //"YYYY-MM-DD" //this.format
			},
			timePicker: this.timePicker,
			calendar: {
				showToday: false,
			},
		});
		// datepicker 생성 끝

		// datepicker 초기값 생성
		this.startDatepickerInstance.setDate(new Date(this.fromDtValue));
		// datepicker 초기값 생성 끝

		// datepicker 변경시 이벤트 추가
		this.startDatepickerInstance.on('change', () => this.getStartDt());
		this.endDatepickerInstance.on('change', () => this.getEndDt());
		// datepicker 이벤트는 mount 될때 추가 해주어야 한다.
	},
	methods: {
		...mapMutations({ setPageData: 'setPageData' }),
		onOpenDatepicker() {
			this.startDatepickerInstance.open();
			this.endDatepickerInstance.open();
		},
		getStartDt() {
			const dt = this.startDatepickerInstance.getDate();
			this.setPageData({
				fromDt: Utility.setFormatDate(dt, this.myOptions.sendFormat),
			});
		},
		getEndDt() {
			const dt = this.endDatepickerInstance.getDate();
			this.setPageData({
				toDt: Utility.setFormatDate(dt, this.myOptions.sendFormat),
			});
		},
		toDtChanged(newVal, oldVal) {
			if (
				this.isRange &&
				this.defaultRange !== 'no limite' &&
				newVal !== 'Invalid Date' &&
				newVal !== oldVal
			) {
				this.fromDtValueChkRang(newVal);
				this.endDatepickerInstance.setDate(new Date(newVal));
			}
		},
		fromDtChanged(newVal, oldVal) {
			if (
				this.isRange &&
				this.defaultRange !== 'no limite' &&
				newVal !== 'Invalid Date' &&
				newVal !== oldVal
			) {
				this.toDtValueChkRang(newVal);
				this.startDatepickerInstance.setDate(new Date(newVal));
			} else {
				this.setPageData({ isFind: true });
			}
		},
		fromDtValueChkRang(newDt) {
			const defaultDt = this.$dayjs(this.fromDtValue);
			const compareDt = this.$dayjs(newDt);
			const newDefault = Utility.setNewDefaultRange(
				this.myCmCycle,
				this.defaultRange,
			);
			const myRange = newDefault.range;
			const rangeKey = newDefault.key;
			const rangeGap = compareDt.diff(defaultDt, rangeKey);

			if (
				(myRange > rangeGap && compareDt.isAfter(defaultDt)) ||
				defaultDt.format(this.myOptions.sendFormat) ===
					compareDt.format(this.myOptions.sendFormat)
			) {
				// if(this.cmCycleFlag){
				this.setPageData({ isFind: true });
				// }
				// this.cmCycleFlag = true;
			} else {
				this.setPageData({
					fromDt: Utility.setBeforetDate(
						this.searchParam,
						compareDt,
						this.myOptions.sendFormat,
					),
				});
			}
		},
		toDtValueChkRang(newDt) {
			const defaultDt = this.$dayjs(this.toDtValue);
			const compareDt = this.$dayjs(newDt);
			const newDefault = Utility.setNewDefaultRange(
				this.myCmCycle,
				this.defaultRange,
			);
			const myRange = newDefault.range;
			const rangeKey = newDefault.key;
			const rangeGap = defaultDt.diff(compareDt, rangeKey);

			if (
				(myRange > rangeGap && defaultDt.isAfter(compareDt)) ||
				defaultDt.format(this.myOptions.sendFormat) ===
					compareDt.format(this.myOptions.sendFormat)
			) {
				this.setPageData({ isFind: true });
			} else {
				this.setPageData({
					toDt: Utility.setAftertDate(
						this.searchParam,
						compareDt,
						this.myOptions.sendFormat,
					),
				});
			}
		},
	},
};
</script>
<style lang="scss" scoped>
// @import "@/assets/scss/datepicker.scss";

::v-deep {
	.tui-timepicker-row {
		display: flex;
		justify-content: space-around;
		background-color: #edf4fc;
		.tui-timepicker-column.tui-timepicker-colon {
			color: #000 !important;
		}
	}
}
</style>
