<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="2">
							<!-- 에너지 -->
							<component
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
								:label="'에너지'"
							/>
						</v-col>
						<v-col cols="2">
							<!-- 주기 -->
							<component :is="'SelectCmCycle'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col cols="4">
							<!-- 조회기간 -->
							<!-- <component :is="swichDatePicker" :parentPrgmId="myPrgmId" /> -->
							<DatePicker
								:parentPrgmId="myPrgmId"
								label="조회기간"
								:labelCols="3"
								:textCols="9"
							/>
						</v-col>
						<v-col cols="2" class="d-flex justify-end align-center">
							<BtnSearch @click="search" class="mr-1" />
							<BtnExcelDownload :parentPrgmId="myPrgmId" :gridName="gridName" />
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="4">
							<!-- 공정/설비 -->
							<component
								:is="'FtnPlcMultiPop'"
								:parentPrgmId="myPrgmId"
								:labelCols="2"
								:textCols="10"
							/>
						</v-col>
						<v-col :cols="2">
							<v-radio-group v-model="radioButtonData" row hide-details dense>
								<v-col :cols="4">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>
										구분
									</label>
								</v-col>
								<v-radio
									label="사용량"
									value="0"
									on-icon="mdi-record-circle"
									:color="isDarkMode ? '#1b74d7' : '#4777d9'"
									:ripple="false"
								></v-radio>
								<v-radio
									label="비용"
									value="1"
									on-icon="mdi-record-circle"
									:color="isDarkMode ? '#1b74d7' : '#4777d9'"
									:ripple="false"
								></v-radio>
							</v-radio-group>
						</v-col>
						<v-col :cols="2">
							<v-row class="search-box">
								<v-col :cols="6">
									<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="6">
									<v-checkbox
										v-model="sumChkValue"
										:color="isDarkMode ? '#fff' : '#4777d9'"
									></v-checkbox>
								</v-col>
							</v-row>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" style="height: calc(100vh - 230px)">
			<v-col>
				<v-card>
					<div ref="chartParent" style="height: 50%">
						<component
							class="w100 h100"
							:is="loadChart ? 'Chart' : null"
							:parentPrgmId="myPrgmId"
							:chartName="'rowGridChart'"
						/>
					</div>
					<!-- <p class="custom-text-2 font-weight-bold text-right text-color--non-activate" v-if="unit"> 단위 : {{unit}}</p> -->
					<v-card-title>
						<!-- 차트와 그리드 사이 공백을 위한 공간 -->
					</v-card-title>
					<div ref="gridParent" class="px-5" style="height: 43%">
						<component
							:is="loadGrid ? 'Grid' : null"
							:gridName="gridName"
							:parentPrgmId="myPrgmId"
							ref="rowGrid"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstrForPop';
import SelectEnergy from '@/components/common/select/SelectEnergyForPop';
import SelectCmCycle from '@/components/common/select/SelectCmCycle';

import SelectDate from '~/components/common/select/SelectDate';
import SelectDateVc from '~/components/common/select/SelectDateVc';
import FtnPlcMultiPop from '~/components/common/modal/FtnPlcMultiPop2';

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 DatePicker from '~/components/common/Datepicker';
import mixinGlobal from '@/mixin/global.js';
let myTitle;
//const myPrgmId = "PRG0022";
let myPrgmId;
export default {
	mixins: [mixinGlobal],
	async asyncData(context) {
		const myState = context.store.state;
		// context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
		// myTitle = myState.activeMenuInfo.menuNm;
		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: {
		SelectBlocMstr,
		SelectEnergy,
		SelectCmCycle,
		SelectDate,
		SelectDateVc,
		FtnPlcMultiPop,
		BtnSearch,
		BtnExcelDownload,
		Utility,
		Grid,
		Chart,
		DatePicker,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			loadChart: false,
			radioButtonData: '0', // 0: 사용량, 1: 비용
			unit: '', // 그리드 우상단 라벨
			apiKey: 'selectEnergyUseReadYear',
			locKind: 'LOC_COM', // defaultValue
			upEccId: 'PLC00001', // defaultValue
			qtyLength: [],
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
			isDarkMode: state => state.isDarkMode,
		}),
		swichDatePicker() {
			let picker = 'SelectDateVc';
			if (
				this.pageData.cmCycle == 'CYC_MONTH' ||
				this.pageData.cmCycle == 'CYC_YEAR'
			) {
				picker = 'SelectDate';
			}
			return picker;
		},
		sumChkValue: {
			get() {
				return this.pageData.chkSum;
			},
			set(value) {
				return this.setPageData({ chkSum: value });
			},
		},
		chkIsFind() {
			return this.pageData.isFind;
		},
		myCmCycle() {
			return this.pageData.cmCycle;
		},
		chkBlocCd() {
			return this.pageData.blocId;
		},
		chkEnergyCd() {
			return this.pageData.energyCd;
		},
		chkFacInfo() {
			return this.pageData.facInfo;
		},
		initFlag() {
			if (
				this.pageData.energyList.length > 0 &&
				this.pageData.blocMstrList.length > 0
			) {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		sumChkValue(val) {
			this.setPageData({ isFind: true });
		},
		chkIsFind(val) {
			if (val) this.search();
		},
		myCmCycle: function(val) {},
		chkBlocCd() {},
		chkEnergyCd() {
			this.setUnitLabel();
		},
		chkFacInfo() {
			this.setPageData({ isFind: true });
		},
		radioButtonData() {
			this.setPageData({ isFind: true });
		},
		initFlag(val) {
			if (val) {
				this.init();
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {},
	mounted() {},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartXAxisData: 'setChartXAxisData',
			setChartSeries: 'setChartSeries',
			setChartOption: 'setChartOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		init() {
			this.layoutInit();
			this.gridInit();
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		async search() {
			this.setLocalStorage();
			await this.getFacList();
		},
		setLocalStorage() {
			if (this.pageData.energyCd !== '' && this.pageData.energyCd != null) {
				localStorage.setItem(
					myPrgmId + 'SelectedEnergyCd',
					this.pageData.energyCd,
				);
			}
			if (this.pageData.blocId !== '' && this.pageData.blocId != null) {
				localStorage.setItem(myPrgmId + 'SelectedBlocCd', this.pageData.blocId);
			}
		},
		setUnitLabel() {
			this.unit = this.pageData.energyList[this.pageData.energyCd].unit
				? this.pageData.energyList[this.pageData.energyCd].unit
				: 'kwh';
			if (this.apiKey.search('Cost') > 0) {
				this.unit = '원';
			}
		},
		setApiKey() {
			var apiKeyMapper = {
				/*
          cycValue + radioButtonData
          사용량 API  : ~0
          비용 API    : ~1
         */
				CYC_YEAR0: 'selectEnergyUseReadYear',
				CYC_MONTH0: 'selectEnergyUseReadMonth',
				CYC_DAY0: 'selectEnergyUseReadDay',
				CYC_HOUR0: 'selectEnergyUseReadHour',
				CYC_YEAR1: 'selectEnergyUseReadYearCost',
				CYC_MONTH1: 'selectEnergyUseReadMonthCost',
				CYC_DAY1: 'selectEnergyUseReadDayCost',
				CYC_HOUR1: 'selectEnergyUseReadHourCost',
			};
			this.apiKey = apiKeyMapper[this.pageData.cmCycle + this.radioButtonData];
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 46;
			const myOptions = {
				// scrollX: false,
				setScroll: true,
				columnOptions: {
					//frozenCount:2,
					minWidth: 100,
					resizable: true,
				},
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			this.getFacList();
		},
		async getFacList() {
			this.loadChart = false;
			this.pageData.rowGrid.data = [];
			var facList = null;

			this.setApiKey();

			if (
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.energyList.length > 0
			) {
				this.setUnitLabel();

				var apiParameters = {
					blocId: this.pageData.blocMstrList[this.chkBlocCd].blocId, //"BL0001",
					readObjId: this.pageData.energyList[this.chkEnergyCd].cd,
					locKind: this.pageData.facInfo.locKind
						? this.pageData.facInfo.locKind
						: this.locKind,
					upEccId: this.pageData.facInfo.eccId
						? this.pageData.facInfo.eccId
						: this.eccId,
				};

				facList = await this.postApiReturn({
					apiKey: 'selectEnergyUseReadDnPlc',
					resKey: 'energyUseReadDnPlc',
					sendParam: apiParameters,
				});

				const isRange =
					this.pageData.defaultRange[this.pageData.cmCycle] === 0
						? false
						: true;
				apiParameters['toObjDt'] = isRange
					? this.pageData.toDt
					: this.pageData.fromDt;
				apiParameters['fromObjDt'] = this.pageData.fromDt;
				apiParameters['eccId'] = facList.map(item => item.eccId);
				apiParameters['eccNm'] = facList.map(item => item.eccNm);

				this.setQtyParameters(apiParameters);
				await this.getGridData(apiParameters);
			} else {
				this.setPageData({ isFind: false });
			}
			this.setPageData({ isFind: false });
		},
		setQtyParameters(params) {
			switch (this.pageData.cmCycle) {
				case 'CYC_YEAR':
					var qtyNumber;
					var year = parseInt(params['fromObjDt']);

					for (var i = 0; i < 10; i++) {
						qtyNumber = (i + 1).toString().padStart(2, '0');
						params['qty' + qtyNumber] = (year++).toString();
					}
					break;
				case 'CYC_MONTH':
					var qtyNumber;
					var date = new Date(
						params['fromObjDt'].substr(0, 4),
						params['fromObjDt'].substr(4, 2),
					);
					date.setMonth(date.getMonth() - 1);

					for (var i = 0; i < 12; i++) {
						qtyNumber = (i + 1).toString().padStart(2, '0');
						params['qtyY' + qtyNumber] = String(date.getFullYear());
						params['qtyM' + qtyNumber] = String(date.getMonth() + 1).padStart(
							2,
							'0',
						);
						date.setMonth(date.getMonth() + 1);
					}
					break;
				case 'CYC_DAY':
					var qtyNumber;
					var date = new Date(
						params['fromObjDt'].substr(0, 4),
						params['fromObjDt'].substr(4, 2),
						params['fromObjDt'].substr(6, 2),
					);
					date.setMonth(date.getMonth() - 1);

					for (var i = 0; i < 31; i++) {
						qtyNumber = (i + 1).toString().padStart(2, '0');
						params['qty' + qtyNumber] =
							String(date.getFullYear()) +
							String(date.getMonth() + 1).padStart(2, '0') +
							String(date.getDate()).padStart(2, '0');
						date.setDate(date.getDate() + 1);
					}
					break;
				case 'CYC_HOUR':
					break;
			}
		},
		makeColumnList(params) {
			var colNameList = [
				{ header: '에너지', name: 'readObjNm', align: 'center', width: '200' },
				{ header: '구분', name: 'eccNm', align: 'left', width: '200' },
			];

			switch (this.pageData.cmCycle) {
				case 'CYC_YEAR':
					var qtyNumber, qtyStr;
					for (var i = 0; i < 10; i++) {
						qtyNumber = (i + 1).toString().padStart(2, '0');
						qtyStr = 'qty' + qtyNumber;
						if (
							parseInt(params[qtyStr]) >= parseInt(params['fromObjDt']) &&
							parseInt(params[qtyStr]) <= parseInt(params['toObjDt'])
						) {
							colNameList.push({
								header: params[qtyStr],
								name: qtyStr,
								align: 'right',
								excelType: 'number',
								excelFormatter: '2',
								formatter: numberFormatter,
							});
						}
					}
					break;
				case 'CYC_MONTH':
					var qtyNumber;
					var qtyY;
					var qtyM;
					for (var i = 0; i < 12; i++) {
						qtyNumber = (i + 1).toString().padStart(2, '0');
						qtyStr = 'qty' + qtyNumber;
						qtyY = 'qtyY' + qtyNumber;
						qtyM = 'qtyM' + qtyNumber;
						if (
							parseInt(params[qtyY] + params[qtyM]) >=
								parseInt(params['fromObjDt']) &&
							parseInt(params[qtyY] + params[qtyM]) <=
								parseInt(params['toObjDt'])
						) {
							colNameList.push({
								header: params[qtyY] + '/' + params[qtyM],
								name: qtyStr,
								align: 'right',
								excelType: 'number',
								excelFormatter: '2',
								formatter: numberFormatter,
							});
						}
					}
					break;
				case 'CYC_DAY':
					var qtyNumber, qtyStr;
					for (var i = 0; i < 31; i++) {
						qtyNumber = (i + 1).toString().padStart(2, '0');
						qtyStr = 'qty' + qtyNumber;
						if (
							parseInt(params[qtyStr]) >= parseInt(params['fromObjDt']) &&
							parseInt(params[qtyStr]) <= parseInt(params['toObjDt'])
						) {
							colNameList.push({
								header:
									params[qtyStr].substr(4, 2) +
									'/' +
									params[qtyStr].substr(6, 2),
								name: qtyStr,
								align: 'right',
								excelType: 'number',
								excelFormatter: '2',
								formatter: numberFormatter,
							});
						}
					}
					break;
				case 'CYC_HOUR':
					var qtyNumber, qtyStr;
					for (var i = 0; i < 24; i++) {
						qtyNumber = i.toString().padStart(2, '0');
						qtyStr = 'qty' + qtyNumber;
						colNameList.push({
							header: i.toString().padStart(1, '0') + '시',
							name: qtyStr,
							align: 'right',
							excelType: 'number',
							excelFormatter: '2',
							formatter: numberFormatter,
						});
					}
					break;
			}

			return colNameList;
		},

		addChkSumRowData(res) {
			var chkSumRowData = {};
			var columnListMap = {
				CYC_YEAR: [
					'qty01',
					'qty02',
					'qty03',
					'qty04',
					'qty05',
					'qty06',
					'qty07',
					'qty08',
					'qty09',
					'qty10',
				],
				CYC_MONTH: [
					'qty01',
					'qty02',
					'qty03',
					'qty04',
					'qty05',
					'qty06',
					'qty07',
					'qty08',
					'qty09',
					'qty10',
					'qty11',
					'qty12',
				],
				CYC_DAY: [
					'qty01',
					'qty02',
					'qty03',
					'qty04',
					'qty05',
					'qty06',
					'qty07',
					'qty08',
					'qty09',
					'qty10',
					'qty11',
					'qty12',
					'qty13',
					'qty14',
					'qty15',
					'qty16',
					'qty17',
					'qty18',
					'qty19',
					'qty20',
					'qty21',
					'qty22',
					'qty23',
					'qty24',
					'qty25',
					'qty26',
					'qty27',
					'qty28',
					'qty29',
					'qty30',
					'qty31',
				],
				CYC_HOUR: [
					'qty00',
					'qty01',
					'qty02',
					'qty03',
					'qty04',
					'qty05',
					'qty06',
					'qty07',
					'qty08',
					'qty09',
					'qty10',
					'qty11',
					'qty12',
					'qty13',
					'qty14',
					'qty15',
					'qty16',
					'qty17',
					'qty18',
					'qty19',
					'qty20',
					'qty21',
					'qty22',
					'qty23',
				],
			};
			var columnList = columnListMap[this.myCmCycle];

			if (this.sumChkValue && res.length && res.length > 0) {
				chkSumRowData['eccNm'] = this.pageData.facInfo.eccNm;
				chkSumRowData['eccId'] = this.pageData.facInfo.eccId;
				chkSumRowData['readObjNm'] = res[0]['readObjNm'];
				chkSumRowData['readObjId'] = res[0]['readObjId'];
				chkSumRowData['comId'] = res[0]['comId'];

				for (var i = 0; i < columnList.length; i++) {
					chkSumRowData[columnList[i]] = 0;
				}

				for (var i = 0; i < res.length; i++) {
					for (var j = 0; j < columnList.length; j++) {
						var oldValue =
							chkSumRowData[columnList[j]] != undefined
								? chkSumRowData[columnList[j]]
								: 0;
						var newValue =
							res[i][columnList[j]] != undefined ? res[i][columnList[j]] : 0;
						chkSumRowData[columnList[j]] =
							Math.round((oldValue + newValue) * 100) / 100;
					}
				}

				// res.unshift(chkSumRowData);
				res.push(chkSumRowData);
			}
		},

		async getGridData(params) {
			var res = null;
			this.loadGrid = false;

			let colNameList = await this.makeColumnList(params);

			try {
				res = await this.postApiReturn({
					apiKey: this.apiKey,
					resKey: 'energyUseRead',
					sendParam: params,
				});
			} catch (error) {
				res = [];
			}
			// res = await this.postApiReturn({
			//   apiKey: this.apiKey,
			//   resKey: "energyUseRead",
			//   sendParam: params
			// });

			// if(res.length < 1){
			//   for(var i=0;i<params.eccNm.length;i++){
			//     res.push({
			//       readObjNm : this.pageData.energyList[this.pageData.energyCd].enrgNm,
			//       eccNm:params.eccNm[i]
			//     })
			//   }
			// }

			this.addChkSumRowData(res);

			if (res.length && res.length > 0) {
				Object.assign(res[0], {
					_attributes: { rowSpan: { readObjNm: res.length } },
				});
			}

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

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

		setChartData(data) {
			this.$store.state.pageData[this.myPrgmId].rowGridChart.series = [];
			// if(!data.length){
			//   return;
			// }
			let exceptionColumList = ['에너지', '구분'];
			let xAxisData = [];
			let seriesData = [];

			var keyList = this.pageData[this.gridName].column.filter(el => {
				return !exceptionColumList.includes(el.header);
			});

			xAxisData = keyList.map(el => el.header);
			seriesData = data.map(item => ({
				name: item.eccNm,
				type: 'line',
				data: keyList.map(obj => item[obj.name] || 0),
			}));
			var _this = this;
			var chartOption = {
				grid: {
					top: '3%',
					// right: '8%',
				},
				yAxis: {
					type: 'value',
					nameLocation: 'middle',
					nameGap: 45,
					name: _this.unit,
				},
				xAxis: {
					data: xAxisData,
				},
				series: seriesData,
			};

			this.setChartOption({ chartKey: 'rowGridChart', value: chartOption });

			this.loadChart = true;
		},
	},
};

const defaultData = {
	isFind: false,
	blocId: '',
	blocMstrList: [],
	energyCd: '',
	energyList: [],
	cmCycle: 'CYC_HOUR',
	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: '',
	facInfo: {},
	chkSum: false,

	rowGrid: {
		data: [],
		option: {},
		column: [],
	},

	modalData: {},
	isMulti: false,

	rowGridChart: Utility.defaultChartOption(true),

	xlsFileInfo: {
		rowGrid: {
			fileName: null,
			sheetName: null,
		},
	},
};

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