<template>
	<div ref="mainDiv" class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="end" no-gutters>
						<v-col :cols="2.5">
							<DatePicker :parentPrgmId="myPrgmId" :label="'조회연도'" />
						</v-col>
						<v-col :cols="2.5">
							<component :is="'SelectBox'" ref="SelectBox1" :propsValue="selectValue01" :itemList="selectValueList01"
								:label="'FAB'" @update:propsValue="selectValue01 = $event" :iconShow="false" />
						</v-col>
						<v-col :cols="2.5">
							<component :is="'SelectBox'" ref="SelectBox2" :propsValue="selectValue02" :itemList="selectValueList02"
								:label="'설비종류'" @update:propsValue="selectValue02 = $event" :iconShow="false" />
						</v-col>
						<v-col :cols="2.5">
							<component :is="'SelectBox'" ref="SelectBox3" :propsValue="selectValue03" :itemList="selectValueList03"
								:label="'설비그룹'" @update:propsValue="selectValue03 = $event" :iconShow="false" />
						</v-col>

						<BtnSearch @click="search" />
						<v-col>
						</v-col>
						<component ref="EnrgUsePlanModiPop" :is="'EnrgUsePlanModiPop'" :label="'test'" :parentPrgmId="myPrgmId"
							@gridEditingFinish="gridEditingFinish" />
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12" style="height: 100%">
				<v-card class="pb-5 h100">
					<div class="d-flex align-center justify-space-between pa-4">
						<v-card-title class="pa-0 custom-title-4">설비별 에너지 계획 리스트</v-card-title>
						<Buttons :parentPrgmId="myPrgmId" :bindingData="gridName" :btnActionsFnc="btnActions" />
					</div>
					<div class="h100 px-5" style="height:calc(100% - 70px)">
						<div ref="gridParent" class="w100 h100">
							<component :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName" :parentPrgmId="myPrgmId"
								:editorGrid="true" @getRowsData="getRowData" :dataPath="dataPathMock" />

						</div>
					</div>
				</v-card>
			</v-col>
		</v-row>


	</div>
</template>
<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import SelectBox from '@/components/common/select/SelectBox';
import BtnSearch from '~/components/common/button/BtnSearch';
import DatePicker from '~/components/common/Datepicker';
import Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import Buttons from '~/components/common/button/Buttons';
import EnrgUsePlanModiPop from '~/components/common/modal/EnrgUsePlanModiPop';
import DateUtility from '~/plugins/dateUtility';

let myTitle;
let myPrgmId;
let stateOfDarkMode;

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;
		stateOfDarkMode = await myState.isDarkMode;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		BtnSearch,
		SelectBox,
		DatePicker,
		Grid,
		Buttons,
		EnrgUsePlanModiPop,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			darkModeFg: stateOfDarkMode,
			btnStyleDict: null,
			initedFlag: false,
			loadGrid: false,
			gridName: 'grid01',
			selectValue01: null,
			selectValueList01: [],
			selectValue02: null,
			selectValueList02: [],
			selectValue03: null,
			selectValueList03: [],
			fromDt: new Date().getFullYear(),
			rowKey: null,
			edtingFinishFlag: 'Y',
			dataPathMock: {
				// "grid01": {}
			},
			// gridName: 'rowGrid',
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		...mapState({
			isDarkMode: state => state.isDarkMode,
		}),
		chkIsDarkMode() {
			return this.isDarkMode;
		},
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkFromDt() {
			return this.pageData.fromDt;
		},
	},
	watch: {
		chkIsDarkMode(val) {
			this.darkModeFg = val;
			// this.btnStyleDict = val;
		},
		chkFromDt(val) {
			this.fromDt = val;
		},
		chkIsFind(val) {
			if (val) this.search();
		},
		async selectValue01(val) {
			if (this.initedFlag) {
				this.setPageData({ isFind: true });
			}
		},
		async selectValue02(val) {
			if (this.initedFlag) {
				this.setPageData({ eqpmKindId: val });
				await this.getEqpmGrp();
			}
		},
		async selectValue03(val) {
			if (this.initedFlag) {
				this.setPageData({ isFind: true });
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() { },
	async mounted() {
		// -------
		this.initTest();
		return;
		// ========End test===========
		await this.init();
		this.initedFlag = true;
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapActions({
			getCodeList: 'modules/search/getCodeList',
			getBlocMstrList: 'modules/search/getBlocMstrList',
			getAddInfoList: 'modules/search/getAddInfoList',
		}),
		...mapMutations({
			setPageData: 'setPageData',
		}),
		initTest() {
			let _this = this;
			// _this.setPageData({ popupDialogFg: true });
			
			class MockCustumButton {
				constructor(props) {
					const { grid, rowKey, columnInfo } = props;
					const value = columnInfo.renderer.options.value;
					
					const elDiv = document.createElement('div');
					elDiv.innerHTML = `<span>${value}</span>`;
					$(elDiv).addClass('tui-grid-cell-content d-flex justify-space-between');
					const el = document.createElement('button');
					$(el).addClass('edit-btn blue--text');
					el.innerText = 'Edit';

					el.addEventListener('click', function (event) {
						// console.log("------DEBUG----_this:", _this);
						// _this.setPageData({ eqpmNm: selectedGridData[0]?.eqpmNm });
						_this.setPageData({ popupDialogFg: true });
					});

					elDiv.appendChild(el);
					this.elDiv = elDiv;
				}

				getElement() {
					return this.elDiv;
				}
			}
			const mockData = {
				column: [
					{ header: 'No', name: 'rowNum', align: 'center', width: 40 },
					{ header: 'FAB', name: 'fab', align: 'left', width: 80 },
					{ header: '설비 그룹', name: 'eqpmGrpNm', align: 'left', minWidth: 150 },
					// {
					// 	header: '설비명', name: 'eqpmNm', align: 'left', minWidth: 150,
					// 	formatter: ({ value, row }) => {
					// 		return `
					// 				<div class="d-flex justify-space-between">
					// 					<span>${value}</span>
					// 					<button class="edit-btn blue--text" data-row='${JSON.stringify(row)}'>Edit</button
					// 				</div>
					// 			`;
					// 	}
					// },
					{
						header: '설비명',
						name: 'eqpmNm',
						width: 70,
						align: 'left',
						minWidth: 150,
						renderer: {
							type: MockCustumButton,
							options: {
								value: '계획수정',
							},
						},
					},
					{
						header: '구분', name: 'gubun', align: 'left', width: 80,
						formatter({ value }) {
							let retVal = '';
							if (value == '1RSLT') {
								retVal = '전년실적';
							} else if (value == '2PLAN') {
								retVal = '계획';
							} else {
								retVal = value;
							}
							return retVal;
						},
					},

					{ header: '1월', name: 'jan', align: 'right', width: 80 },
					{ header: '2월', name: 'feb', align: 'right', width: 80 },
					{ header: '3월', name: 'mar', align: 'right', width: 80 },
					{ header: '4월', name: 'apr', align: 'right', width: 80 },
					{ header: '5월', name: 'may', align: 'right', width: 80 },
					{ header: '6월', name: 'jun', align: 'right', width: 80 },
					{ header: '7월', name: 'jul', align: 'right', width: 80 },
					{ header: '8월', name: 'aug', align: 'right', width: 80 },
					{ header: '9월', name: 'sep', align: 'right', width: 80 },
					{ header: '10월', name: 'oct', align: 'right', width: 80 },
					{ header: '11월', name: 'nov', align: 'right', width: 80 },
					{ header: '12월', name: 'dec', align: 'right', width: 80 }
				],
				data: dataPathDataExample,
				defaultRow: dataPathDataExample,
				option: {
					columnOptions: {
						resizable: true,
					},
					header: {
						height: 65,
						complexColumns: [
							{
								header: '2025 년',
								name: 'yyyyCol',
								childNames: [
									'jan', 'feb', 'mar', 'apr', 'may', 'jun',
									'jul', 'aug', 'sep', 'oct', 'nov', 'dec'
								],
							},
						],
					}
				}
			};
			this.dataPathMock[this.gridName] = mockData;
			this.$nextTick(() => {
				this.loadGrid = true;
			});
		},
		async init() {
			await this.getFab();
			await this.getEqpmKind();
			await this.getEqpmGrp();
			await this.gridInit();
		},
		search() {
			// this.gridInit();
			this.getGridData();
			this.setPageData({
				isFind: false,
			});
		},
		async getFab() {
			let res = await this.postApiReturn({
				apiKey: 'selectFabCodeList',
				resKey: 'fabCodeLists',
				sendParam: {},
				// sendParam: {level:3},
			});
			if (res.length > 0) {
				this.selectValueList01 = await res.map(item => {
					return {
						text: item.eccNm,
						value: item.eccId,
					};
				});
				// this.selectValueList01.unshift({
				// 	text: '전체',
				// 	value: null,
				// });
				this.selectValue01 = this.selectValueList01[0].value;
			} else {
				this.selectValueList01 = [];
				this.selectValue01 = null;
			}
			this.setPageData({
				eccIdList: this.selectValueList01,
				eccId: this.selectValue01,
			});
		},
		async getEqpmKind() {
			let res = await this.postApiReturn({
				apiKey: 'selectEqpmKindCodeList',
				resKey: 'eqpmKindCodeLists',
				sendParam: {},
			});
			if (res.length > 0) {
				this.selectValueList02 = await res.map(item => {
					return {
						text: item.eqpmKindNm,
						value: item.eqpmKindId,
					};
				});
				this.selectValue02 = this.selectValueList02[0].value;
			} else {
				this.selectValueList02 = [];
				this.selectValue02 = null;
			}
			this.setPageData({
				eqpmKindList: this.selectValueList02,
				eqpmKindId: this.selectValue02,
			});
		},
		async getEqpmGrp() {
			let res = await this.postApiReturn({
				apiKey: 'selectEqpmGrpCodeList',
				resKey: 'eqpmGrpCodeLists',
				sendParam: { eqpmKindId: this.selectValue02 },
			});
			if (res.length > 0) {
				this.selectValueList03 = await res.map(item => {
					return {
						text: item.eqpmGrpNm,
						value: item.eqpmGrpId,
					};
				});
				this.selectValue03 = this.selectValueList03[0].value;
			} else {
				this.selectValueList03 = [];
				this.selectValue03 = null;
			}
			this.setPageData({
				eqpmGrpList: this.selectValueList03,
				eqpmGrpId: this.selectValue03,
			});
		},
		gridInit() {
			this.loadGrid = false;
			let _this = this;
			const gridHeight = this.$refs.gridParent.offsetHeight - 50;
			let yyyyCol = this.pageData.fromDt + '년';
			let childCols1 = [];
			let myComplexColumns = [
				{
					header: yyyyCol,
					name: 'yyyyCol',
					childNames: childCols1,
				},
				{
					header: '설비명',
					name: 'fakeEqpmNm',
					childNames: ['eqpmNm', 'btnCol'],
					hideChildHeaders: true,
				},
			];
			let myOptions = {
				columnOptions: {
					resizable: true,
				},
				header: {
					height: 65,
					complexColumns: myComplexColumns,
				},
			};

			class CustumButton {
				constructor(props) {
					// v-btn v-btn--is-elevated v-btn--has-bg theme--dark v-size--default
					const el = document.createElement('button');
					const { grid, rowKey, columnInfo } = props;

					$(el).addClass('tui-grid-cell-content');
					// $(el).css('text-align', 'center');
					el.classList.add('v-btn');
					// el.style.width = '80%';
					// el.style.height = '80%';
					// el.style.boxShadow = '0px 0px 0px 2px #cbced6';
					// el.style.background = 'linear-gradient(to bottom, #242940 5%, #476e9e 100%)';
					// el.style.backgroundColor = '#144985';
					el.style.borderRadius = '7px';
					el.style.border = '1px solid #4e6096';
					// el.style.display = 'inline-block';
					// el.style.cursor = 'pointer';
					el.style.color = '#ffffff';
					// el.style.fontFamily = 'Arial';
					el.style.padding = '6% 3%';

					// el.style.textDecoration = 'none';
					// el.style.textShadow = '0px 1px 0px #283966';

					el.innerText = columnInfo.renderer.options.value;
					this.el = el;
					this.disabled = columnInfo.renderer.options.disabled || false;

					if (!this.disabled) {
						// hover 기능 구현
						this.el.addEventListener('mouseover', function (event) {
							// console.log('darkModeFg', _this.darkModeFg);
							// console.log('event',event.fromElement);
							// console.log('event',document.defaultView.getComputedStyle(el).getPropertyValue('background-color'));
							// rgb(85, 130, 220) // light
							// el.style.backgroundColor = '#26578F';	// rgb(20, 73, 133) // dark
							// let btnColor = _this.darkModeFg? {mouseOver: '#26578F', mouseOut: '#144985'} : {mouseOver: 'rgb(85, 130, 220)', mouseOut: 'rgb(71, 119, 217)'};
							// el.style.backgroundColor = btnColor['mouseOver'];
						});
						this.el.addEventListener('mouseout', function (event) {
							// rgb(71, 119, 217) // light
							// el.style.backgroundColor = '#144985'; // dark
							// console.log('event',event.fromElement);
							// let btnColor = _this.darkModeFg? {mouseOver: '#26578F', mouseOut: '#144985'} : {mouseOver: 'rgb(85, 130, 220)', mouseOut: 'rgb(71, 119, 217)'};
							// el.style.backgroundColor = btnColor['mouseOut'];
						});
						// click 이벤트
						this.el.addEventListener('click', function (event) {
							let gridData = grid.store.data.rawData;
							let rowNum = gridData[rowKey].rowNum;
							let selectedGridData = gridData.filter(item => {
								return item.rowNum === rowNum && item.gubun == '2PLAN';
							});
							// this.popupDialogFg = true;
							_this.setPageData({ eqpmNm: selectedGridData[0].eqpmNm });
							_this.setPageData({ popupDialogFg: true });
						});
					}
				}
				getElement() {
					return this.el;
				}
				getValue() {
					// return this.el.value;
				}
				mounted() {
					// this.el.focus();
				}
			}
			let myColumns = [
				{
					header: '설비그룹ID',
					name: 'eqpmGrpId',
					width: 50,
					align: 'left',
					hidden: true,
				},
				{
					header: '설비ID',
					name: 'eqpmId',
					width: 50,
					align: 'left',
					hidden: true,
				},
				{
					header: 'NO',
					name: 'rowNum',
					width: 40,
					align: 'center',
					// hidden: true,
				},
				{
					header: 'FAB',
					name: 'fab',
					width: 100,
					align: 'left',
					// hidden: true,
				},
				{
					header: '공정명',
					name: 'eccNm',
					width: 100,
					align: 'left',
					hidden: true,
				},
				{
					header: '설비그룹',
					name: 'eqpmGrpNm',
					minwidh: 200,
					align: 'left',
					// hidden: true,
				},
				{
					header: '설비명',
					name: 'eqpmNm',
					minWidth: 200,
					align: 'left',
					// hidden: true,
					formatter: ({ value, row }) => {
						return `
						<span>${value}</span>
						<button class="edit-btn" data-row='${JSON.stringify(row)}'>Edit</button>
					`;
					}
				},
				{
					header: '',
					name: 'btnCol',
					width: 70,
					align: 'center',
					renderer: {
						type: CustumButton,
						options: {
							value: '계획수정',
						},
					},
					// ,editor: {
					// 	type: CustomEditor,
					// 	align: "center"
					// }
				},
				{
					header: '구분',
					name: 'gubun',
					width: 80,
					align: 'left',
					// hidden: true,
					formatter({ value }) {
						let retVal = '';
						if (value == '1RSLT') {
							retVal = '전년실적';
						} else if (value == '2PLAN') {
							retVal = '계획';
						} else {
							retVal = value;
						}
						return retVal;
					},
				},
				{
					header: 'rowStat',
					name: 'rowStat',
					hidden: true,
				},
				{
					header: 'readObjId',
					name: 'readObjId',
					hidden: true,
				},
			];

			for (var i = 1; i <= 12; i++) {
				let qty = 'qty' + i.toString().padStart(2, '0');
				myColumns.push({
					header: i.toString() + '월',
					name: qty,
					width: 73,
					align: 'right',
					editor: 'text',
					formatter: this.numberFormatter,
				});
				childCols1.push(qty);
			}
			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			this.$nextTick(() => {
				this.loadGrid = true;
				this.getGridData();
			});
		},
		async getRowData(data) {
			this.rowKey = data.rowKey;
			this.edtingFinishFlag = 'Y';
			// 선택한 row의 계획data만 pageData에 저장
			let gridData = this.$refs.grid01.getData();
			let selectedGridData = gridData.filter(item => {
				return item.rowNum == data.rowNum;
			});
			await this.$nextTick(() => { });
			this.setPageData({
				rowGrid2SelectData: selectedGridData,
			});

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

			// this.setPageData({
			// 	rowGridSelectKey: selectedGridData[1].rowKey,
			// 	rowGridSelectData: selectedGridData[1],
			// });
		},
		async getGridData() {
			let res = [];
			res = await this.postApiReturn({
				apiKey: 'selectEnrgUsePlanData',
				resKey: 'enrgUsePlanDatas',
				sendParam: {
					fromDt: this.fromDt,
					pastDt: parseInt(this.fromDt) - 1,
					eqpmGrpId: this.selectValue03,
					eccId: this.selectValue01,
				},
			});
			let fabText = this.pageData.eccIdList.filter(item => {
				return item.value == this.selectValue01;
			})[0]['text'];

			let newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
					fab: fabText,
				};
				return newObj;
			});

			function setRowSpanAttribute(
				separateColStandardList,
				res,
				targetAttributeName,
				rowSpanList,
			) {
				if (!(res.length && res.length >= 2)) {
					return;
				}
				var valueList = [];
				var rowSpanValueList = [];
				var currentIdx = 0;
				for (var i = 0; i < res.length; i++) {
					valueList.push(res[i][targetAttributeName]);
				}

				function makeCurrentSeparateVal(idx, separateColStandardList) {
					let returnVal = '';
					for (var i = 0; i < separateColStandardList.length; i++) {
						returnVal += res[idx][separateColStandardList[i]];
					}
					return returnVal;
				}

				let beforeSeparateVal = makeCurrentSeparateVal(
					0,
					separateColStandardList,
				);
				rowSpanValueList[0] = [valueList[0], 1, currentIdx];
				for (var i = 1; i < valueList.length; i++) {
					currentIdx += 1;
					let currentSeparateVal = makeCurrentSeparateVal(
						i,
						separateColStandardList,
					);
					if (
						currentSeparateVal == beforeSeparateVal &&
						valueList[i] == rowSpanValueList[rowSpanValueList.length - 1][0]
					) {
						rowSpanValueList[rowSpanValueList.length - 1][1] += 1;
					} else {
						rowSpanValueList[rowSpanValueList.length] = [
							valueList[i],
							1,
							currentIdx,
						];
						beforeSeparateVal = currentSeparateVal;
					}
				}

				for (var i = 0; i < rowSpanValueList.length; i++) {
					if (rowSpanValueList[i][1] === 1) {
						continue;
					}
					if (res[rowSpanValueList[i][2]]['_attributes'] == undefined) {
						res[rowSpanValueList[i][2]]['_attributes'] = {
							rowSpan: new Object(),
						};
						//추가용
						res[rowSpanValueList[i][2]]['_attributes']['className'] = {
							column: new Object(),
						};
						for (var j = 0; j < rowSpanList.length; j++) {
							res[rowSpanValueList[i][2]]['_attributes']['className']['column'][
								rowSpanList[j]
							] = ['colrowspan'];
						}
						//추가용
					}
					res[rowSpanValueList[i][2]]['_attributes']['rowSpan'][
						targetAttributeName
					] = rowSpanValueList[i][1];
					res[rowSpanValueList[i][2]]['_attributes']['className']['column'][
						targetAttributeName
					].push(['rowrowspan']);
				}
			}
			let rowSpanList = ['rowNum', 'fab', 'eqpmGrpNm', 'eqpmNm', 'btnCol'];
			setRowSpanAttribute(['eqpmId'], newRes, 'rowNum', rowSpanList);
			setRowSpanAttribute(['rowNum'], newRes, 'fab', rowSpanList);
			setRowSpanAttribute(['rowNum'], newRes, 'eqpmGrpNm', rowSpanList);
			setRowSpanAttribute(['rowNum'], newRes, 'eqpmNm', rowSpanList);
			setRowSpanAttribute(['rowNum'], newRes, 'btnCol', rowSpanList);
			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});
			this.$nextTick(() => {
				this.setRowDisabled();
			});

			// let temp = newRes.filter(item => {
			// 	return item.gubun=='1RSLT'
			// })
			// console.log('temp', temp);
			// for(var i=0; i<temp.length; i++){
			// 	console.log(temp.rowKey);
			// }
		},
		numberFormatter({ value }) {
			// return Utility.setFormatIntDecimal(value, 0);
			if (value === undefined || value === null || value === '') {
				return '';
			}
			var newValue = value.toString().split('.');

			// 숫자와 문자가 섞여있을 경우 구분하는 로직 추가
			var regex = /[^0-9]/g; // 숫자가 아닌 문자열을 선택하는 정규식
			for (var i = 0; i < newValue.length; i++) {
				if (regex.test(newValue[i])) {
					newValue[i] = newValue[i].toString().replace(regex, '');
				}
			}
			if (parseInt(newValue[1]) >= 5) {
				return (parseInt(newValue[0]) + 1)
					.toString()
					.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
			} else {
				return newValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
			}
			// return (
			// 	newValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') +
			// 	(newValue[1] ? '.' + newValue[1] : '')
			// );
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'save':
					if (this.edtingFinishFlag == 'Y') {
						await this.$refs[this.gridName].editingFinish({
							rowKey: this.rowKey,
						});
					}
					// let temp = this.$refs[this.gridName].getData();
					dataArr = this.$refs[this.gridName].save();
					var validCheck = true;
					if (dataArr.length > 0) {
						dataArr.filter(item => {
							if (item.eqpmGrpId == '' || item.eqpmId == null) {
								alert('필수 입력값을 입력해주세요.');
								validCheck = false;
							}
						});
						let dataList = [];
						for (var i = 0; i < dataArr.length; i++) {
							if (dataArr[i]['gubun'] == '2PLAN') {
								for (var j = 1; j <= 12; j++) {
									let temp = {};
									let qty = 'qty' + j.toString().padStart(2, '0');
									temp['eqpmId'] = dataArr[i]['eqpmId'];
									temp['readObjId'] = dataArr[i]['readObjId'];
									temp['objMm'] =
										this.pageData.fromDt + j.toString().padStart(2, '0');
									temp['rowStat'] = dataArr[i]['rowStat'];
									temp['planVal'] =
										dataArr[i][qty] == ''
											? null
											: parseInt(dataArr[i][qty]) == 0
												? 0
												: dataArr[i][qty];
									dataList.push(temp);
								}
							}
						}
						// console.log('dataList', dataList);
						// 		// dataArr[i]
						// }
						if (validCheck) {
							const sendParam = {
								datas: {
									dsEmsEqpmMmPlanDatas: dataList,
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveEmsEqpmMmPlanDatas',
								sendParam: sendParam,
							});

							this.$nextTick(() => {
								// this.setPageData({ isFind: true });
								this.search();
							});
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		setRowDisabled() {
			let gridData = this.$refs[this.gridName].getData();
			let rowKeyList = gridData
				.filter(item => {
					return item.gubun == '1RSLT';
				})
				.map(item => item.rowKey);
			for (var i = 0; i < rowKeyList.length; i++) {
				this.$refs[this.gridName].disableRow(rowKeyList[i]);
			}
			if (gridData.length > 0) {
				try {
					this.$refs[this.gridName].focus({
						//rowKey: 0,
						rowKey: 0,
						setScroll: true,
					});
				} catch (error) {
					console.log('error[nextTick grid] : ', error);
				}
			}
		},
	},
};
const dt = new Date();
const yyyy = dt.getFullYear();
const defaultData = {
	isFind: false, // true 경우 조회
	/* 검색옵션 */
	cmCycle: 'CYC_YEAR', // DatePicker 옵션
	fromDt: `${yyyy}`, // DatePicker 옵션
	eccIdList: [], // FAB
	eccId: '', // FAB
	eqpmKindList: [], // 설비종류
	eqpmKindId: '', // 설비종류
	eqpmGrpList: [], // 설비그룹
	eqpmGrpId: '', // 설비그룹

	// Grid에서 선택된 데이터
	rowGridSelectKey: 0,
	rowGridSelectData: null,
	rowGrid2SelectData: [
		{
			gubun: '',
			eccNm: '',
			eqpmGrpId: '',
			eqpmGrpNm: '',
			eqpmId: '',
			eqpmNm: '',
			qty01: '',
			qty02: '',
			qty03: '',
			qty04: '',
			qty05: '',
			qty06: '',
			qty07: '',
			qty08: '',
			qty09: '',
			qty10: '',
			qty11: '',
			qty12: '',
			btnCol: '',
			rowStat: null,
		},
	],

	// popup dialog flag
	popupDialogFg: false,
	eqpmNm: '',

	//grid 설정
	grid01: {
		data: [],
		column: [],
		option: { header: { complexColumns: [] } },
		defaultRow: {
			gubun: '',
			eccNm: '',
			eqpmGrpId: '',
			eqpmGrpNm: '',
			eqpmId: '',
			eqpmNm: '',
			qty01: '',
			qty02: '',
			qty03: '',
			qty04: '',
			qty05: '',
			qty06: '',
			qty07: '',
			qty08: '',
			qty09: '',
			qty10: '',
			qty11: '',
			qty12: '',
			btnCol: '',
			rowStat: null,
		},
		buttonAuth: {
			add: false,
			remove: false,
			save: true,
			excel: false,
		},
	},
};

const dataPathDataExample = [
	{
		rowNum: 1,
		fab: 'B01',
		eqpmGrpNm: '방송기술운',
		eqpmNm: 'U/T_LT_CH101',
		gubun: '전력량',
		jan: 110000,
		feb: 112000,
		mar: 115000,
		apr: 117000,
		may: 120000,
		jun: 118000,
		jul: 119000,
		aug: 121000,
		sep: 122000,
		oct: 123000,
		nov: 124000,
		dec: 125000
	},
	{
		rowNum: 2,
		fab: 'B02',
		eqpmGrpNm: '방송기술운',
		eqpmNm: 'U/T_LT_CH102',
		gubun: '전력량',
		jan: 81000,
		feb: 82000,
		mar: 83000,
		apr: 84000,
		may: 85000,
		jun: 86000,
		jul: 87000,
		aug: 88000,
		sep: 89000,
		oct: 90000,
		nov: 91000,
		dec: 92000
	},
	{
		rowNum: 3, fab: 'C01', eqpmGrpNm: '방송기술운', eqpmNm: 'U/T_LT_CH124', gubun: '수도량',
		jan: 106178, feb: 104740, mar: 92283, apr: 116081, may: 98945, jun: 126579,
		jul: 90690, aug: 124243, sep: 97524, oct: 84072, nov: 88160, dec: 118183
	},
	{
		rowNum: 4, fab: 'B01', eqpmGrpNm: '방송기술운', eqpmNm: 'U/T_LT_CH103', gubun: '가스량',
		jan: 80442, feb: 102867, mar: 114939, apr: 106335, may: 81743, jun: 83711,
		jul: 86114, aug: 97432, sep: 84146, oct: 84775, nov: 117921, dec: 119417
	},
	{
		rowNum: 5, fab: 'B01', eqpmGrpNm: '설비운영팀', eqpmNm: 'U/T_LT_CH156', gubun: '전력량',
		jan: 90341, feb: 94072, mar: 122754, apr: 85471, may: 90813, jun: 116831,
		jul: 90856, aug: 109437, sep: 94029, oct: 96075, nov: 127067, dec: 102503
	},
	{
		rowNum: 6, fab: 'B03', eqpmGrpNm: '방송기술운', eqpmNm: 'U/T_LT_CH183', gubun: '가스량',
		jan: 104163, feb: 107012, mar: 104631, apr: 83055, may: 106311, jun: 117306,
		jul: 86434, aug: 117087, sep: 118414, oct: 91499, nov: 93829, dec: 94192
	},
	{
		rowNum: 7, fab: 'C01', eqpmGrpNm: '전력관리부', eqpmNm: 'U/T_LT_CH158', gubun: '가스량',
		jan: 84821, feb: 128234, mar: 116883, apr: 116718, may: 114738, jun: 88297,
		jul: 93840, aug: 84700, sep: 98360, oct: 87021, nov: 113098, dec: 94734
	},
	{
		rowNum: 8, fab: 'B02', eqpmGrpNm: '방송기술운', eqpmNm: 'U/T_LT_CH179', gubun: '가스량',
		jan: 128714, feb: 88797, mar: 124808, apr: 109283, may: 113141, jun: 82873,
		jul: 114993, aug: 129108, sep: 100885, oct: 125730, nov: 92127, dec: 122286
	},
	{
		rowNum: 9, fab: 'C01', eqpmGrpNm: '전력관리부', eqpmNm: 'U/T_LT_CH191', gubun: '전력량',
		jan: 107258, feb: 108424, mar: 113604, apr: 116648, may: 124149, jun: 129978,
		jul: 112215, aug: 129602, sep: 93551, oct: 111272, nov: 89736, dec: 128423
	},
	{
		rowNum: 10, fab: 'B02', eqpmGrpNm: '방송기술운', eqpmNm: 'U/T_LT_CH104', gubun: '전력량',
		jan: 82089, feb: 102793, mar: 96784, apr: 85238, may: 86153, jun: 123849,
		jul: 115095, aug: 129484, sep: 102109, oct: 80976, nov: 119841, dec: 106309
	},
	{
		rowNum: 11, fab: 'C02', eqpmGrpNm: '전력관리부', eqpmNm: 'U/T_LT_CH139', gubun: '전력량',
		jan: 128592, feb: 95647, mar: 85982, apr: 126824, may: 87928, jun: 128967,
		jul: 94637, aug: 107530, sep: 122533, oct: 97546, nov: 112110, dec: 126250
	},
	{
		rowNum: 12, fab: 'C01', eqpmGrpNm: '설비운영팀', eqpmNm: 'U/T_LT_CH109', gubun: '전력량',
		jan: 106530, feb: 91716, mar: 111104, apr: 102663, may: 108912, jun: 91464,
		jul: 121245, aug: 90785, sep: 120586, oct: 105718, nov: 96191, dec: 111513
	}
];

</script>
<style lang="scss" scoped>
@import '@/assets/scss/var.scss';

@each $theme in dark, light {
	.v-application.#{$theme}-mode {
		.tui-grid {

			&-row-odd,
			&-row-even {
				&:hover>.colrowspan {
					background-color: map-deep-get($config,
						#{$theme},
						'tui-grid-cell-backgroundColor'
					) !important;

					.tui-grid-cell-content {
						color: map-deep-get($config, #{$theme}, 'activate') !important;
					}
				}
			}

			&-cell {
				&.row-selected.colrowspan {
					background-color: map-deep-get($config,
						#{$theme},
						'tui-grid-cell-backgroundColor'
					) !important;

					.tui-grid-cell-content {
						color: map-deep-get($config, #{$theme}, 'activate') !important;
					}
				}
			}
		}
	}
}
</style>
