<template>
	<div class="l-layout">
		<PageTitle text="측정 위치 데이터 조회" />

		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="end" no-gutters>
						<v-col :cols="2">
							<component
								:is="'SelectBlocMstr'"
								ref="SelectBlocMstr"
								:parentPrgmId="myPrgmId"
								:textCols="12"
								customClass="select-large"
							/>
						</v-col>
						<!-- <v-col :cols="2">
							<component
								label="검침개소"
								:is="'PastRsltDataReadPop'"
								:parentPrgmId="myPrgmId"
							/>
						</v-col> -->
						<!-- <v-col :cols="2">
               <component 
              :is="'SelectTagNmList'"
              ref="SelectTagNmList"
              :parentPrgmId="myPrgmId"
              />
            </v-col> -->
						<v-col :cols="3">
							<!-- <component
								:is="'PastRsltDataReadTagPop'"
								:parentPrgmId="myPrgmId"
								:label="'TAG'"
							/> -->
							<component
								:is="'EvtObjPop'"
								:parentPrgmId="myPrgmId"
								:item="evtObjPopItem"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="4">
							<component
								:is="'Datepicker'"
								:parentPrgmId="myPrgmId"
								:label="'조회기간'"
								:textCols="12"
							/>
						</v-col>
						 <v-col :cols="3" class="d-flex align-end justify-end text-right">
							 <BtnExcelDownload
							 	class="mr-1"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
								type="primary"
								size="large"
							/>
							<BtnSearch @click="search" size="large" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12" style="height: 100%" class="h100">
				<v-card class="px-5 py-5 h100">
					<div ref="gridParent" class="h100 px-5" style="height: 100%">
						<component
							ref="myGrid"
							:is="loadGrid ? 'Grid' : null"
							:gridName="gridName"
							:parentPrgmId="myPrgmId"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import BtnSearch from '~/components/common/button/BtnSearch';
import Grid from '~/components/common/Grid';
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
import Utility from '~/plugins/utility';
import Datepicker from '~/components/common/PastRsltDatePicker';
import PastRsltDataReadPop from '~/components/common/modal/PastRsltDataReadPop';
import PastRsltDataReadTagPop from '~/components/common/modal/PastRsltDataReadTagPop';
import SelectTagNmList from '~/components/common/select/SelectTagNmList';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
// import TotUseQtyCmprPageVue from './TotUseQtyCmprPage.vue';
import DateUtility from '~/plugins/dateUtility';
// import Search from "~/components/common/search";
import EvtObjPop from '~/components/common/modal/EvtObjPop';
import PageTitle from "~/components/common/PageTitle";

let myTitle;
// const myPrgmId = "PRG0052";
let myPrgmId;
export default {
	mixins: [mixinGlobal, resize],

	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: {
		BtnSearch,
		Datepicker,
		SelectBlocMstr,
		SelectTagNmList,
		BtnExcelDownload,
		Grid,
		PastRsltDataReadPop,
		PastRsltDataReadTagPop,
		EvtObjPop,
		PageTitle,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadGrid: false,
			gridName: 'rowGrid',
			myRowKey: 0,
			initFlag: false,
			evtObjPopItem: {
				labelContent: 'TAG',
				modalTitle: 'TAG 리스트',
				valueNm: 'tagId',
				valueNm2: 'tagNm',
				iconShow: true,
				disabled: false,
				labelCols: 12,
				textCols: 12,
				class: 'py-2',
				required: false,
				formFg: false,
			},
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			return this.pageData.isFind;
		},
		chkTagId() {
			return this.pageData.tagList === undefined ? null : this.pageData.tagId;
		},
		// chkTagList() {
		// 	return this.pageData.tagList;
		// },
		chkTagNm() {
			return this.pageData.tagData.tagNm;
		},
		chkReadPlcId() {
			return this.pageData.readPlcId;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkTagId(val) {
			if (this.initFlag && val != null) {
				this.search();
			}
		},
		// chkTagList() {
		// 	if(this.initFlag){
		// 		this.search();
		// 	}
		// },
		chkTagNm() {
			if (this.initFlag) {
				this.search();
			}
		},
		chkReadPlcId() {
			this.setPageData({
				sendTagParam: { readPlc: this.pageData.readPlcId.readPlcId },
			});
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {},
	async mounted() {
		await this.setFromDt();
		await this.init();
		this.initFlag = true;
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			chkOpenTabList: 'chkOpenTabList',
		}),
		async search() {
			// this.gridInit();
			if (this.initFlag) {
				if (this.pageData.tagId == '' || this.pageData.tagId == null) {
					alert('TAG를 선택해 주세요');
				} else {
					this.getRowGridData();
				}
			}
			this.setPageData({
				isFind: false,
			});
		},
		async init() {
			//this.layoutInit();
			this.gridInit();
			this.pageData.blocId = this.userInfo.blocId;
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		async setFromDt() {
			this.pageData.fromDt = Utility.setBeforetDate(
				this.pageData,
				this.pageData.toDt,
				'YYYYMMDD',
			);
			// this.pageData.toDt = Utility.setAftertDate(this.pageData, this.pageData.fromDt, "YYYYMMDD");
		},
		gridInit() {
			this.loadGrid = false;
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				header: {
					height: 38,
				},
			};

			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			let myColumns = [
				{
					header: 'TAG ID',
					name: 'tagId',
					align: 'left',
					minWidth: 500,
				},
				{
					header: 'TAG명',
					name: 'tagNm',
					align: 'left',
				},
				{
					header: '대상일시',
					name: 'readDttm',
					align: 'center',
					width: 200,
				},
				{
					header: '값',
					name: 'readVal',
					align: 'right',
					width: 100,
					excelType: 'number',
					excelFormatter: '2',
					formatter({ value }) {
						return Utility.setFormatIntDecimal(value, 2);
					},
				},
				{
					header: '취득일시',
					name: 'regDttm',
					align: 'center',
					width: 200,
				},
				{
					header: '적재일시',
					name: 'procDttm',
					align: 'center',
					width: 200,
				},
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			this.loadGrid = true;
		},
		async getRowGridData() {
			this.loadGrid = false;

			let res = [];
			let yearQuarterData = [];
			yearQuarterData = this.yearQuarterMaker([
				this.pageData.fromDt,
				this.pageData.toDt,
			]);

			// if(this.pageData.tagList.length > 0){
			//   const sendParams= {
			//     fromDt: this.pageData.fromDt,
			//     toDt: this.pageData.toDt,
			//     yearQuarterList: yearQuarter,
			//   }
			//   if(this.pageData.tagList[this.pageData.tagId].tagId == '' || this.pageData.tagList[this.pageData.tagId].tagId == null){
			//     sendParams['readPlcId']= this.pageData.readPlcId.readPlcId
			//   }else{
			//     sendParams['tagId']= this.pageData.tagList[this.pageData.tagId].tagId
			//   }

			//   res = await this.postApiReturn({
			//     apiKey: "selectTagRawDataByQuarter",
			//     resKey: "pastRsltReadData",
			//     sendParam: sendParams
			//   });

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

			// 기존 소스
			if (this.pageData.tagData.tagNm != '') {
				const sendParams = {
					fromDt: this.pageData.fromDt,
					toDt: this.pageData.toDt,
					yearQuarterList: yearQuarterData['yearQuarterList'],
				};
				sendParams['tagId'] = this.pageData.tagData.tagId;
				//
				if (yearQuarterData['newToDt'] != undefined) {
					sendParams['toDt'] = yearQuarterData['newToDt'];
					sendParams['newFromDt'] = yearQuarterData['newFromDt'];
					sendParams['rawTableToDt'] = yearQuarterData['rawTableToDt'];
				} else if (yearQuarterData['rawTableToDt'] != undefined) {
					sendParams['newFromDt'] = yearQuarterData['newFromDt'];
					sendParams['rawTableToDt'] = yearQuarterData['rawTableToDt'];
				}
				res = await this.postApiReturn({
					apiKey: 'selectTagRawDataByQuarter',
					resKey: 'pastRsltReadData',
					sendParam: sendParams,
				});

				this.setGridData({
					gridKey: this.gridName,
					value: res,
				});
			} else {
				// 바뀐 popup에 맞춘 소스
				const sendParams = {
					fromDt: this.pageData.fromDt,
					toDt: this.pageData.toDt,
					yearQuarterList: yearQuarterData['yearQuarterList'],
				};
				sendParams['tagId'] = this.pageData.tagId;
				//
				if (yearQuarterData['newToDt'] != undefined) {
					sendParams['toDt'] = yearQuarterData['newToDt'];
					sendParams['newFromDt'] = yearQuarterData['newFromDt'];
					sendParams['rawTableToDt'] = yearQuarterData['rawTableToDt'];
				} else if (yearQuarterData['rawTableToDt'] != undefined) {
					sendParams['newFromDt'] = yearQuarterData['newFromDt'];
					sendParams['rawTableToDt'] = yearQuarterData['rawTableToDt'];
				}
				res = await this.postApiReturn({
					apiKey: 'selectTagRawDataByQuarter',
					resKey: 'pastRsltReadData',
					sendParam: sendParams,
				});

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

			this.loadGrid = true;
		},
		yearQuarterMaker(dateList) {
			//1번 조건: 오늘 날짜 기준 최근 4개월까지는 raw_data 테이블 조회
			//2번 조건: 그 이후의 경우는 raw_data2022Y2Q 같은 backup 테이블 조회
			//3번 조건: 1+2번 조건
			let finalResult = {};
			let newFromDt = '';
			let newToDt = '';
			let today = Utility.setFormatDate(new Date(), 'YYYYMMDDHHmmss');
			let checkPoint = 0;
			let diffTime = DateUtility.diff(dateList[0], today, 'd');

			if (diffTime >= 120) {
				newFromDt = DateUtility.addDate(-119, 'YYYYMMDD', dateList[1]);
				newToDt = DateUtility.addDate(-120, 'YYYYMMDD', today);
				checkPoint = DateUtility.diff(newToDt, dateList[1], 'd');

				// 오늘날짜로부터 4개월 보다 많은 경우(raw_data + raw_data_backup 테이블)
				if (checkPoint > 0) {
					finalResult['newToDt'] = newToDt;
					finalResult['newFromDt'] = newFromDt;
					finalResult['rawTableToDt'] = dateList[1];
				}
				// console.log('newFromDt', dateList[0], newToDt, newFromDt, dateList[1]);

				//1번 조건: 최근 4개월이내의 경우(raw_data만 조회)
			} else {
				finalResult['newFromDt'] = dateList[0];
				finalResult['rawTableToDt'] = dateList[1];
				finalResult['yearQuarterList'] = [];
				return finalResult;
			}
			//2번 조건: 최근 4개월을 벗어나는 경우(raw_data_backup 테이블 조회)
			let result = [];
			let quarterNum;

			//2022Y3Q 같은 형태로 만들기
			for (let date of [dateList[0], newToDt]) {
				quarterNum = 'Y1Q';
				let year = date.substring(0, 4);
				let qNum = parseInt(date.substring(4, 6).replace(/(^0+)/, ''));
				if (qNum > 3) quarterNum = 'Y2Q';
				if (qNum > 6) quarterNum = 'Y3Q';
				if (qNum > 9) quarterNum = 'Y4Q';
				result.push(year + quarterNum);
			}
			if (result.length > 1) {
				let fromYear = parseInt(result[0].substring(0, 4));
				let fromQuarter = parseInt(result[0].substring(5, 6));
				let toYear = parseInt(result[1].substring(0, 4));
				let toQuarter = parseInt(result[1].substring(5, 6));
				let endPoint = toYear + 'Y' + toQuarter + 'Q';
				let diffYear = toYear - fromYear;

				for (var i = 0; i <= diffYear; i++) {
					if (fromQuarter + 1 >= 4) {
						fromYear = fromYear + 1;
						fromQuarter = 0;
					}
					let newYearQuarter = fromYear + 'Y' + (fromQuarter + i + 1) + 'Q';
					if (endPoint == newYearQuarter) {
						break;
					} else {
						result.splice(i + 1, 0, newYearQuarter);
					}
				}
			}
			finalResult['yearQuarterList'] = result;
			return finalResult;
		},
	},
};

const defaultData = {
	sendTagParam: { readPlc: '' },
	tagData: { tagNm: '' },
	/* 검색옵션 */
	blocId: '',
	blocMstrList: [],
	tagId: '',
	tagNm: '',
	tagList: [],
	isFind: false,
	modalData: {},
	cmCycle: 'CYC_DAY', // 주기
	readPlcId: '',
	defaultRange: {
		CYC_DAY: 30,
	},
	fromDt: '', // 조회 시작일
	toDt: Utility.setFormatDate(new Date(), 'YYYYMMDD'), // 조회 종료일,
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {},
	},
	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};
</script>
