<template>
	<div 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="'SelectBlocMstr'"
								ref="SelectBlocMstr"
								:parentPrgmId="myPrgmId"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								label="에너지"
								:is="'SelectErcInfoList'"
								:parentPrgmId="myPrgmId"
								:initFlag="true"
							/>
						</v-col>
						<v-col cols="4">
							<DatePicker
								:parentPrgmId="myPrgmId"
								:textCols="9"
								:labelCols="3"
								label="조회기간"
							/>
							<component
								:is="'SelectCmCycle'"
								:parentPrgmId="myPrgmId"
								v-show="false"
							/>
						</v-col>
						<v-col cols="3" class="text-right">
							<v-btn :ripple="false" class="mr-1" @click="search()">조회</v-btn>
							<BtnExcelDownload
								class="mr-1"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" style="height: calc(100vh - 230px)">
			<v-col :cols="12">
				<v-card class="pa-5">
					<v-row ref="row1" class="search-box" no-gutters>
						<v-col :cols="1">
							<label for="" class="search-box-label">
								<v-icon x-small color="primary" class="mr-1"
									>mdi-record-circle</v-icon
								>
								전력 요금제
							</label>
						</v-col>
						<v-col :cols="2">
							<v-text-field
								v-model="energyPlanName"
								class="v-input__custom"
								:disabled="true"
								outlined
								:hide-details="true"
							></v-text-field>
						</v-col>
						<v-col :cols="1" align="center">
							<v-btn @click="dialog = !dialog" class="v-input__custom">
								단가보기
							</v-btn>
						</v-col>
						<v-dialog
							ref="popModel"
							v-model="dialog"
							width="850"
							overlay-color="#000"
							overlay-opacity="0.8"
						>
							<v-card-title
								class="pa-5 d-flex align-center justify-space-between"
							>
								<span class="custom-title-4">단가정보</span>
							</v-card-title>
							<v-divider></v-divider>
							<v-card style="height: 240px">
								<div ref="dialogGridParent" style="height: 180px">
									<component
										:ref="dialogGridName"
										:is="loadDialogGrid ? 'Grid' : null"
										:gridName="dialogGridName"
										:parentPrgmId="myPrgmId"
									/>
								</div>
								<v-card-actions class="align-center justify-center">
									<v-btn :ripple="false" @click="dialog = !dialog">닫기</v-btn>
								</v-card-actions>
							</v-card>
						</v-dialog>
					</v-row>
					<v-row ref="row2">
						<v-col :cols="1">
							<label for="" class="search-box-label">
								<v-icon x-small color="primary" class="mr-1"
									>mdi-record-circle</v-icon
								>
								월별 요금 정보
							</label>
						</v-col>
						<v-col :cols="9"> </v-col>
						<v-col :cols="2" align="right">
							<Buttons
								:parentPrgmId="myPrgmId"
								:bindingData="gridName"
								:btnActionsFnc="btnActions"
							/>
						</v-col>
					</v-row>
					<v-row ref="row3">
						<v-col :cols="12">
							<div ref="gridParent" class="px-5" style="height: 43%">
								<component
									:is="loadGrid ? 'Grid' : null"
									:gridName="gridName"
									:parentPrgmId="myPrgmId"
									:editorGrid="true"
									@updateDataInfo="evtUpdateDataInfo"
									ref="rowGrid"
								/>
							</div>
						</v-col>
					</v-row>
					<v-row ref="row4">
						<v-col :cols="1">
							<label for="" class="search-box-label">
								<v-icon x-small color="primary" class="mr-1"
									>mdi-record-circle</v-icon
								>
								월별 추이
							</label>
						</v-col>
					</v-row>
					<v-row ref="row5">
						<v-col :cols="12">
							<div
								ref="chartParent"
								class="h100 w100"
								style="height: calc((100vh - 400px) / 2  - 30px);"
							>
								<component
									class="w100 h100"
									:is="loadChart ? 'Chart' : null"
									:parentPrgmId="myPrgmId"
									:chartName="chartName"
									ref="rowGridChart"
								/>
							</div>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import BtnSearch from '~/components/common/button/BtnSearch';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Utility from '~/plugins/utility';
import Grid from '~/components/common/Grid';
import Chart from '~/components/common/Chart';
import mixinGlobal from '@/mixin/global.js';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstrForPop';
import SelectErcInfoList from '@/components/common/select/SelectErcInfoList';
import DatePicker from '~/components/common/Datepicker';
import SelectCmCycle from '@/components/common/select/SelectCmCycle';
import Buttons from '~/components/common/button/Buttons';

let myTitle;
// const myPrgmId = "PRG0055";
let myPrgmId;
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: {
		Buttons,
		BtnSearch,
		BtnExcelDownload,
		Utility,
		Grid,
		Chart,
		SelectBlocMstr,
		SelectErcInfoList,
		DatePicker,
		SelectCmCycle,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			energyPlanName: '',
			energyPlan: null,
			dialog: false,
			loadDialogGrid: false,
			dialogGridName: 'dialogGrid',
			loadGrid: false,
			gridName: 'rowGrid',
			loadChart: false,
			chartName: 'rowGridChart',
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		blocId() {
			return this.pageData.blocId === undefined ? null : this.pageData.blocId;
		},
		ercId() {
			return this.pageData.ercList === undefined ? null : this.pageData.ercId;
		},
	},
	watch: {
		blocId(val) {},
		async ercId(val) {
			this.energyPlan = await this.getEnergyPlan();

			if (this.energyPlan != null) {
				this.energyPlanName = this.energyPlan.elecContNm;
			} else {
				this.energyPlanName = '';
			}

			this.search();
		},
		async dialog(val) {
			if (val === true) {
				this.dialogGridInit();
				await this.setDialogGridData();
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridSelectData: 'setGridSelectData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartXAxisData: 'setChartXAxisData',
			setChartYAxisData: 'setChartYAxisData',
			setChartSeries: 'setChartSeries',
			setChartOption: 'setChartOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		init() {},
		dialogGridInit() {
			// const dialogGridHeight = this.$refs.dialogGridParent.offsetHeight - 36;
			const dialogGridHeight = 180;
			const myOptions = {
				scrollX: false,
			};
			var dialogGridColumnList = [
				{
					header: '기본요금(원/kw)',
					name: 'baseChrg',
					align: 'right',
					formatter({ value }) {
						return Utility.setFormatDecimal(value, 5);
					},
				},
				{ header: '시간대', name: 'peakKindNm', align: 'center' },
				{
					header: '여름철(6~8월)',
					name: 'unitPrcSum',
					align: 'right',
					formatter({ value }) {
						return Utility.setFormatIntDecimal(value, 1);
					},
				},
				{
					header: '봄·가을철(3~5,9~10월)',
					name: 'unitPrcSprfal',
					align: 'right',
					formatter({ value }) {
						return Utility.setFormatIntDecimal(value, 1);
					},
				},
				{
					header: '겨울철(11~2월)',
					name: 'unitPrcWin',
					align: 'right',
					formatter({ value }) {
						return Utility.setFormatIntDecimal(value, 1);
					},
				},
			];

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

			this.setGridColumn({
				gridKey: this.dialogGridName,
				value: dialogGridColumnList,
			});
		},
		async search() {
			await this.mainGridInit();
			await this.getMainGridData();
		},
		async mainGridInit() {
			// const gridHeight = this.$refs.gridParent.offsetHeight - 36;
			const gridHeight = 250;

			const myOptions = {
				scrollX: false,
			};

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

			this.setMainGridColunmnList();
		},
		setMainGridColunmnList() {
			var chrgKind = this.energyPlan.chrgKind;

			var hiddenBooleanList;
			var columnWidth;

			if (chrgKind === 'PEAK') {
				hiddenBooleanList = [
					true, // 회사 ID
					true, // 에너지원 번호
					true, // 대상월(202205)
					false, // 대상월(2022/05) - 화면상에 표시
					true, // 사업장
					false, // 시작일
					false, // 종료일
					false, // 고지요금
					false, // 기본요금
					false, // 사용량
					false, // 피크전력(chrgKind==PEAK)
					false, // 계약전력(chrgKind==PEAK)
					true, // 보정계수(chrgKind==GAS)
					true, // 히터계수(chrgKind==GAS)
					true, // 단가
					false, // 비고
					true, // 등록사용자
					true, // 등록일자
					true, // 수정사용자
					true, // 수정일자
				];
				columnWidth = columnWidth;
			} else if (chrgKind === 'GAS') {
				hiddenBooleanList = [
					true, // 회사 ID
					true, // 에너지원 번호
					true, // 대상월(202205)
					false, // 대상월(2022/05) - 화면상에 표시
					true, // 사업장
					false, // 시작일
					false, // 종료일
					false, // 고지요금
					false, // 기본요금
					false, // 사용량
					true, // 피크전력(chrgKind==PEAK)
					true, // 계약전력(chrgKind==PEAK)
					false, // 보정계수(chrgKind==GAS)
					false, // 히터계수(chrgKind==GAS)
					false, // 단가(chrgKind==GAS && chrgKind==ETC)
					false, // 비고
					true, // 등록사용자
					true, // 등록일자
					true, // 수정사용자
					true, // 수정일자
				];
				columnWidth = 150;
			} else if (chrgKind === 'ETC') {
				hiddenBooleanList = [
					true, // 회사 ID
					true, // 에너지원 번호
					true, // 대상월(202205)
					false, // 대상월(2022/05) - 화면상에 표시
					true, // 사업장
					false, // 시작일
					false, // 종료일
					false, // 고지요금
					false, // 기본요금
					false, // 사용량
					false, // 피크전력(chrgKind==PEAK)
					false, // 계약전력(chrgKind==PEAK)
					true, // 보정계수(chrgKind==GAS)
					true, // 히터계수(chrgKind==GAS)
					false, // 단가(chrgKind==GAS && chrgKind==ETC)
					false, // 비고
					true, // 등록사용자
					true, // 등록일자
					true, // 수정사용자
					true, // 수정일자
				];
				columnWidth = 175;
			}

			var columnList = [
				{ header: '회사 ID', name: 'comId', hidden: hiddenBooleanList[0] },
				{
					header: '에너지원 번호',
					name: 'ercId',
					hidden: hiddenBooleanList[1],
				},
				{
					header: '대상월',
					name: 'objMm',
					align: 'right',
					hidden: hiddenBooleanList[2],
				},
				{
					header: '대상 월',
					name: 'objYm',
					width: columnWidth,
					align: 'center',
					hidden: hiddenBooleanList[3],
				},
				{
					header: '사업장',
					name: 'blocId',
					width: columnWidth,
					align: 'center',
					hidden: hiddenBooleanList[4],
				},
				{
					header: '시작일',
					name: 'strtDt',
					width: columnWidth,
					align: 'center',
					editor: {
						type: 'datePicker',
						options: {
							format: 'yyyy-MM-dd',
							language: 'ko',
							calendar: {
								showToday: false,
							},
						},
					},
					hidden: hiddenBooleanList[5],
				},
				{
					header: '종료일',
					name: 'endDt',
					width: columnWidth,
					align: 'center',
					editor: {
						type: 'datePicker',
						options: {
							format: 'yyyy-MM-dd',
							language: 'ko',
							calendar: {
								showToday: false,
							},
						},
					},
					hidden: hiddenBooleanList[6],
				},
				{
					header: '고지 요금',
					name: 'notiChrg',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[7],
				},
				{
					header: '기본 요금',
					name: 'baseChrg',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[8],
				},
				{
					header: '사용량',
					name: 'useQty',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[9],
				},
				{
					header: '피크 전력',
					name: 'peakPow',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[10],
				},
				{
					header: '계약 전력',
					name: 'contPow',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[11],
				},
				{
					header: '보정계수',
					name: 'corrCoff',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[12],
				},
				{
					header: '히터계수',
					name: 'heatCoff',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[13],
				},
				{
					header: '단가',
					name: 'unitPrce',
					width: columnWidth,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
					hidden: hiddenBooleanList[14],
				},
				{
					header: '비고',
					name: 'rmrk',
					width: columnWidth,
					align: 'left',
					editor: 'text',
					hidden: hiddenBooleanList[15],
				},
				{
					header: '등록 사용자',
					name: 'regUserNo',
					hidden: hiddenBooleanList[16],
				},
				{ header: '등록 일자', name: 'regDttm', hidden: hiddenBooleanList[17] },
				{
					header: '수정 사용자',
					name: 'procUserNo',
					hidden: hiddenBooleanList[18],
				},
				{
					header: '수정 일자',
					name: 'procDttm',
					hidden: hiddenBooleanList[19],
				},
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: columnList,
			});
		},
		async getMainGridData() {
			this.loadGrid = false;

			const res = await this.postApiReturn({
				apiKey: 'selectEnrgChrgInfo',
				resKey: 'enrgChrgInfoData',
				sendParam: {
					blocId: this.pageData.blocMstrList[this.blocId].blocId,
					ercId: this.pageData.ercList[this.ercId].ercId,
					startDt: this.pageData.fromDt,
					endDt: this.pageData.toDt,
				},
			});

			const newRes = res.map(item => {
				const newObj = {
					...item,
					comId: item.comId || '',
					blocId: item.blocId || '',
					ercId: item.ercId || '',
					objMm: item.objMm || '',
					objYm: item.objYm || '',
					strtDt: item.strtDt || '',
					endDt: item.endDt || '',
					notiChrg: item.notiChrg || '',
					baseChrg: item.baseChrg || '',
					rmrk: item.rmrk || '',
					useQty: item.useQty || '',
					unitPrce: item.unitPrce || '',
					corrCoff: item.corrCoff || '',
					heatCoff: item.heatCoff || '',
					peakPow: item.peakPow || '',
					contPow: item.contPow || '',
					regUserNo: item.regUserNo || '',
					regDttm: item.regDttm || '',
					procUserNo: item.procUserNo || '',
					procDttm: item.procDttm || '',
					rowStat: null,
				};
				return newObj;
			});

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

			this.setChartData(this.pageData[this.gridName].data);

			this.loadGrid = true;
		},
		async setDialogGridData() {
			this.loadDialogGrid = false;
			var res;
			if (this.energyPlan.elecContId != '') {
				res = await this.postApiReturn({
					apiKey: 'selectElecPowChrgInfo',
					resKey: 'elecPowChrgInfoData',
					sendParam: {
						elecContId: this.energyPlan.elecContId,
					},
				});
			} else {
				res = [];
			}

			setRowSpanAttribute(res, 'baseChrg');

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

			this.loadDialogGrid = true;
		},
		setChartData(data) {
			if (this.$refs.rowGridChart != undefined) {
				this.$refs.rowGridChart.clear();
			}

			this.loadChart = false;
			this.pageData.rowGridChart = Utility.defaultChartOption(true);

			var chrgKind = this.energyPlan.chrgKind;
			let xAxisData = [];
			let yAxisData = [];
			let seriesData = [];
			let seriesDataBaseChrg = {
				name: '기본요금',
				type: 'line',
				symbol: 'none',
				data: [],
			};
			let seriesDataNotiChrg = { name: '고지요금', type: 'line', data: [] };

			for (var idx in data) {
				xAxisData.push(data[idx].objYm);
				if (data[idx].baseChrg == null || data[idx].baseChrg == '') {
					seriesDataBaseChrg.data.push(0);
				} else {
					seriesDataBaseChrg.data.push(data[idx].baseChrg);
				}
				if (data[idx].notiChrg == null || data[idx].notiChrg == '') {
					seriesDataNotiChrg.data.push(0);
				} else {
					seriesDataNotiChrg.data.push(data[idx].notiChrg);
				}
			}
			seriesData.push(seriesDataBaseChrg);
			seriesData.push(seriesDataNotiChrg);
			yAxisData.push({
				type: 'value',
				name: '원',
				nameLocation: 'middle',
				nameGap: 50,
				position: 'left',
				axisLabel: {
					formatter: '{value}',
				},
			});

			if (chrgKind === 'PEAK') {
				var seriesDataPeakPow = {
					name: '피크전력',
					type: 'line',
					symbol: 'none',
					yAxisIndex: 1,
					data: [],
				};

				for (var idx in data) {
					if (data[idx].peakPow == null || data[idx].peakPow == '') {
						seriesDataPeakPow.data.push(0);
					} else {
						seriesDataPeakPow.data.push(data[idx].peakPow);
					}
				}

				seriesData.push(seriesDataPeakPow);
			}

			var seriesDataUseQty = {
				name: '사용량',
				type: 'bar',
				yAxisIndex: 1,
				data: [],
			};

			for (var idx in data) {
				if (data[idx].useQty == null || data[idx].useQty == '') {
					seriesDataUseQty.data.push(0);
				} else {
					seriesDataUseQty.data.push(data[idx].useQty);
				}
			}

			seriesData.push(seriesDataUseQty);
			yAxisData.push({
				type: 'value',
				name: this.energyPlan.unitNm,
				nameLocation: 'middle',
				nameGap: 50,
				axisLabel: {
					formatter: '{value}',
				},
				position: 'right',
			});

			this.setChartYAxisData({ chartKey: this.chartName, value: yAxisData });
			this.setChartXAxisData({ chartKey: this.chartName, value: xAxisData });
			this.setChartSeries({ chartKey: this.chartName, value: seriesData });

			this.loadChart = true;
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					break;

				case 'remove':
					this.$refs[this.gridName].removeRow();
					break;

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						const sendParam = {
							datas: {
								dsEnrgChrgInfo: dataArr.map(item => ({
									...item,
								})),
							},
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveEnrgChrgInfo',
							sendParam: sendParam,
						});
					} else {
						alert('저장할 내용이 없습니다.');
					}
					this.search();
					break;

				default:
					break;
			}
		},
		async getEnergyPlan() {
			var data = await this.postApiReturn({
				// apiKey : "selectElecPowChrgInfo",
				apiKey: 'selectErcInfoWithUnitCd',
				resKey: 'ercInfoData',
				sendParam: {
					blocId: this.pageData.blocMstrList[this.blocId].blocId,
					ercId: this.pageData.ercList[this.ercId].ercId,
					useFg: '1',
				},
			});
			if (data.length > 0) {
				data = data[0];
			} else {
				data = null;
			}
			return data;
		},
		evtUpdateDataInfo(data) {
			var gridInstance = this.$refs.rowGrid.$el.__vue__.$el.__vue__
				.gridInstance;

			this.validationCheck(data, gridInstance);
		},
		validationCheck(data, gridInstance) {
			if (data.columnName === 'strtDt') {
				var pattern = /^\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/g;
				var chk = pattern.test(data.value);
				if (chk) {
					var objMm = data.rowData.objMm;
					var year = parseInt(objMm.substring(0, 4));
					var month = parseInt(objMm.substring(4, 6)) - 1;
					var monthFirstDay = new Date(year, month, 1);
					var monthLastDay = new Date(year, month + 1, 0);

					var endDt = data.rowData.endDt === '' ? null : data.rowData.endDt;
					var strtDt = data.rowData.strtDt;
					var strtDay = new Date(
						parseInt(strtDt.replaceAll('-', '').substring(0, 4)),
						parseInt(strtDt.replaceAll('-', '').substring(4, 6)) - 1,
						parseInt(strtDt.replaceAll('-', '').substring(6, 8)),
					);
					var endDay =
						endDt === null
							? null
							: new Date(
									parseInt(endDt.replaceAll('-', '').substring(0, 4)),
									parseInt(endDt.replaceAll('-', '').substring(4, 6)) - 1,
									parseInt(endDt.replaceAll('-', '').substring(6, 8)),
							  );

					if (strtDay < monthFirstDay) {
						gridInstance.invoke(
							'setValue',
							data.rowIdxKey,
							'strtDt',
							getStringDate(monthFirstDay),
						);
						this.$refs.rowGrid.editingFinish({
							ignoreUpdateDataInfoFlag: true,
							rowKey: data.rowIdxKey,
							columnName: 'strtDt',
							value: getStringDate(monthFirstDay),
							save: true,
							stopped: false,
							triggeredByKey: true,
						});
					} else if (strtDay > endDay && endDt != null) {
						gridInstance.invoke(
							'setValue',
							data.rowIdxKey,
							'strtDt',
							getStringDate(endDay),
						);
						this.$refs.rowGrid.editingFinish({
							ignoreUpdateDataInfoFlag: true,
							rowKey: data.rowIdxKey,
							columnName: 'strtDt',
							value: getStringDate(endDay),
							save: true,
							stopped: false,
							triggeredByKey: true,
						});
					} else if (strtDay > monthLastDay) {
						gridInstance.invoke(
							'setValue',
							data.rowIdxKey,
							'strtDt',
							getStringDate(monthLastDay),
						);
						this.$refs.rowGrid.editingFinish({
							ignoreUpdateDataInfoFlag: true,
							rowKey: data.rowIdxKey,
							columnName: 'strtDt',
							value: getStringDate(monthLastDay),
							save: true,
							stopped: false,
							triggeredByKey: true,
						});
					}
				} else {
					gridInstance.invoke('setValue', data.rowIdxKey, 'strtDt', '');
					this.$refs.rowGrid.editingFinish({
						ignoreUpdateDataInfoFlag: true,
						rowKey: data.rowIdxKey,
						columnName: 'strtDt',
						value: '',
						save: true,
						stopped: false,
						triggeredByKey: true,
					});
				}
			} else if (data.columnName === 'endDt') {
				var pattern = /^\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/g;
				var chk = pattern.test(data.value);
				if (chk) {
					var objMm = data.rowData.objMm;
					var year = parseInt(objMm.substring(0, 4));
					var month = parseInt(objMm.substring(4, 6)) - 1;
					var monthFirstDay = new Date(year, month, 1);
					var monthLastDay = new Date(year, month + 1, 0);

					var strtDt = data.rowData.strtDt === '' ? null : data.rowData.strtDt;
					var endDt = data.rowData.endDt;
					var endDay = new Date(
						parseInt(endDt.replaceAll('-', '').substring(0, 4)),
						parseInt(endDt.replaceAll('-', '').substring(4, 6)) - 1,
						parseInt(endDt.replaceAll('-', '').substring(6, 8)),
					);
					var strtDay =
						strtDt === null
							? null
							: new Date(
									parseInt(strtDt.replaceAll('-', '').substring(0, 4)),
									parseInt(strtDt.replaceAll('-', '').substring(4, 6)) - 1,
									parseInt(strtDt.replaceAll('-', '').substring(6, 8)),
							  );
					if (endDay > monthLastDay) {
						gridInstance.invoke(
							'setValue',
							data.rowIdxKey,
							'endDt',
							getStringDate(monthLastDay),
						);
						this.$refs.rowGrid.editingFinish({
							ignoreUpdateDataInfoFlag: true,
							rowKey: data.rowIdxKey,
							columnName: 'endDt',
							value: getStringDate(monthLastDay),
							save: true,
							stopped: false,
							triggeredByKey: true,
						});
					} else if (endDay < strtDay && strtDt != null) {
						gridInstance.invoke(
							'setValue',
							data.rowIdxKey,
							'endDt',
							getStringDate(strtDay),
						);
						this.$refs.rowGrid.editingFinish({
							ignoreUpdateDataInfoFlag: true,
							rowKey: data.rowIdxKey,
							columnName: 'endDt',
							value: getStringDate(strtDay),
							save: true,
							stopped: false,
							triggeredByKey: true,
						});
					} else if (endDay < monthFirstDay) {
						gridInstance.invoke(
							'setValue',
							data.rowIdxKey,
							'endDt',
							getStringDate(monthFirstDay),
						);
						this.$refs.rowGrid.editingFinish({
							ignoreUpdateDataInfoFlag: true,
							rowKey: data.rowIdxKey,
							columnName: 'endDt',
							value: getStringDate(monthFirstDay),
							save: true,
							stopped: false,
							triggeredByKey: true,
						});
					}
				} else {
					gridInstance.invoke('setValue', data.rowIdxKey, 'endDt', '');
					this.$refs.rowGrid.editingFinish({
						ignoreUpdateDataInfoFlag: true,
						rowKey: data.rowIdxKey,
						columnName: 'endDt',
						value: '',
						save: true,
						stopped: false,
						triggeredByKey: true,
					});
				}
			} else if (
				data.columnName === 'baseChrg' ||
				data.columnName === 'notiChrg' ||
				data.columnName === 'useQty' ||
				data.columnName === 'peakPow' ||
				data.columnName === 'contPow'
			) {
				//var resultValue = (data.value).replace(/[^0-9.]/g, "");
				var resultValue = '';
				var pattern = /(^\d+$)|(^\d{1,}[.]\d{1,5}$)/g;
				var chk = pattern.test(data.value);
				if (chk) {
					resultValue = data.value;
				} else {
					resultValue = '';
				}
				gridInstance.invoke(
					'setValue',
					data.rowIdxKey,
					data.columnName,
					resultValue,
				);
				this.$refs.rowGrid.editingFinish({
					ignoreUpdateDataInfoFlag: true,
					rowKey: data.rowIdxKey,
					columnName: data.columnName,
					value: resultValue,
					save: true,
					stopped: false,
					triggeredByKey: true,
				});
			}
		},
	},
};

function setRowSpanAttribute(res, targetAttributeName, targetAttributeList) {
	if (!(res.length && res.length >= 1)) {
		return;
	}

	if (targetAttributeList == undefined) {
		var currentCnt = 1;
		var currentIdx = 0;
		var currentValue = res[0][targetAttributeName];
		for (var i = 1; i < res.length; i++) {
			if (res[i][targetAttributeName] != currentValue) {
				if (res[currentIdx]['_attributes'] == undefined) {
					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
				}
				res[currentIdx]['_attributes']['rowSpan'][
					targetAttributeName
				] = currentCnt;

				currentValue = res[i][targetAttributeName];
				currentCnt = 1;
				currentIdx = i;
			} else if (
				res[i][targetAttributeName] == currentValue &&
				i == res.length - 1
			) {
				currentCnt = currentCnt + 1;
				if (res[currentIdx]['_attributes'] == undefined) {
					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
				}
				res[currentIdx]['_attributes']['rowSpan'][
					targetAttributeName
				] = currentCnt;
			} else {
				currentCnt = currentCnt + 1;
			}
		}
	} else {
		var currentCnt = 1;
		var currentIdx = 0;
		for (var i = 1; i < res.length; i++) {
			if (!compareValue(res, targetAttributeList, currentIdx, i)) {
				if (res[currentIdx]['_attributes'] == undefined) {
					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
				}
				if (currentCnt != 1) {
					res[currentIdx]['_attributes']['rowSpan'][
						targetAttributeName
					] = currentCnt;
				}
				currentCnt = 1;
				currentIdx = i;
			} else if (
				compareValue(res, targetAttributeList, currentIdx, i) &&
				i == res.length - 1
			) {
				currentCnt = currentCnt + 1;
				if (res[currentIdx]['_attributes'] == undefined) {
					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
				}
				if (currentCnt != 1) {
					res[currentIdx]['_attributes']['rowSpan'][
						targetAttributeName
					] = currentCnt;
				}
			} else {
				currentCnt = currentCnt + 1;
			}
		}
	}
	function compareValue(res, targetAttributeList, currentIdx, targetIdx) {
		for (var i = 0; i < targetAttributeList.length; i++) {
			if (
				res[currentIdx][targetAttributeList[i]] !=
				res[targetIdx][targetAttributeList[i]]
			) {
				return false;
			}
		}
		return true;
	}
}

const defaultData = {
	/* 검색옵션 */
	blocId: '',
	blocMstrList: [],
	ercId: null,
	ercList: [],
	cmCycle: 'CYC_MONTH',
	cmCycleList: [
		{ idx: 0, text: '연', value: 'CYC_YEAR' },
		{ idx: 1, text: '월', value: 'CYC_MONTH' },
		{ idx: 2, text: '일', value: 'CYC_DAY' },
		{ idx: 3, text: '시간', value: 'CYC_HOUR' },
	],
	defaultRange: {
		CYC_YEAR: 10,
		CYC_MONTH: 12,
		CYC_DAY: 30,
		CYC_HOUR: 0,
	},
	fromDt: '',
	toDt: '',
	dialogGrid: {
		data: [],
		option: {},
		column: [],
	},
	rowGrid: {
		data: [],
		option: {},
		column: [],
		buttonAuth: {
			add: false,
			remove: false,
			save: true,
			excel: false,
		},
		defaultRow: {
			comId: '',
			blocId: '',
			ercId: '',
			objMm: '',
			objYm: '',
			strtDt: '',
			endDt: '',
			notiChrg: '',
			baseChrg: '',
			rmrk: '',
			useQty: '',
			unitPrce: '',
			corrCoff: '',
			heatCoff: '',
			peakPow: '',
			contPow: '',
			regUserNo: '',
			regDttm: '',
			procUserNo: '',
			procDttm: '',
			rowStat: null,
		},
	},
	rowGridChart: Utility.defaultChartOption(true),
	xlsFileInfo: {
		rowGrid: {
			fileName: null,
			sheetName: null,
		},
	},
};

function numberFormatter({ value }) {
	if (value === undefined || (value === null) | (value === '')) {
		return '';
	}
	var newValue = value.toString().split('.');
	return (
		newValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') +
		(newValue[1] ? '.' + newValue[1] : '')
	);
}
function getStringDate(date) {
	var year = date.getFullYear();
	var month = String(date.getMonth() + 1);
	var day = String(date.getDate());

	if (month.length < 2) {
		month = '0' + month;
	}
	if (day.length < 2) {
		day = '0' + day;
	}
	return year + '-' + month + '-' + day;
}
</script>
<style scoped lang="scss">
::v-deep {
	.tui-grid-scrollbar-right-bottom {
		margin-bottom: -1px;
	}
}
@each $theme in dark, light {
	.v-application.#{$theme}-mode {
		.v-dialog {
			.v-card {
				&__title {
					color: map-deep-get($color, 'white', '0');
					@if $theme == dark {
						background-color: #2d3355;
						.v-btn {
							background-color: #2d3355;
						}
					} @else {
						background-color: #3f4d7d;
						.v-btn {
							background-color: #3f4d7d;
						}
					}
				}
			}
		}
	}
}
</style>
