<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="3">
							<!-- 사업장 -->
							<component
								:is="'SelectBlocMstr'"
								:parentPrgmId="myPrgmId"
								valueNm="blocNm"
							/>
						</v-col>
						<v-col :cols="3">
							<!-- 에너지 -->
							<component
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
								:label="'에너지'"
							/>
						</v-col>
						<v-col :cols="3">
							<!-- 주기 -->
							<component :is="'SelectCmCycle'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col :cols="3" class="text-right">
							<!-- 조회버튼 -->
							<BtnSearch @click="search" />
							<BtnExcelDownload
								style="vertical-align: middle;"
								class="d-inline-flex"
								:parentPrgmId="myPrgmId"
								:gridName="grid_01"
							/>
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="3">
							<!-- 조회기간 -->
							<!-- <component :is="swichDatePicker" :parentPrgmId="myPrgmId" /> -->
							<component
								:is="'Datepicker'"
								:parentPrgmId="myPrgmId"
								:label="'조회기간'"
							/>
						</v-col>
						<v-col :cols="7">
							<!-- 공정/설비 -->
							<component
								:is="'OutSideWeatherPlcPop'"
								:parentPrgmId="myPrgmId"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12" style="height: 65%">
				<v-card class="pa-5">
					<component
						class="w100 h100"
						:is="loadChart_01 ? 'Chart' : null"
						:parentPrgmId="myPrgmId"
						:chartName="chart_01"
						ref="chart_01"
					/>
				</v-card>
			</v-col>

			<v-col :cols="12" style="height: 35%">
				<v-card class="pb-5">
					<v-card-title class="justify-end caption text-color--non-activate"
						>단위 : {{ unit }}
					</v-card-title>
					<div ref="gridParent" class="px-5" style="height: calc(100% - 70px)">
						<component
							ref="grid_01"
							:is="loadGrid_01 ? 'Grid' : null"
							:gridName="grid_01"
							:parentPrgmId="myPrgmId"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global';
import SelectCmCycle from '@/components/common/select/SelectCmCycle';
import SelectEnergy from '@/components/common/select/SelectEnergyForPop';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstrForPop';
import OutSideWeatherPlcPop from '~/components/common/modal/OutSideWeatherPlcMultiPop';
import BtnSearch from '~/components/common/button/BtnSearch';
import Grid from '~/components/common/Grid';
import Datepicker from '~/components/common/Datepicker';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Chart from '~/components/common/Chart';

import SelectMttGrp from '@/components/common/select/SelectMttGrp';
import SelectUseFg from '@/components/common/select/SelectUseFg';
import SelectUnit from '@/components/common/select/SelectUnit';
import SelectEqpmGrpKind from '@/components/common/select/SelectEqpmGrpKind';
import InputText from '@/components/common/input/InputText';
import InputTextPassword from '@/components/common/input/InputTextPassword';
import InputRmrk from '@/components/common/input/InputRmrk';
import Utility from '~/plugins/utility';
import DateUtility from '~/plugins/dateUtility';
// import ChangePassword from "~/components/common/modal/ChangePassword";

let myTitle;
let myPrgmId;

export default {
	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,
	},
	mixins: [mixinGlobal],
	components: {
		Grid,
		SelectEnergy,
		SelectCmCycle,
		SelectBlocMstr,
		BtnSearch,
		OutSideWeatherPlcPop,
		BtnExcelDownload,
		Chart,
		Datepicker,

		SelectMttGrp,
		SelectUseFg,
		SelectUnit,
		SelectEqpmGrpKind,
		InputText,
		InputTextPassword,
		InputRmrk,
		// ChangePassword
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			grid_01: 'readPlcGrid', // defaultData랑 맞춰야 됨
			chart_01: 'readPlcChart',
			loadGrid_01: false,
			loadChart_01: false,
			apiKey: 'selectSameTermReadPlcHour',
			unit: '',
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		swichDatePicker() {
			let picker = 'SelectDateVc';
			if (
				this.pageData.cmCycle == 'CYC_MONTH' ||
				this.pageData.cmCycle == 'CYC_YEAR'
			) {
				picker = 'SelectDate';
			}
			return picker;
		},
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},

		chkBlocCd: function() {
			// 사업장 선택 감지
			//this.selectBoxEvt();
			return this.pageData.blocId;
		},

		chkEnergyCd() {
			// 에너지 선택 감지
			//this.selectBoxEvt();
			return this.pageData.energyCd;
		},

		chkFacInfo() {
			// 공정/설비 변경 감지
			return this.pageData.facInfoList;
		},
		initFlag() {
			if (
				this.pageData.energyList.length > 0 &&
				this.pageData.blocMstrList.length > 0
			) {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},

		chkBlocCd() {
			//this.setPageData({ isFind: true });
		},

		chkEnergyCd() {
			this.initUnit();
			//this.setPageData({ isFind: true });
		},

		chkFacInfo() {
			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,
		});
		// this.pageData.facInfoList = localStorage.getItem(myPrgmId + "CheckedRow") !=null ? JSON.parse(localStorage.getItem(myPrgmId + "CheckedRow")) : [] // 선택된 공정/설비 데이타 리스트
	},
	mounted() {
		//this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartOption: 'setChartOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		async init() {
			// await this.layoutInit();
			await this.gridInit();
		},
		async initUnit() {
			this.unit = this.pageData.energyList[this.pageData.energyCd].unit;
		},
		async gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 36;
			const isRange =
				this.pageData.defaultRange[this.pageData.cmCycle] === 0 ? false : true;
			// const gridHeight = this.$refs.contents.offsetHeight - 30;

			const myOptions = {
				scrollX: false,
			};
			this.setGridOption({
				gridKey: this.grid_01,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			await this.getRowGridData();
		},

		async search() {
			await this.setPageData({
				isFind: false,
			});
			await this.getRowGridData();
			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);
			}
			// await this.getRowGridData2(); // tab2
		},
		async getRowGridData() {
			this.loadGrid_01 = false;
			this.loadChart_01 = false;

			let diffTime;
			var apiKeymapper = {
				CYC_YEAR: 'selectSameTermReadPlcYear',
				CYC_MONTH: 'selectSameTermReadPlcMonth',
				CYC_DAY: 'selectSameTermReadPlcDay',
				CYC_HOUR: 'selectSameTermReadPlcHour',
			};
			this.apiKey = apiKeymapper[this.pageData.cmCycle];

			// readPlcList setting
			const readPlcCdList = [];
			const facInfoList = this.pageData.facInfoList;
			if (facInfoList.length > 0) {
				for (const item of facInfoList) {
					readPlcCdList.push(item.readPlc);
				}
			}
			var sendParams = {};
			if (
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.energyList.length > 0
			) {
				sendParams = {
					blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId,
					endDt: this.pageData.toDt,
					frDt: this.pageData.fromDt,
					readPlcList: readPlcCdList,
				};
			}

			let myColumns = [
				{ header: '번호', name: 'rowNum', align: 'center' },
				{ header: '구분', name: 'readPlcNm', align: 'left' },
				{ header: '검침개소', name: 'readPlc', align: 'left', hidden: true },
				{ header: '에너지', name: 'mttCd', align: 'left', hidden: true },
				{ header: '공통코드', name: 'comId', align: 'left', hidden: true },
			];

			// 주기별 qty 파라미터 및 gridHeader 세팅
			switch (this.pageData.cmCycle) {
				case 'CYC_YEAR':
					// diffTime = this.calDiffTime();
					diffTime =
						DateUtility.diff(this.pageData.fromDt, this.pageData.toDt, 'y') + 1;

					for (var i = 0; i < 10; i++) {
						let qtyKey;
						qtyKey = 'qty' + String(i + 1).padStart(2, '0');

						sendParams[qtyKey] = parseInt(parseInt(this.pageData.fromDt) + i);

						if (i < diffTime) {
							myColumns.push({
								header: parseInt(parseInt(this.pageData.fromDt) + i),
								name: qtyKey,
								align: 'center',
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
							});
						}
					}
					break;

				case 'CYC_MONTH':
					diffTime =
						DateUtility.diff(this.pageData.fromDt, this.pageData.toDt, 'm') + 1;

					for (var i = 0; i < 12; i++) {
						let qtyKey;
						let tDate;
						let tDateVal;
						qtyKey = 'qty' + String(i + 1).padStart(2, '0');
						tDate = DateUtility.addMonth(i, 'YYYYMM', this.pageData.fromDt);
						tDateVal = DateUtility.getDate(tDate);

						sendParams[qtyKey] = parseInt(tDate);

						if (i < diffTime) {
							myColumns.push({
								header:
									String(tDateVal['$y']) +
									'/' +
									String(tDateVal['$M'] + 1).padStart(2, '0'),
								name: qtyKey,
								align: 'center',
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
							});
						}
					}
					break;

				case 'CYC_DAY':
					diffTime =
						DateUtility.diff(this.pageData.fromDt, this.pageData.toDt, 'd') + 1;

					for (var i = 0; i < 31; i++) {
						let qtyKey;
						let tDate;
						let tDateVal;
						qtyKey = 'qty' + String(i + 1).padStart(2, '0');
						tDate = DateUtility.addDate(i, 'YYYYMMDD', this.pageData.fromDt);
						tDateVal = DateUtility.getDate(tDate);

						sendParams[qtyKey] = parseInt(tDate);

						if (i < diffTime) {
							myColumns.push({
								header:
									String(tDateVal['$M'] + 1).padStart(2, '0') +
									'/' +
									String(tDateVal['$D']).padStart(2, '0'),
								name: qtyKey,
								align: 'center',
								width: 100,
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
							});
						}
					}
					break;

				case 'CYC_HOUR':
					for (var i = 0; i < 24; i++) {
						let qtyKey;
						qtyKey = 'qty' + String(i + 1).padStart(2, '0');
						sendParams['endDt'] = sendParams['frDt'];

						myColumns.push({
							header: i + '시',
							name: qtyKey,
							align: 'center',
							formatter({ value }) {
								return Utility.setFormatIntDecimal(value, 2);
							},
						});
					}
					break;
			}
			let res = [];
			if (sendParams.endDt != undefined && sendParams.readPlcList.length > 0) {
				res = await this.postApiReturn({
					apiKey: this.apiKey,
					resKey: 'ddlyReadRsltData',
					sendParam: sendParams,
				});
			} else {
				this.setPageData({ isFind: false });
				//alert("검침개소 정보가 없습니다.");
			}

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

			this.setGridColumn({
				gridKey: this.grid_01,
				value: myColumns,
			});
			this.setGridData({
				gridKey: this.grid_01,
				value: res,
			});

			this.loadGrid_01 = true;

			this.setPageData({ isFind: false });

			this.$nextTick(() => {
				if (this.loadGrid_01) {
					this.setChartData(res);
				}
			});
		},
		async setChartData(data) {
			let xAxisData = [];
			let seriesData = [];

			let seriesDataList = [];
			const myKey = this.pageData[this.grid_01].column.filter(v => {
				return (
					v.header !== '구분' &&
					v.header !== '번호' &&
					v.header !== '에너지' &&
					v.header !== '공통코드' &&
					v.header !== '검침개소'
				);
			});

			seriesDataList = data.map(item => ({
				name: item.readPlcNm,
				type: 'line',
				data: myKey.map(obj => item[obj.name] || 0),
			}));

			xAxisData = myKey.map(obj => obj.header);
			seriesData = seriesDataList;

			let option = {
				grid: {
					right: '10%',
				},
				xAxis: {
					type: 'category',
					data: xAxisData,
				},
				legend: {
					top: 'center',
					left: 'right',
					orient: 'vertical',
				},
				series: seriesData,
			};
			this.setChartOption({ chartKey: 'readPlcChart', value: option });

			this.loadChart_01 = true;
		},
		// compareData(type, newData) {
		//   if (this.selectedUserData[type] == newData) {
		//     return true;
		//   } else {
		//     return false;
		//   }
		// },
		calDiffTime() {
			var toDate;
			var fromDate;

			if (this.pageData.cmCycle == 'CYC_YEAR') {
				return (
					parseInt(this.pageData.toDt) - parseInt(this.pageData.fromDt) + 1
				);
			} else if (this.pageData.cmCycle == 'CYC_MONTH') {
				var toDate = new Date(
					this.pageData.toDt.substr(0, 4),
					this.pageData.toDt.substr(4, 2),
				);
				var fromDate = new Date(
					this.pageData.fromDt.substr(0, 4),
					this.pageData.fromDt.substr(4, 2),
				);
			} else if (this.pageData.cmCycle == 'CYC_DAY') {
				var toDate = new Date(
					this.pageData.toDt.substr(0, 4),
					this.pageData.toDt.substr(4, 2),
					this.pageData.toDt.substr(6, 2),
				);
				var fromDate = new Date(
					this.pageData.fromDt.substr(0, 4),
					this.pageData.fromDt.substr(4, 2),
					this.pageData.fromDt.substr(6, 2),
				);
			}
			toDate.setMonth(toDate.getMonth() - 1);
			fromDate.setMonth(fromDate.getMonth() - 1);

			var diff = toDate - fromDate;
			var cDay = 24 * 60 * 60 * 1000;
			var cMonth = cDay * 30;
			//var cYear = cMonth * 12;
			var typeMapper = {
				CYC_MONTH: cMonth,
				CYC_DAY: cDay,
			};
			return parseInt(diff / typeMapper[this.pageData.cmCycle]) + 1;
		},
		// // 확인하기1
		// selectBoxEvt() {
		//   localStorage.removeItem("SameTermReadPlcCheckedRow");
		//   this.pageData.facInfoList = [];
		// }
	},
};

const defaultData = {
	/* 검색옵션 */
	isFind: false,

	blocId: '', // 사업장
	//blocId: "BL0001", // 사업장
	blocMstrList: [],
	energyCd: null, // 에너지
	//energyCd: "MTT00001", // 에너지
	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' },
	],
	// 각 주기에 따른 기간 max
	defaultRange: {
		CYC_YEAR: 10,
		CYC_MONTH: 12,
		CYC_DAY: 30,
		CYC_HOUR: 0,
	},
	// fromDt: "", // 조회 시작일
	fromDt: Utility.setFormatDate(new Date(), 'YYYYMMDD'), // 조회 시작일
	toDt: '', // 조회 종료일,
	// popup 설정
	isMulti: true, //checkBox
	facInfo: {}, // 선택된 공정/설비 데이타
	facInfoList: [], // 선택된 공정/설비 데이타 리스트
	modalData: {}, // 모달 관련 데이타 저장소
	//
	//localStorageKey: "SameTermReadPlcCheckedRow",

	/* data 세팅 */
	readPlcGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {},
	},

	// chart 설정
	readPlcChart: Utility.defaultChartOption(true),

	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		readPlcGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
	// selectedRowKey:null,
	// selectedUserData: null,
};

function numberFormatter({ value }) {
	if (value == null) {
		return 0;
	} else {
		return value;
	}
}

function makeDateVal(date, cmCycle) {
	let result = '';
	var newDate = DateUtility.getDate(date);

	result = newDate['$y'];
	if (cmCycle == 'CYC_YEAR') return result;
	result = result + '-' + String(newDate['$M'] + 1).padStart(2, '0');
	if (cmCycle == 'CYC_MONTH') return result;
	result = result + '-' + String(newDate['$D']).padStart(2, '0');
	return result;
}
</script>
