<template>
	<div ref="mainDiv" class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="center" no-gutters>
						<v-col :cols="2">
							<component
								:is="'SelectBox'"
								ref="SelectBox1"
								:propsValue="selectValue01"
								:itemList="selectValueList01"
								:label="'Fab'"
								@update:propsValue="selectValue01 = $event"
							/>
						</v-col>
						<v-col :cols="2">
							<component
								:is="'SelectBox'"
								ref="SelectBox2"
								:propsValue="selectValue02"
								:itemList="selectValueList02"
								:label="'설비종류'"
								@update:propsValue="selectValue02 = $event"
							/>
						</v-col>
						<v-col :cols="2">
							<component
								:is="'SelectBox'"
								ref="SelectBox3"
								:propsValue="selectValue03"
								:itemList="selectValueList03"
								:label="'설비그룹'"
								@update:propsValue="selectValue03 = $event"
							/>
						</v-col>
						<v-col :cols="2">
							<component 
								:is="'SelectCmCycle'" 
								:parentPrgmId="myPrgmId" 
								:label="'구분'"
							/>
						</v-col>
						<v-col :cols="2">
							<component
								:is="'DatePicker'"
								:label="'대상년월'"
								:parentPrgmId="myPrgmId"
								:isRangeOption="false"
							/>
						</v-col>
						<v-col :cols="2" class="text-right">
							<v-btn :ripple="false" @click="search()">조회</v-btn>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>		
		<v-row ref="contents" style="height: calc(100vh - 230px)">
			<v-col :cols="12" class="">
				<v-card class="pb-5 px-2">
					<v-card-title class="d-flex align-center justify-space-between pa-5">
						<span class="tit ft-size_20 ft-weight_600">설비별 현황 리스트</span>
					</v-card-title>
					<div class="px-5" style="height:calc(100% - 106px)">
						<div ref="gridParent" class="w100 h100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								@dblClick="gridDoubleClickEvent"
							/>
							<!--
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								:mouseoverEvent="gridMouseoverEvent"
								:mouseoutEvent="gridMouseoutEvent"
								@dblClick="gridDoubleClickEvent"
							/>
							-->
						</div>
					</div>
				</v-card>
			</v-col>
		</v-row>
		<!--<v-tooltip
			top
			v-model="tooltipData.show"
			:position-x="tooltipData.x" 
			:position-y="tooltipData.y"
			:z-index="1000"
		>
		{{tooltipData.content}}
		</v-tooltip> -->
	</div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import Utility from '~/plugins/utility';
import SelectBox from '@/components/common/select/SelectBox';
import SelectCmCycle from '@/components/common/select/SelectCmCycle';
import DatePicker from '@/components/common/Datepicker';
import Grid from '~/components/common/Grid';

let myTitle;
let myPrgmId;
let paramKey;

export default {
	mixins: [mixinGlobal],
	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: {
		Utility,
		SelectBox,
		SelectCmCycle,
		DatePicker,
		Grid,
	},
	data() {
		return {
			myPrgmId: myPrgmId,

			initedFlag:false,
			queryParams: null,

			selectValueList01: [],
			selectValueList02: [],
			selectValueList03: [],

			selectValue01:null,
			selectValue02:null,
			selectValue03:null,

			loadGrid:false,
			gridName:'grid01',

			enrgUseMainIdxDesc:[],
			
			// tooltipData:{
			// 	show:false,
			// 	x:0,
			// 	y:0,
			// 	content:null
			// },
		};
	},
	computed:{
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		fromDt(){
			return this.pageData.fromDt;
		}		
	},
	watch:{
		async $route(to, from){
			if(to.query.prgmId == myPrgmId){
				if(to.params.key){
					document.getElementById('refresh').click();
				}
			}
		},
		async selectValue01(value){
			if(this.initedFlag){
				await this.search();
			}
		},
		async selectValue02(value){
			if(this.initedFlag){
				await this.getSelectValueList03();
			}
		},
		async selectValue03(value){
			if(this.initedFlag){
				await this.search();
			}			
		},
		async fromDt(value){
			if(this.initedFlag){
				await this.search();
			}
		}
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.initedFlag = false;
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		async init(){
			await this.getSelectValueList();
			await this.setQueryParams();
			this.gridInit();
			await this.getGridData();

			this.initedFlag = true;
		},
		async setQueryParams(){
			this.queryParams = null;

			if(paramKey==this.$route.params.key){
				return;
			}

			if(this.$route.params.key){
				paramKey = this.$route.params.key;
				this.queryParams = this.$route.params;
			}

			if(this.queryParams && typeof(this.queryParams)=='object'){
				this.selectValue01 = this.queryParams['fabId'];
				this.selectValue02 = this.queryParams['eqpmKindId'];
				await this.getSelectValueList03();
				this.selectValue03 = this.queryParams['eqpmGrpId'];
			}
		},
		async getSelectValueList(){
			await this.getSelectValueList01();
			await this.getSelectValueList02();
			await this.getSelectValueList03();
		},
		async getSelectValueList01(){
			let res = await this.postApiReturn({
				apiKey: 'selectFabCodeList',
				resKey: 'fabCodeLists',
				sendParam: {},
			});
			if (res.length > 0) {
				this.selectValueList01 = await res.map(item => {
					return {
						text: item.eccNm,
						value: item.eccId,
					};
				});
				this.selectValue01 = this.selectValueList01[0].value;
			} else {
				this.selectValueList01 = [];
				this.selectValue01 = null;
			}
		},
		async getSelectValueList02(){
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmKindList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {},
			});

			if (res.length > 0) {
				this.selectValueList02 = await res.map(item => {
					return {
						text: item.eqpmKindNm,
						value: item.eqpmKindId,
						data: {
							...item,
						},
					};
				});
				this.selectValue02 = this.selectValueList02[0].value;
			} else {
				this.selectValueList02 = [];
				this.selectValue02 = null;
			}
		},
		async getSelectValueList03(){
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmGrpList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {
					eqpmKindId: this.selectValue02,
				},
			});

			if (res.length > 0) {
				this.selectValueList03 = await res.map(item => {
					return {
						text: item.eqpmGrpNm,
						value: item.eqpmGrpId,
						data: {
							...item,
						},
					};
				});
				this.selectValue03 = this.selectValueList03[0].value;
			} else {
				this.selectValueList03 = [];
				this.selectValue03 = null;
			}
		},
		gridInit(){
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			const _this = this;
			var columnList = [
				{header:'NO', name:'no', align:'center'},
				{header:'fabId', name:'fabId', hidden:true},
				{header:'FAB', name:'fabNm', align:'left'},
				{header:'eqpmGrpId', name:'eqpmGrpId', hidden:true},
				{header:'설비그룹', name:'eqpmGrpNm', align:'left'},
				{header:'eqpmId', name:'eqpmId', hidden:true},
				{header:'설비명', name:'eqpmNm', align:'left'},
				{header:'계획량', name:'planVal', align:'right'},
				{header:'사용량', name:'usedVal', align:'right'},
				{header:'KPI', name:'effcRt', align:'right'},
				{header:'지표1', name:'gd01', align:'right'},
				{header:'지표2', name:'gd02', align:'right'},
				{header:'지표3', name:'gd03', align:'right'},
				{header:'지표4', name:'gd04', align:'right'},
				{header:'지표5', name:'gd05', align:'right'},
				{header:'지표6', name:'gd06', align:'right'},
				{header:'지표7', name:'gd07', align:'right'},
				{header:'지표8', name:'gd08', align:'right'},
				{header:'지표9', name:'gd09', align:'right'},
				{header:'지표10', name:'gd10', align:'right'},
			];
			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				header:{
					height:65,
					complexColumns:[
						{
							header:'주요지표',
							name:'complexColumn01',
							childNames:[
								'gd01',
								'gd02',
								'gd03',
								'gd04',
								'gd05',
								'gd06',
								'gd07',
								'gd08',
								'gd09',
								'gd10',
							]
						}
					]
				}
			};

			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			this.setGridColumn({
				gridKey: this.gridName,
				value: columnList,
			});			
		},
		async getGridData(){
			this.loadGrid = false;
			this.enrgUseMainIdxDesc = [];
			var apiKey = null;
			var params = {
				fabId:this.selectValue01,
				eqpmKindId:this.selectValue02,
				eqpmGrpId:this.selectValue03,
				fromDt:this.pageData.fromDt
			};

			if(this.pageData.cmCycle=='CYC_DAY'){
				params['fromDtMm'] = String(this.pageData.fromDt).substring(0, 6);
				apiKey = 'selectDailyEnrgUseMainIdx';
			}else if(this.pageData.cmCycle=='CYC_MONTH'){
				apiKey = 'selectMonthlyEnrgUseMainIdx';
			}

			var res = await this.postApiReturn({
				apiKey: apiKey,
				resKey: 'eqpmIndMntrData',
				sendParam: params,
			});


			this.enrgUseMainIdxDesc = await this.getEnrgUseMainIdxDesc();
			// this.enrgUseMainIdxDesc = await this.postApiReturn({
			// 	apiKey: 'selectEnrgUseMainIdxDesc',
			// 	resKey: 'eqpmIndMntrData',
			// 	sendParam: {
			// 		eqpmGrpId:this.selectValue03
			// 	},
			// });

			var newRes = [];

			for(var i=0; i<res.length; i++){
				newRes.push({
					...res[i],
					'no':(i+1)
				});
			}

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

			this.loadGrid = true;

			this.makeTooltip();
		},
		async getEnrgUseMainIdxDesc(){
			var res = await this.postApiReturn({
				apiKey: 'selectEnrgUseMainIdxDesc',
				resKey: 'eqpmIndMntrData',
				sendParam: {
					eqpmGrpId:this.selectValue03
				},
			});

			while(res.length < 10){
				res.push({
				});
			}

			return res;
		},
		async search(){
			await this.getGridData();
		},
		async makeTooltip(){
			var gdIdxList = ['gd01', 'gd02', 'gd03', 'gd04', 'gd05', 'gd06', 'gd07', 'gd08', 'gd09', 'gd10'];
			var elementList = [];

			await new Promise(resolve => setTimeout(resolve, 1000));

			for(var i=0; i<gdIdxList.length; i++){
				var selector = '.tui-grid-cell-header[data-column-name="'+gdIdxList[i]+'"]';
				var tempElement = document.querySelector(selector);
				elementList.push(tempElement);
			}

			for(var i=0; i<elementList.length; i++){
				var columnElement = document.createElement('span');
				var tooltipElement = document.createElement('div');
				// var tooltipContent = this.enrgUseMainIdxDesc[i].gdIdxNm != undefined ? this.enrgUseMainIdxDesc[i].gdIdxNm : '지표에 대한 정보가 없습니다.';
				var tooltipContent = this.enrgUseMainIdxDesc[i].gdIdxNm != undefined ? this.enrgUseMainIdxDesc[i].gdIdxNm : '지표';

				console.log('this.enrgUseMainIdxDesc : ', this.enrgUseMainIdxDesc);
				console.log('tooltipContent[' + i + '] : ', tooltipContent );

				// textContent 세팅
				columnElement.textContent = elementList[i].textContent;
				elementList[i].textContent = '';
				tooltipElement.textContent = tooltipContent;
				// tooltipElement.textContent = this.enrgUseMainIdxDesc[i].gdIdxNm;

				// id값 설정
				columnElement.id = 'tooltipTargetElement_'+i;
				tooltipElement.id =  'tooltipElement_'+i;
				
				// element 추가
				elementList[i].append(columnElement);
				elementList[i].append(tooltipElement);
			}
			
		},
		// gridMouseoverEvent(e){
		// 	if(e.targetType=='columnHeader'){
		// 		if(String(e.columnName).search('gd')>=0){
		// 			this.tooltipData.content = null;
		// 			var element = document.querySelector('.tui-grid-cell-header[data-column-name="'+e.columnName+'"]');
		// 			var boundingClientRect = element.getBoundingClientRect();

		// 			this.tooltipData.x = (boundingClientRect.right + boundingClientRect.left)/2;
		// 			this.tooltipData.y = boundingClientRect.top;

		// 			for(var i=0; i<this.enrgUseMainIdxDesc.length; i++){
		// 				if(this.enrgUseMainIdxDesc[i].gdSeq == String(e.columnName).toUpperCase()){
		// 					this.tooltipData.content = this.enrgUseMainIdxDesc[i].gdIdxNm;
		// 				}
		// 			}
					
		// 			if(this.tooltipData.content==null){
		// 				this.tooltipData.content = '지표에 대한 정보가 없습니다.';
		// 			}

		// 			this.tooltipData.show = true;
		// 		}
		// 	}
		// },
		// gridMouseoutEvent(e){
		// 	if(e.targetType=='columnHeader'){
		// 		this.tooltipData.show = false;
		// 	}
		// },
		gridDoubleClickEvent(_, event, gridName){
			var gridInstance = this.$refs[this.gridName].gridInstance;
			var eventRowData = gridInstance.invoke('getRow', event.rowKey);

			var data = {
				cmCycle : this.pageData.cmCycle,
				fromDt : this.pageData.fromDt,
				fabId:this.selectValue01,
				eqpmKindId:this.selectValue02,
				eqpmGrpId:this.selectValue03,
				eqpmId:eventRowData.eqpmId
			};
			var key = 'tick_' + Math.random();
			this.$router.push({
				name:'ems-effc-EnrgUseEqpmDetlMntrPage',
				query:{
					prgmId:'PRG0082',
					// tick:key
				},
				params:{
					...data,
					key:key
				}
			})

		}
	}
};

const defaultData = {
	cmCycle:'CYC_MONTH',
	cmCycleList: [
		{ idx: 0, text: '월', value: 'CYC_MONTH' },
		{ idx: 1, text: '일', value: 'CYC_DAY' },
	],
	defaultRange: {
		CYC_MONTH: 1,
		CYC_DAY: 1,
	},
	fromDt: Utility.setFormatDate(new Date(), 'YYYYMM'), // 조회 시작일

	grid01:{
		data: [],
		column: [],
		option: {},		
	}
}
</script>
<style lang="scss" scoped>
// #tooltipTargetElement_0:hover + #tooltipElement_0{
// 	display : block
// }
// #tooltipElement_0{
// 	display : none
// }

@for $i from 0 through 9{
	#tooltipTargetElement_#{$i}:hover + #tooltipElement_#{$i}{
		display : block
	}
	#tooltipElement_#{$i}{
		display : none
	}
}
</style>