<template>
	<div class="l-layout">
		<common-page-title />
		<v-row ref="searchFilter" class="mt-2">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="end" no-gutters>
						<v-col cols="3">
							<component :is="'SelectBlocMstr'" :parentPrgmId="myPrgmId" :sendParam="{ comId }"
								:labelCols="12" :textCols="12" :customClass="'select-large'" />
						</v-col>
						<v-col cols="3">
							<!-- <component :is="'SelectDateSolo'" :parentPrgmId="myPrgmId" /> -->
							<DatePicker :parentPrgmId="myPrgmId" :label="'조회연월'" />
						</v-col>
						<v-col cols="6" class="text-right">
							<BtnSearch @click="search()" size="large" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" id="CalendarMngContent" class="mt-4">
			<v-col cols="12" lg="4" class=" pr-2">
				<v-card class="w100">
					<v-card-title class="d-flex justify-space-between align-center">
						<span class="custom-title-4">캘린더 리스트</span>
						<Buttons :parentPrgmId="myPrgmId" :bindingData="gridName" :btnActionsFnc="btnActions" />
					</v-card-title>
					<v-card-actions class="pt-0 px-5 pb-5" :style="{ height: 'calc(100% - 10px)' }">
						<div ref="gridParent" class="w100 h100">
							<component class="w100" :ref="gridName + myPrgmId" :is="loadGrid ? 'Grid' : null"
								:gridName="gridName" :parentPrgmId="myPrgmId" :editorGrid="true"
								@getRowsData="getRowData" />
						</div>
					</v-card-actions>
				</v-card>
			</v-col>
			<v-col cols="12" lg="8" class=" pl-3">
				<v-card>
					<v-card-title>
						<span class="custom-title-4">캘린더 미리보기</span>
					</v-card-title>
					<v-card-actions class="px-5 d-block" >
						<Calendar :parentPrgmId="myPrgmId" :gridName="gridName" :headerVisible="false"
							:showTitle="false" />
					</v-card-actions>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import { mapState, mapMutations, mapActions } from 'vuex';
import Utility from '~/plugins/utility';
import Grid from '~/components/common/Grid';
import Buttons from '~/components/common/button/Buttons';
import BtnSearch from '~/components/common/button/BtnSearch';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
// import SelectDateSolo from "@/components/common/select/SelectDateSolo";
import InputText from '@/components/common/input/InputText';
import Calendar from '~/components/common/Calendar';
import DatePicker from '~/components/common/Datepicker';

let myTitle;
// const myPrgmId = "PRG0008";
let myPrgmId;
export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		myPrgmId = context.route.query.prgmId;
		await context.store.commit('setActiveMenuInfo', myState.menuData[myPrgmId]);
		myTitle = await myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		Grid,
		Buttons,
		SelectBlocMstr,
		// SelectDateSolo,
		InputText,
		Calendar,
		DatePicker,
		BtnSearch
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			rowKey: null,
			edtingFinishFlag: 'Y',
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkBlocCd() {
			// 사업장 선택 감지
			return this.pageData.blocId;
		},
		chkFromDt() {
			// 사업장 선택 감지
			return this.pageData.fromDt;
		},
		initFlag() {
			if (this.pageData.blocMstrList.length > 0) {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkBlocCd() {
			this.setPageData({ isFind: true });
		},
		chkFromDt() {
			this.setPageData({ isFind: true });
		},
		initFlag(val) {
			if (val) {
				this.init();
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() { },
	mounted() { },
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		async init() {
			await this.gridInit();
		},
		async search() {
			await this.getRowGridData();
		},
		async gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), {
					scrollX: false, header: {
						height: 37,
					},
					rowHeight: 37,
				}),
			});

			// this.getRowGridData();
		},
		// 메뉴리스트 조회
		async getRowGridData() {
			class CustomSelectBoxEditor {
				constructor(props) {
					const el = document.createElement('select');
					const option1 = document.createElement('option');
					const option2 = document.createElement('option');

					console.log('props : ', props);

					option1.value = '1';
					option2.value = '0';

					option1.text = '휴일';
					option2.text = '평일';

					option1.classList.add('calendarOption');
					option2.classList.add('calendarOption');
					el.classList.add('selectbox');

					el.id = 'calendarSelect';
					// el.size = 2;
					el.appendChild(option1);
					el.appendChild(option2);

					// el.options.add(option2);

					console.log('props.value : ', props.value);

					document
						.querySelector('#CalendarMngContent')
						.addEventListener('click', function (event) {
							if (event.target.className == 'calendarOption') {
								// el.size = 1;
							}
						});
					el.value = props.value;
					this.el = el;
				}

				getElement() {
					return this.el;
				}

				getValue() {
					return this.el.value;
				}

				mounted() {
					// this.el.focus();
				}
			}

			const myColumns = [
				{
					header: '일자',
					name: 'dt',
					align: 'center',
					formatter({ value }) {
						return value.split(' ')[0];
					},
				},
				{
					header: '요일',
					name: 'dtNm',
					align: 'center',
					formatter({ value }) {
						return value + '요일';
					},
				},
				{
					header: '구분',
					name: 'hldyFg',
					align: 'center',
					essential: true,
					formatter({ value }) {
						return value == 1 ? '휴일' : '평일';
					},
					editor: {
						type: CustomSelectBoxEditor,
					},
					// editor: {
					// 	type: 'select',
					// 	options: {
					// 		listItems: [
					// 			{ text: '휴일', value: '1' },
					// 			{ text: '평일', value: '0' },
					// 		],
					// 	},
					// },
				},
				{ header: '휴일명', name: 'hldyNm', editor: 'text' },
			];

			this.loadGrid = false;

			let res = await this.postApiReturn({
				apiKey: 'selectWorkCald',
				resKey: 'workcaldData',
				sendParam: {
					blocId: this.pageData.blocMstrList[this.chkBlocCd].blocId,
					yymm: this.chkFromDt,
					comId: this.comId,
				},
			});

			let res2 = await this.postApiReturn({
				apiKey: 'selectWorkCaldDetl',
				resKey: 'workcaldDetlData',
				sendParam: {
					blocId: this.pageData.blocMstrList[this.chkBlocCd].blocId,
					yymm: this.chkFromDt,
					comId: this.comId,
				},
			});

			for (var i = 0; i < res2.length; i++) {
				if (
					!(
						res2[i].hldyNm == null ||
						res2[i].hldyNm == '토요일' ||
						res2[i].hldyNm == '일요일'
					)
				) {
					for (var j = i + 1; j < res2.length; j++) {
						if (res2[i].hldyNm == res2[j].hldyNm) {
							res2[i].hldyNm = '';
						}
					}
				}
			}

			res = res.map(item => {
				const dt = this.$dayjs(item.dt.split(' ')[0]); // YYYY-MM-DD
				const dtNm = dt.format('ddd'); // 요일
				const newItem = {
					...item,
					dtNm: dtNm,
					hldyNm: item.hldyNm ? item.hldyNm : '',
					rowStat: null,
				};
				return newItem;
			});

			this.loadGrid = true;
			this.setPageData({ isFind: false });

			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			this.setGridData({
				gridKey: this.gridName,
				value: res,
			});

			this.setPageData({ planData: res2 });

			// 첫번째 row 선택상태
			this.$nextTick(() => {
				this.$refs[this.gridName + this.myPrgmId].focus({
					//rowKey: 0,
					rowKey:
						this.pageData.rowGridSelectKey == '' ||
							this.pageData.rowGridSelectKey == null
							? 0
							: this.pageData.rowGridSelectKey ==
								this.$refs[this.gridName + this.myPrgmId].getData().length - 1
								? this.pageData.rowGridSelectKey
								: 0,
					columnName: 'dt',
					setScroll: true,
				});
				this.setPageData({ isFind: false });
			});
		},
		async getRowData(data, gridName) {
			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});

			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});

			this.rowKey = data.rowKey;
			this.edtingFinishFlag = 'Y';
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName + this.myPrgmId].addRow();
					this.edtingFinishFlag = 'Y';
					break;

				case 'remove':
					await this.$refs[this.gridName + this.myPrgmId].editingFinish({
						rowKey: this.rowKey,
					});
					this.$refs[this.gridName + this.myPrgmId].removeRow();
					this.edtingFinishFlag = 'N';
					break;

				case 'save':
					if (this.edtingFinishFlag == 'Y') {
						await this.$refs[this.gridName + this.myPrgmId].editingFinish({
							rowKey: this.rowKey,
						});
					}
					dataArr = this.$refs[this.gridName + this.myPrgmId].save();
					dataArr = dataArr.map(item => {
						const dt = item.dt.substr(0, 10);
						const newItem = {
							...item,
							dt: dt,
						};
						return newItem;
					});
					if (dataArr.length > 0) {
						const sendParam = {
							datas: { dsWorkcald: dataArr },
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveWorkCald',
							sendParam: sendParam,
						});
						this.setPageData({ isFind: true });
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
	},
};
const dt = new Date();
const yy = dt.getFullYear();
const mm = dt.getMonth() + 1;

const defaultData = {
	isFind: false, // true 경우 조회

	/* 검색옵션 */
	blocId: '',
	blocMstrList: [],

	cmCycle: 'CYC_MONTH',
	fromDt: `${yy}${mm}`,
	planData: [],
	// 선택된 그룹코드 상세 데이터
	rowGridSelectKey: 0,
	rowGridSelectData: {},

	/* data 세팅 */
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			dt: null,
			dtNm: null,
			hldyFg: 1,
			hldyNm: null,
			rowStat: null,
		},
		rowGridSelectKey: 0,
		rowGridSelectData: {},
		buttonAuth: {
			add: false,
			remove: false,
			save: true,
			excel: false,
		},
	},
};
</script>
<style lang="scss" scoped>
.selectbox:focus {
	outline: none;
}

.calendarOption {
	box-sizing: border-box;
	position: relative;
	width: 100%;
	height: 100%;
	padding: 0;
	margin: 0;
}

select.selectbox {
	box-sizing: border-box;
	position: relative;
	width: 100%;
	height: 100%;
	/* 높이 초기화 */
	padding: 0;
	margin: 0;
	line-height: normal;
	/* line-height 초기화 */
	font-family: inherit;
	/* 폰트 상속 */
	border: 0;
	// opacity: 0;  /* 숨기기 */
	// filter:alpha(opacity=0);  /* IE8 숨기기 */
	// -webkit-appearance: none; /* 네이티브 외형 감추기 */
	// -moz-appearance: none;
	// appearance: none;
	opacity: 1;
	/* 숨기기 */
	filter: alpha(opacity=1);
	/* IE8 숨기기 */
	-webkit-appearance: auto;
	/* 네이티브 외형 감추기 */
	-moz-appearance: auto;
	appearance: auto;
}

.tui-grid-layer-editing {
	position: absolute;
	background: #fff;
	// background-image: initial;
	// background-position-x: initial;
	// background-position-y: initial;
	// background-size: initial;
	// background-repeat-x: initial;
	// background-repeat-y: initial;
	// background-attachment: initial;
	// background-origin: initial;
	// background-clip: initial;
	// background-color: rgb(255, 255, 255);
	// z-index: 15;
	padding: 0;
	margin: 0;
	/* border-style: solid; */
	/* border-width: 1px; */
	white-space: nowrap;
	border-width: 0px;
	// box-sizing: border-box;
}

::v-deep {
	.custom-vc-calender {
		.vc-header {
			display: none;
		}

		.vc-weeks {
			padding: 0;
		}

	}
}
</style>
