<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="10">
							<v-row align="center" no-gutters>
								<v-col cols="3">
									<!-- 사업장 -->
									<component
										:is="'SelectBlocMstr'"
										ref="SelectBlocMstr"
										:parentPrgmId="myPrgmId"
										:textCols="7"
									/>
								</v-col>
								<v-col cols="3">
									<!-- 에너지 -->
									<component
										:is="'SelectMttList'"
										ref="SelectMttList"
										:parentPrgmId="myPrgmId"
										:label="'검침대상'"
										dataKey="readObjId"
										:sendParam="{ mttGrp: 'MTT_ENRG' }"
									/>
								</v-col>
								<v-col cols="3">
									<!-- 조회기간 -->
									<component
										ref="fromPicker"
										:is="'Datepicker'"
										:parentPrgmId="myPrgmId"
										:label="'조회기간'"
									/>
								</v-col>
								<v-col cols="3">
									<component
										:is="'SelectReadPlcPop'"
										:parentPrgmId="myPrgmId"
										:label="'검침개소'"
									/>
								</v-col>
							</v-row>
						</v-col>
						<v-col cols="2" class="d-flex justify-end align-center">
							<v-btn class="mr-1" :ripple="false" @click="search()">조회</v-btn>
							<BtnExcelDownload :parentPrgmId="myPrgmId" :gridName="gridName" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="center" no-gutters>
						<v-col :cols="9">
							<v-row align="center" no-gutters>
								<v-col :cols="4">
									<InputNumber
										:parentPrgmId="myPrgmId"
										label="월 마감 사용량"
										valueNm="totValDtSum"
										:disabled="true"
										:labelCols="5"
										:textCols="6"
									/>
								</v-col>
								<v-col :cols="4">
									<InputNumber
										:parentPrgmId="myPrgmId"
										label="월 마감 요금"
										valueNm="totCostValDtSum"
										:disabled="true"
										:labelCols="5"
										:textCols="6"
									/>
								</v-col>
								<v-col :cols="4">
									<component
										:is="'selectCodeList'"
										:parentPrgmId="myPrgmId"
										:label="'배분 기준'"
										dataKey="rpcDistCd"
										:sendParam="{ commGrpCd: 'EM_RPCDIST', useFg: '1' }"
									/>
								</v-col>
							</v-row>
							<v-row align="center" no-gutters>
								<v-col :cols="4">
									<InputNumber
										:parentPrgmId="myPrgmId"
										label="월 보정 사용량"
										valueNm="totValDtRtc"
										:labelCols="5"
										:textCols="6"
									/>
								</v-col>
								<v-col :cols="4">
									<InputNumber
										:parentPrgmId="myPrgmId"
										label="월 보정 요금"
										valueNm="totCostValDtRtc"
										:labelCols="5"
										:textCols="6"
									/>
								</v-col>
								<v-col :cols="4">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>
										{{ this.pageData.lavelComment }}
									</label>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3">
							<v-row align="center" no-gutters>
								<v-col :cols="12">
									<div class="d-flex justify-end align-center">
										<v-btn
											class="mr-1"
											:ripple="false"
											@click="distributionByDay()"
										>
											일자별 배분
										</v-btn>
										<v-btn :ripple="false" @click="reDistributionByDay()"
											>일자별 제배분</v-btn
										>
									</div>
								</v-col>
							</v-row>
							<v-row align="center" no-gutters>
								<v-col :cols="12">
									<div class="d-flex justify-end align-center">
										<v-btn
											class="mr-1"
											:ripple="false"
											@click="deleteDistributionByDay()"
											>보정자료 삭제</v-btn
										>
										<v-btn :ripple="false" @click="saveDistributionByDay()"
											>보정자료 저장</v-btn
										>
									</div>
								</v-col>
							</v-row>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" class="h50">
			<!-- 일일검침정보 목록-->
			<v-col :cols="12" class="h100">
				<v-card class="pt-5 pb-5">
					<div class="px-5" style="height:calc(100% - 76px)">
						<div ref="gridParent" class="w100 h100">
							<component
								class="w100 h100"
								ref="rowGrid"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								:editorGrid="true"
								@getRowsData="getRowData"
								@endEditing="endEditing"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" class="h30">
			<!-- 일일검침정보 목록-->
			<v-col :cols="6" class="h100">
				<v-card class="py-2 pl-4">
					<div ref="chartParent" id="test2" class="h100">
						<component
							class="w100 h100"
							ref="chart1"
							:is="loadChart ? 'Chart' : null"
							:chartName="'chart1'"
							:parentPrgmId="myPrgmId"
						/>
					</div>
				</v-card>
			</v-col>
			<v-col :cols="6" class="h100">
				<v-card class="py-2 pl-4">
					<div ref="chartParent2" id="test3" class="h100">
						<component
							class="w100 h100"
							ref="chart2"
							:is="loadChart ? 'Chart' : null"
							:chartName="'chart2'"
							:parentPrgmId="myPrgmId"
							@click="dayChrtClick"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
import { mapState, mapMutations, mapActions } from 'vuex';
import Search from '~/components/common/search';
import Grid from '~/components/common/Grid';
import Chart from '~/components/common/Chart';
import Utility from '~/plugins/utility';
import DateUtility from '~/plugins/dateUtility';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
import selectCodeList from '@/components/common/select/selectCodeList';
import SelectMttList from '@/components/common/select/SelectMttList';
import Datepicker from '~/components/common/Datepicker';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import BtnSearch from '~/components/common/button/BtnSearch';
import SelectReadPlcPop from '~/components/common/modal/SelectReadPlcPop';
import InputNumber from '~/components/common/input/InputNumber';

let myTitle;
const myPrgmId = 'PRG0067';
export default {
	mixins: [mixinGlobal],
	asyncData(context) {
		const myState = context.store.state;
		context.store.commit('setActiveMenuInfo', myState.menuData[myPrgmId]);
		myTitle = myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		SelectBlocMstr,
		selectCodeList,
		SelectMttList,
		BtnExcelDownload,
		Datepicker,
		Search,
		Grid,
		Chart,

		SelectReadPlcPop,
		BtnSearch,
		InputNumber,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			chartName: 'chart1',
			loadGrid: false,
			loadChart: false,
			unit: '',
		};
	},
	computed: {
		...mapState({
			isDarkMode: state => state.isDarkMode,
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkBlocId() {
			// 사업장 코드
			return this.pageData.blocId;
		},
		chkReadObjId() {
			this.pageData.energyList = this.pageData.readObjIdList;
			this.pageData.energyCd = this.pageData.readObjId;
			return this.pageData.readObjId;
		},
		totValDtSum() {
			return this.pageData.totValDtSum;
		},
		chkFacInfo() {
			console.log(
				'computed chkFacInfo : ',
				this.pageData.facInfo,
				this.pageData.facInfoList,
			);
			return this.pageData.facInfo;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkBlocId() {
			this.setPageData({ isFind: true });
		},
		chkReadObjId() {
			this.pageData.energyList = this.pageData.readObjIdList;
			this.pageData.energyCd = this.pageData.readObjId;
			this.setUnitLabel();

			this.setPageData({ isFind: true });
		},
		chkFacInfo() {
			// console.log("watch chkFacInfo : ", this.pageData.facInfo, this.pageData.facInfoList);
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {},
	created() {},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartYAxisData: 'setChartYAxisData',
			setChartXAxisData: 'setChartXAxisData',
			setChartSeries: 'setChartSeries',
			setChartOption: 'setChartOption',
			setChartTitle: 'setChartTitle',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		init() {
			console.log('init 시작');
			this.pageData.blocId = this.userInfo.blocId;
			this.gridColnumInit();
			this.layoutInit();
			this.gridInit();
			this.setChartData(this.pageData[this.gridName].data);
		},
		setUnitLabel() {
			var energyCd = this.pageData.energyCd;
			var unit = '';
			this.pageData.energyList.filter(item => {
				if (item.mttCd == energyCd) {
					unit = item.unit;
				}
			});
			this.unit = unit;
		},
		gridColnumInit() {
			console.log('gridColnumInit 시작');
			for (let i = 0; i < 24; i++) {
				for (let j = 0; j < 4; j++) {
					// myColumns.push(
					//     { header: i.toString().padStart(2, '0') + ":" + (j *15).toString().padStart(2, '0'), name:"totVal" + i.toString().padStart(2, '0') +  (j *15).toString().padStart(2, '0'), align:"right", width: 100,
					//         formatter({value}){
					//         if(value===null){
					//             return "0";
					//         }else{
					//             return value;
					//         }
					//         }
					//     }
					// );
					myColumns.push({
						header: '마감',
						name:
							'totVal' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0'),
						align: 'right',
						width: 100,
						formatter: numberFormatter,
						// formatter({value}){
						// if(value===null){
						//     return "0";
						// }else{
						//     return value;
						// }
						// }
					});
					myColumns.push({
						header: '마감',
						name:
							'totCostVal' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0'),
						align: 'right',
						width: 100,
						hidden: true,
						formatter: numberFormatter,
						// formatter({value}){
						// if(value===null){
						//     return "0";
						// }else{
						//     return value;
						// }
						// }
					});
					myColumns.push({
						header: '보정',
						name:
							'totValRtc' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0'),
						align: 'right',
						width: 100,
						editor: 'text',
						formatter: numberFormatter,
						// formatter({value}){
						// if(value===null){
						//     return "0";
						// }else{
						//     return value;
						// }
						// }
					});
					myColumns.push({
						header: '보정',
						name:
							'totCostValRtc' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0'),
						align: 'right',
						width: 100,
						hidden: true,
						formatter: numberFormatter,
						// formatter({value}){
						// if(value===null){
						//     return "0";
						// }else{
						//     return value;
						// }
						// }
					});

					// defaultRow에 컬럼 추가
					this.pageData.rowGrid.defaultRow[
						'totVal' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0')
					] = 0;
					this.pageData.rowGrid.defaultRow[
						'totValRtc' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0')
					] = 0;
					this.pageData.rowGrid.defaultRow[
						'totCostVal' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0')
					] = 0;
					this.pageData.rowGrid.defaultRow[
						'totCostValRtc' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0')
					] = 0;
				}
			}
			// console.log("this.pageData.rowGrid.defaultRow : ", this.pageData.rowGrid.defaultRow);
		},
		layoutInit() {
			console.log('layoutInit 시작');
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = 'calc(100% - ${searchFilterHeight}px)';
		},
		gridInit() {
			console.log('gridInit 시작');
			const gridHeight = this.$refs.gridParent.offsetHeight - 0;

			let myComplexColumns = [
				{
					header: '일 사용량',
					name: 'monthUse',
					childNames: ['totValDtSum', 'totValDtRtc'],
				},
				{
					header: '일 요금',
					name: 'monthCost',
					childNames: ['totCostValDtSum', 'totCostValDtRtc'],
				},
			];

			for (let i = 0; i < 24; i++) {
				for (let j = 0; j < 4; j++) {
					myComplexColumns.push({
						header:
							i.toString().padStart(2, '0') +
							':' +
							(j * 15).toString().padStart(2, '0'),
						name:
							'termUse' +
							i.toString().padStart(2, '0') +
							(j * 15).toString().padStart(2, '0'),
						childNames: [
							'totVal' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0'),
							'totCostVal' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0'),
							'totValRtc' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0'),
							'totCostValRtc' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0'),
						],
					});
				}
			}

			const myOptions = {
				columnOptions: {
					// frozenCount: 2,
					// frozenBorderWidth: 2,
					minWidth: 100,
					resizable: true,
				},
				header: {
					height: 65,
					complexColumns: myComplexColumns,
				},
				// scrollX: false,
			};

			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});
			this.loadGrid = true;
		},

		async getGridData() {
			console.log('getGridData 시작');
			this.loadGrid = false;
			this.loadChart = false;
			// console.log("this.pageData.facInfo : ", this.pageData.facInfo);
			// console.log("this.pageData.facInfo.readPlcId : ", this.pageData.facInfo.readPlcId);
			var params = {
				blocId:
					typeof this.pageData.blocId === 'number'
						? this.pageData.blocMstrList[this.pageData.blocId].blocId
						: this.pageData.blocId,
				readPlcId:
					this.pageData.facInfo.readPlcId != undefined
						? this.pageData.facInfo.readPlcId
						: this.pageData.readPlcId,
				readObjId: this.pageData.readObjId,
				dm: this.pageData.fromDt,
			};
			this.loadGrid = false;
			// console.debug("getGridData params : ", params);

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

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

			this.loadGrid = true;
			this.setUnitLabel();
			const data = this.pageData[this.gridName].data;
			let totValDtTmpSum = 0;
			let totCostValDtTmpSum = 0;

			let totValDtTmpRtc = 0;
			let totCostValDtTmpRtc = 0;
			for (let idx in data) {
				if (data[idx].totValDtSum == null || data[idx].totValDtSum == '') {
					totValDtTmpSum += 0;
				} else {
					totValDtTmpSum += data[idx].totValDtSum;
				}
				if (
					data[idx].totCostValDtSum == null ||
					data[idx].totCostValDtSum == ''
				) {
					totCostValDtTmpSum += 0;
				} else {
					totCostValDtTmpSum += data[idx].totCostValDtSum;
				}
				if (data[idx].totValDtRtc == null || data[idx].totValDtRtc == '') {
					totValDtTmpRtc += 0;
				} else {
					totValDtTmpRtc += data[idx].totValDtRtc;
				}

				if (
					data[idx].totCostValDtRtc == null ||
					data[idx].totCostValDtRtc == ''
				) {
					totCostValDtTmpRtc += 0;
				} else {
					totCostValDtTmpRtc += data[idx].totCostValDtRtc;
				}
			}

			this.pageData.totValDtSum = totValDtTmpSum;
			this.pageData.totCostValDtSum = totCostValDtTmpSum;

			this.pageData.totValDtRtc = totValDtTmpRtc.toFixed(0);
			this.pageData.totCostValDtRtc = totCostValDtTmpRtc.toFixed(0);
			// console.log("getGridData : ", totValDtTmpRtc, totCostValDtTmpRtc);
			// console.log("getGridData : ", this.pageData.totValDtRtc, this.pageData.totCostValDtRtc);

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

			this.$nextTick(() => {
				if (res.length > 0) {
					this.$refs[this.gridName].focus({
						rowKey: 0,
						setScroll: true,
					});
					this.getRowData(this.$refs[this.gridName].getData()[0]);
				} else {
					this.getRowData(null);
				}
			});
		},
		search() {
			console.log('search 시작');
			this.getGridData();
		},

		async setChartData(data) {
			console.log('setChartData 시작');
			//   console.log("차트 옵션 세팅 : ", data);
			let xAxisData = [];
			let seriesData = [];
			let seriesDataBaseChrg = {
				name: '마감',
				type: 'line',
				smooth: true,
				data: [],
			};
			let seriesDataRtcChrg = {
				name: '보정',
				type: 'line',
				smooth: true,
				data: [],
			};

			for (let idx in data) {
				xAxisData.push(data[idx].totDt);
				if (data[idx].totValDtSum == null || data[idx].totValDtSum == '') {
					seriesDataBaseChrg.data.push(0);
				} else {
					seriesDataBaseChrg.data.push(data[idx].totValDtSum);
				}
				if (data[idx].totValDtRtc == null || data[idx].totValDtRtc == '') {
					seriesDataRtcChrg.data.push(0);
				} else {
					seriesDataRtcChrg.data.push(data[idx].totValDtRtc);
				}
			}

			seriesData.push(seriesDataBaseChrg);
			seriesData.push(seriesDataRtcChrg);

			var chartOption = {
				grid: {
					top: '10%',
					// right: '8%',
				},
				yAxis: {
					type: 'value',
					nameLocation: 'middle',
					nameGap: 35,
					name: this.unit,
				},
			};

			//   console.log("setChartData xAxisData : ", xAxisData);
			//   console.log("setChartData seriesData : ", seriesData);
			this.setChartOption({ chartKey: this.chartName, value: chartOption });
			this.setChartXAxisData({ chartKey: this.chartName, value: xAxisData });
			this.setChartSeries({ chartKey: this.chartName, value: seriesData });
			this.loadChart = true;

			if (data.length > 0) {
				if (
					this.$refs[this.gridName] != undefined &&
					this.$refs[this.gridName].gridInstance != undefined
				) {
					this.$refs[this.gridName].gridInstance.invoke(
						'focus',
						data.rowKey,
						'readPlcNm',
						false,
					);
				}
			}
		},

		async getRowData(data) {
			console.log('getRowData 시작');
			this.loadChart = false;
			//   console.log("getRowData : ", data);
			let xAxisData = [];
			let seriesData = [];
			let seriesDataBaseChrg = {
				name: '마감',
				type: 'line',
				smooth: true,
				data: [],
			};
			let seriesDataRtcChrg = {
				name: '보정',
				type: 'line',
				smooth: true,
				data: [],
			};

			const title = [
				{
					text: data ? data.totDt : '',
					left: '10',
					bottom: '0',
					textStyle: {
						color: '#646774',
						fontSize: 16,
					},
				},
			];

			let totValDtTmpSum = 0;
			for (let i = 0; i < 24; i++) {
				for (let j = 0; j < 4; j++) {
					xAxisData.push(
						i.toString().padStart(2, '0') +
							':' +
							(j * 15).toString().padStart(2, '0'),
					);

					if (
						data === null ||
						data[
							'totVal' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0')
						] === undefined
					) {
						seriesDataBaseChrg.data.push(0);
						totValDtTmpSum += 0;
					} else {
						seriesDataBaseChrg.data.push(
							data[
								'totVal' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0')
							],
						);
						totValDtTmpSum +=
							data[
								'totVal' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0')
							];
					}
					if (
						data === null ||
						data[
							'totValRtc' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0')
						] === undefined
					) {
						seriesDataRtcChrg.data.push(0);
					} else {
						seriesDataRtcChrg.data.push(
							data[
								'totValRtc' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0')
							],
						);
						console.log();
					}
				}
			}

			//   data["totValDtRtc"] = totValDtTmpSum;
			//   this.$refs[this.gridName].getData()["totValDtRtc"] = totValDtTmpSum;
			//   this.$refs[this.gridName].gridInstance.invoke("setValue", data.rowKey, "totValDtRtc", totValDtTmpSum, false);

			seriesData.push(seriesDataBaseChrg);
			seriesData.push(seriesDataRtcChrg);

			var chartOption = {
				grid: {
					top: '10%',
					// right: '8%',
				},
				yAxis: {
					type: 'value',
					nameLocation: 'middle',
					nameGap: 20,
					name: 'kWh',
				},
			};

			// console.log("setChartData xAxisData : ", xAxisData);
			// console.log("setChartData seriesData : ", seriesData);
			this.setChartOption({ chartKey: 'chart2', value: chartOption });
			this.setChartXAxisData({ chartKey: 'chart2', value: xAxisData });
			this.setChartSeries({ chartKey: 'chart2', value: seriesData });
			this.setChartTitle({ chartKey: 'chart2', value: title });
			this.loadChart = true;
			if (data !== null) {
				this.validRowSum(data);
			}
		},
		async endEditing(event, data, gridName) {
			console.log('endEditing 시작');
			// console.log("endEditing event : ", event);
			// console.log("endEditing data : ", data);
			// console.log("endEditing gridName : ", gridName);

			// 필드 수정이 있을경우 메시지 및 입력값 검증 ....
			if (event.columnName == 'totValDtRtc') {
				// "totValDtRtc" <= 일자 사용량 수정이 있을경우
				// console.log("endEditing totValDtRtc ....");
				const inputTotValDtRtc =
					this.pageData.totValDtRtc != '' &&
					Number(this.pageData.totValDtRtc.toString().replace(/,/g, '')) > 0
						? Number(this.pageData.totValDtRtc.toString().replace(/,/g, ''))
						: 0;
				if (inputTotValDtRtc != '' && inputTotValDtRtc > 0) {
					// 배분 입력 값이 있을경우 비교 시작
					let tmpTotValDtRtc = 0;
					for (let i = 0; i < 24; i++) {
						for (let j = 0; j < 4; j++) {}
					}
				}
			}

			if (event.columnName.startsWith('totValRtc')) {
				// console.log("endEditing totValRtc ....", event.columnName);
				this.validRowSum(data);
			}

			this.loadChart = false;
			this.setChartData(this.$refs[this.gridName].getData());
			this.getRowData(data);
		},
		validRowSum(data) {
			const inputTotValDtRtc =
				this.pageData.totValDtRtc != '' &&
				Number(this.pageData.totValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totValDtRtc.toString().replace(/,/g, ''))
					: 0;

			let totValDtRtc = Number(data.totValDtRtc != '' ? data.totValDtRtc : 0);
			let totValDtRtcSum = 0;
			for (let i = 0; i < 24; i++) {
				for (let j = 0; j < 4; j++) {
					totValDtRtcSum += Number(
						data[
							'totValRtc' +
								i.toString().padStart(2, '0') +
								(j * 15).toString().padStart(2, '0')
						] != ''
							? data[
									'totValRtc' +
										i.toString().padStart(2, '0') +
										(j * 15).toString().padStart(2, '0')
							  ]
							: 0,
					);
				}
			}
			if (totValDtRtc.toFixed(2) != totValDtRtcSum.toFixed(2)) {
				console.log('endEditing : ', totValDtRtc, totValDtRtcSum);
				this.pageData.lavelComment =
					data.totDt +
					'보정값의 합이 ' +
					(totValDtRtc - totValDtRtcSum).toFixed(3) +
					'차이가 발생하였습니다.'; // "배분 수기 보정시 계산 정보 입니다..."
			} else {
				this.pageData.lavelComment = this.pageData.defaultLavelComment;
			}
		},
		validAllRowsSum() {
			let retVal = true;
			const inputTotValDtRtc =
				this.pageData.totValDtRtc != '' &&
				Number(this.pageData.totValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totValDtRtc.toString().replace(/,/g, ''))
					: 0;
			const inputTotCostValDtRtc =
				this.pageData.totCostValDtRtc != '' &&
				Number(this.pageData.totCostValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totCostValDtRtc.toString().replace(/,/g, ''))
					: 0;

			let tmpTotValDtRtcSum = 0;
			for (const item of this.$refs[this.gridName].getData()) {
				const tmpTotValRtcSum = 0;

				for (let i = 0; i < 24; i++) {
					for (let j = 0; j < 4; j++) {
						tmpTotValRtcSum += Number(
							item[
								'totValRtc' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0')
							],
						);
					}
				}

				if (tmpTotValRtcSum.toFixed(0) != Number(item.totValDtRtc).toFixed(0)) {
					retVal = false;
					console.log(
						'validAllRowsSum row fali.. : ',
						item,
						tmpTotValRtcSum,
						item.totValDtRtc,
					);
				}
				tmpTotValDtRtcSum += Number(item.totValDtRtc);
			}

			if (
				retVal &&
				tmpTotValDtRtcSum.toFixed(0) != Number(inputTotValDtRtc).toFixed(0)
			) {
				retVal = false;
				console.log(
					'validAllRowsSum all row fali.. : ',
					item,
					tmpTotValDtRtcSum,
					inputTotValDtRtc,
				);
			}

			return retVal;
		},
		async distributionByDay() {
			console.log('distributionByDay 시작');
			const inputTotValDtRtc =
				this.pageData.totValDtRtc != '' &&
				Number(this.pageData.totValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totValDtRtc.toString().replace(/,/g, ''))
					: 0;
			const inputTotCostValDtRtc =
				this.pageData.totCostValDtRtc != '' &&
				Number(this.pageData.totCostValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totCostValDtRtc.toString().replace(/,/g, ''))
					: 0;
			const inputTotValDtSum = Number.isFinite(this.pageData.totValDtSum)
				? this.pageData.totValDtSum
				: Number(this.pageData.totValDtSum.toString().replace(/,/g, ''));
			const inputTotCostValDtSum = Number.isFinite(
				this.pageData.totCostValDtSum,
			)
				? this.pageData.totCostValDtSum
				: Number(this.pageData.totCostValDtSum.toString().replace(/,/g, ''));
			let rowIdx = 0;
			if (inputTotValDtSum != '' && inputTotValDtSum > 0) {
				//
				for (const item of this.$refs[this.gridName].getData()) {
					let tmpTotValDtRtc = 0;
					let tmpTotCostValDtRtc = 0;
					if (inputTotValDtSum != '' && inputTotValDtSum > 0) {
						tmpTotValDtRtc =
							inputTotValDtRtc * (item.totValDtSum / inputTotValDtSum);
						tmpTotCostValDtRtc =
							inputTotCostValDtSum > 0
								? inputTotCostValDtRtc *
								  (item.totCostValDtSum / inputTotCostValDtSum)
								: 0;
						this.$refs[this.gridName].gridInstance.invoke(
							'setValue',
							item.rowKey,
							'totValDtRtc',
							tmpTotValDtRtc.toFixed(3),
							false,
						);
						this.$refs[this.gridName].gridInstance.invoke(
							'setValue',
							item.rowKey,
							'totCostValDtRtc',
							tmpTotCostValDtRtc.toFixed(3),
							false,
						);

						for (let i = 0; i < 24; i++) {
							for (let j = 0; j < 4; j++) {
								if (item.totValDtSum != 0) {
									const itemtotValRtc =
										tmpTotValDtRtc *
										(item[
											'totVal' +
												i.toString().padStart(2, '0') +
												(j * 15).toString().padStart(2, '0')
										] /
											item.totValDtSum);
									this.$refs[this.gridName].gridInstance.invoke(
										'setValue',
										item.rowKey,
										'totValRtc' +
											i.toString().padStart(2, '0') +
											(j * 15).toString().padStart(2, '0'),
										itemtotValRtc.toFixed(3),
										false,
									);
								} else {
									this.$refs[this.gridName].gridInstance.invoke(
										'setValue',
										item.rowKey,
										'totValRtc' +
											i.toString().padStart(2, '0') +
											(j * 15).toString().padStart(2, '0'),
										0,
										false,
									);
								}

								if (item.totCostValDtSum != 0) {
									const itemtotCostValRtc =
										item.totValDtSum > 0
											? tmpTotCostValDtRtc *
											  (item[
													'totCostVal' +
														i.toString().padStart(2, '0') +
														(j * 15).toString().padStart(2, '0')
											  ] /
													item.totCostValDtSum)
											: 0;
									this.$refs[this.gridName].gridInstance.invoke(
										'setValue',
										item.rowKey,
										'totCostValRtc' +
											i.toString().padStart(2, '0') +
											(j * 15).toString().padStart(2, '0'),
										itemtotCostValRtc.toFixed(3),
										false,
									);
								} else {
									this.$refs[this.gridName].gridInstance.invoke(
										'setValue',
										item.rowKey,
										'totCostValRtc' +
											i.toString().padStart(2, '0') +
											(j * 15).toString().padStart(2, '0'),
										0,
										false,
									);
								}
							}
						}
					}
					if (rowIdx == 0) {
						this.getRowData(this.$refs[this.gridName].getData()[0]);
						this.$refs[this.gridName].gridInstance.invoke(
							'focus',
							0,
							'totValDtSum',
							true,
						);
					}
					rowIdx++;
				}
			}
			this.setChartData(this.$refs[this.gridName].getData());
		},
		async reDistributionByDay() {
			console.log('reDistributionByDay 시작');
			let tmpRowData = this.$refs[this.gridName].getData();
			// console.log("reDistributionByDay tmpRowData : ", tmpRowData);
			const inputTotValDtRtc =
				this.pageData.totValDtRtc != '' &&
				Number(this.pageData.totValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totValDtRtc.toString().replace(/,/g, ''))
					: 0;
			const inputTotCostValDtRtc =
				this.pageData.totCostValDtRtc != '' &&
				Number(this.pageData.totCostValDtRtc.toString().replace(/,/g, '')) > 0
					? Number(this.pageData.totCostValDtRtc.toString().replace(/,/g, ''))
					: 0;
			let inputTotValDtSum = 0;
			let inputTotCostValDtSum = 0;

			for (const item of tmpRowData) {
				inputTotValDtSum +=
					item.totValDtRtc != '' ? Number(item.totValDtRtc) : 0;
				inputTotCostValDtSum +=
					item.totCostValDtRtc != '' ? Number(item.totCostValDtRtc) : 0;

				let tmpTotValDtRtc = 0;
				let tmpTotCostValDtRtc = 0;
				for (let i = 0; i < 24; i++) {
					for (let j = 0; j < 4; j++) {
						tmpTotValDtRtc += Number(
							item[
								'totValRtc' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0')
							],
						);
						tmpTotCostValDtRtc += Number(
							item[
								'totCostValRtc' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0')
							],
						);
					}
				}

				item['tmpTotValDtRtc'] = tmpTotValDtRtc;
				item['tmpTotCostValDtRtc'] = tmpTotCostValDtRtc;

				// console.log("reDistributionByDay tmpTotValDtRtc : ", tmpTotValDtRtc, tmpTotCostValDtRtc);
			}
			// console.log("reDistributionByDay inputTotValDtSum : ", inputTotValDtSum);
			// console.log("reDistributionByDay inputTotCostValDtSum : ", inputTotCostValDtSum);
			// console.log("reDistributionByDay tmpRowData : ", tmpRowData);

			if (inputTotValDtSum != '' && inputTotValDtSum > 0) {
				for (const item of tmpRowData) {
					const tmpTotValDtRtc =
						Number(item.inputTotValDtSum) != 0
							? inputTotValDtRtc * (Number(item.totValDtRtc) / inputTotValDtSum)
							: 0;
					const tmpTotCostValDtRtc =
						Number(item.inputTotCostValDtSum) != 0
							? inputTotCostValDtRtc *
							  (Number(item.totCostValDtRtc) / inputTotCostValDtSum)
							: 0;

					this.$refs[this.gridName].gridInstance.invoke(
						'setValue',
						item.rowKey,
						'totValDtRtc',
						tmpTotValDtRtc.toFixed(3),
						false,
					);
					this.$refs[this.gridName].gridInstance.invoke(
						'setValue',
						item.rowKey,
						'totCostValDtRtc',
						tmpTotCostValDtRtc.toFixed(3),
						false,
					);

					for (let i = 0; i < 24; i++) {
						for (let j = 0; j < 4; j++) {
							const tmpTotValRtc =
								Number(item.tmpTotValDtRtc) != 0
									? tmpTotValDtRtc.toFixed(3) *
									  (Number(
											item[
												'totValRtc' +
													i.toString().padStart(2, '0') +
													(j * 15).toString().padStart(2, '0')
											],
									  ) /
											Number(item.tmpTotValDtRtc))
									: 0;
							const tmpCostTotValRtc =
								Number(item.tmpTotCostValDtRtc) != 0
									? tmpTotCostValDtRtc.toFixed(3) *
									  (Number(
											item[
												'totCostValRtc' +
													i.toString().padStart(2, '0') +
													(j * 15).toString().padStart(2, '0')
											],
									  ) /
											Number(item.tmpTotCostValDtRtc))
									: 0;
							this.$refs[this.gridName].gridInstance.invoke(
								'setValue',
								item.rowKey,
								'totValRtc' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0'),
								tmpTotValRtc.toFixed(3),
								false,
							);
							this.$refs[this.gridName].gridInstance.invoke(
								'setValue',
								item.rowKey,
								'totCostValRtc' +
									i.toString().padStart(2, '0') +
									(j * 15).toString().padStart(2, '0'),
								tmpCostTotValRtc.toFixed(3),
								false,
							);
						}
					}
				}
			}
			if (tmpRowData.length > 0) {
				this.getRowData(this.$refs[this.gridName].getData()[0]);
				this.$refs[this.gridName].gridInstance.invoke(
					'focus',
					0,
					'totValDtSum',
					true,
				);
			}
			this.setChartData(this.$refs[this.gridName].getData());
		},
		async saveDistributionByDay() {
			console.log('saveDistributionByDay 시작');

			if (!this.validAllRowsSum()) {
				alert('보정 자료의 값이 차이가 존재 합니다.\n 재보정이 필요합니다.');
				return;
			}

			if (confirm('마감 보정 자료를 저장하시겠습니까?') == false) {
				return;
			}

			let dataArr = this.$refs[this.gridName].getData();
			// console.log("saveDistributionByDay dataArr : ", dataArr);
			const sendParam = {
				datas: {
					dsDistributionByDay: dataArr.map(item => ({
						...item,
					})),
				},
				params: {},
			};
			await this.postUpdateApi({
				apiKey: 'saveReadPlcUseData',
				sendParam: sendParam,
			});

			this.$nextTick(() => {
				this.setPageData({ isFind: true });
			});
		},
		async deleteDistributionByDay() {
			console.log('deleteDistributionByDay 시작');

			if (confirm('정말 삭제하시겠습니까?') == false) {
				return;
			}
			var params = {
				blocId:
					typeof this.pageData.blocId === 'number'
						? this.pageData.blocMstrList[this.pageData.blocId].blocId
						: this.pageData.blocId,
				readPlcId:
					this.pageData.facInfo.readPlcId != undefined
						? this.pageData.facInfo.readPlcId
						: this.pageData.readPlcId,
				readObjId: this.pageData.readObjId,
				dm: this.pageData.fromDt,
			};

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

			this.$nextTick(() => {
				this.setPageData({ isFind: true });
			});
			this.search();
		},
		dayChrtClick(data) {
			const tmpRowName = data.name.replace(':', '');
			// console.log("seriesName : ", data.seriesName, data.name, tmpRowName);
			const rowKey = this.$refs[this.gridName].gridInstance.invoke(
				'getFocusedCell',
			).rowKey;
			this.$refs[this.gridName].gridInstance.invoke(
				'startEditing',
				rowKey,
				'totValRtc' + tmpRowName,
				true,
			);
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	mttTp: '',
	mttTpList: [],
	sendMttParam: {},
	readPlcId: 'RPC000001',
	readObjId: 'ROI000001',
	readObjIdList: [],
	commCd: '',
	commCdList: [],
	cmCycle: 'CYC_MONTH',
	blocId: '',
	blocMstrList: [],

	facInfoList: [],
	facInfo: {},

	mttGrp: 'MTT_ENRG',

	fromDt: Utility.setFormatDate(DateUtility.addMonth(-1), 'YYYYMM'),

	isFind: false,

	totValDtSum: 0,
	totCostValDtSum: 0,
	totValDtRtc: 0,
	totCostValDtRtc: 0,
	rpcDistCd: '',
	rpcDistCdList: [],

	defaultLavelComment: '배분 수기 보정시 계산 정보 입니다...',
	lavelComment: '배분 수기 보정시 계산 정보 입니다...',

	/* data 세팅 - sms 목록 */
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			comId: '',
			blocId: '',
			readPlcId: '',
			readPlcNm: '',
			readObjId: '',
			totValDtSum: 0,
			totValDtRtc: 0,
			totCostValDtSum: 0,
			totCostValDtRtc: 0,
		},
	},

	defaultRange: {
		CYC_MONTH: 0,
	},
	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			// 엑셀변환시 데이타 가공이 추가로 필요하게 된다면 여기에 가공된 rowData 를 넣어야 할듯
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},

	// chart 설정
	chart1: Utility.defaultChartOption(true),
	chart2: Utility.defaultChartOption(true),
};

let myColumns = [
	{ header: '검침개소', name: 'readPlcNm', width: 150 },
	{
		header: '일자',
		name: 'totDt',
		align: 'center',
		width: 100,
		formatter({ value }) {
			if (value === null) {
				return '';
			} else {
				return value;
			}
		},
	},
	{
		header: '마감',
		name: 'totValDtSum',
		align: 'right',
		width: 150,
		formatter: numberFormatter,
	},
	{
		header: '보정',
		name: 'totValDtRtc',
		align: 'right',
		width: 150,
		editor: 'text',
		formatter: numberFormatter,
	},
	{
		header: '마감',
		name: 'totCostValDtSum',
		align: 'right',
		width: 150,
		formatter: numberFormatter,
	},
	{
		header: '보정',
		name: 'totCostValDtRtc',
		align: 'right',
		width: 150,
		formatter: numberFormatter,
	},
];

function numberFormatter({ value }) {
	return Utility.setFormatIntDecimal(Number(value), 2);
}
</script>
