<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'"
								ref="SelectBlocMstr"
								:parentPrgmId="myPrgmId"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								label="에너지"
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
							/>
						</v-col>
						<v-col :cols="3">
							<!-- 구분(사용량, 비용) -->
							<component :is="'RadioUseCost'" :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="gridName"
							/>
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="3">
							<component :is="'SelectCmCycle'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col :cols="3">
							<!-- 조회기간 -->
							<DatePicker :parentPrgmId="myPrgmId" :label="'조회기간'" />
						</v-col>
						<v-col :cols="4">
							<!-- 공정/설비 -->
							<component
								label="비교대상"
								:is="'FtnPlcMultiPop'"
								:parentPrgmId="myPrgmId"
								:labelCols="3"
								:textCols="9"
							/>
						</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: 65%">
						<component
							class="w100 h100"
							ref="chart1"
							:is="loadChart1 ? 'Chart' : null"
							:chartName="chartName"
							:parentPrgmId="myPrgmId"
						/>
					</div>
					<v-card-title>
						<!-- 차트와 그리드 사이 공백을 위한 공간 -->
					</v-card-title>
					<div ref="gridParent" class="px-5" style="height: 28%">
						<component
							class="w100 h100"
							ref="grid1"
							:is="loadGrid1 ? '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 BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import SelectEnergy from '@/components/common/select/SelectEnergyForPop';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstrForPop';
import SelectCmCycle from '@/components/common/select/SelectCmCycle';
import SelectDate from '~/components/common/select/SelectDate';
import SelectDateVc from '~/components/common/select/SelectDateVc';
import DatePicker from '~/components/common/Datepicker';
import FtnPlcMultiPop from '~/components/common/modal/FtnPlcMultiPop2';
import InputText from '@/components/common/input/InputText';
import RadioUseCost from '~/components/common/RadioUseCost';
import Utility from '~/plugins/utility';
import dateUtility from '~/plugins/dateUtility';
import Grid from '~/components/common/Grid';
import Chart from '~/components/common/Chart';

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,
	},
	components: {
		BtnSearch,
		BtnExcelDownload,
		SelectBlocMstr,
		SelectEnergy,
		SelectCmCycle,
		SelectDate,
		SelectDateVc,
		RadioUseCost,
		DatePicker,
		FtnPlcMultiPop,
		InputText,
		Utility,
		dateUtility,
		Grid,
		Chart,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			myGrid: null,
			gridName: 'grid1',
			chartName: 'chart1',
			loadGrid1: false,
			loadChart1: false,
			apiKey: 'selectSameTermReadHour',
			unit: '',
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		rdbUseCost: {
			get() {
				return this.pageData[this.parentPrgmId].rdbUseCost;
			},
			set(value) {
				return this.setPageData({ rdbUseCost: value });
			},
		},
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkBlocCd() {
			// 사업장 선택 감지
			return this.pageData.blocId;
		},
		chkEnergyCd() {
			// 에너지 선택 감지
			return this.pageData.energyCd;
		},
		chkFacInfo() {
			// 공정/설비 변경 감지
			return this.pageData.facInfoList;
		},
		chkCmCycle() {
			// 주기 변경 감지
			return this.pageData.cmCycle;
		},
		chkRadio() {
			// 구분: 사용량, 비용 선택 감지
			return this.pageData.rdbUseCost;
		},
		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() {
			//지우지말자
		},
		chkEnergyCd() {
			this.initUnit();
		},
		chkFacInfo() {
			this.setPageData({ isFind: true });
		},
		chkRadio() {
			this.initUnit();
			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,
		});
	},
	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() {
			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);
			}
		},

		initUnit() {
			this.unit =
				this.pageData.energyList.length > 0 && this.pageData.rdbUseCost == 'use'
					? this.pageData.energyList[this.pageData.energyCd].unit
					: '원';
		},

		gridInit() {
			setTimeout(() => {
				const gridHeight = this.$refs.gridParent.offsetHeight - 46;

				const myOptions = {
					setScroll: true,
					columnOptions: {
						//frozenCount: 3,
						minWidth: 100,
						resizable: true,
					},
				};

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

		async getRowGridData() {
			this.loadGrid1 = false;
			this.loadChart1 = false;
			this.pageData.grid1.data = [];

			var url = {};
			if (this.pageData.cmCycle == 'CYC_YEAR') {
				url =
					this.pageData.rdbUseCost == 'use'
						? 'selectSameTermReadYear'
						: 'selectSameTermReadYearCost';
			} else if (this.pageData.cmCycle == 'CYC_MONTH') {
				url =
					this.pageData.rdbUseCost == 'use'
						? 'selectSameTermReadMonth'
						: 'selectSameTermReadMonthCost';
			} else if (this.pageData.cmCycle == 'CYC_DAY') {
				url =
					this.pageData.rdbUseCost == 'use'
						? 'selectSameTermReadDay'
						: 'selectSameTermReadDayCost';
			} else {
				url =
					this.pageData.rdbUseCost == 'use'
						? 'selectSameTermReadHour'
						: 'selectSameTermReadHourCost';
			}
			this.apiKey = url;

			var temp = [],
				temp2 = [],
				res = [];

			const facInfoList = this.pageData.facInfoList;
			if (facInfoList.length > 0) {
				for (var i = 0; i < facInfoList.length; i++) {
					temp.push(facInfoList[i].eccId);
					temp2.push(facInfoList[i].eccNm);
				}
			}

			let myColumns = [
				{ header: '번호', name: 'rowNum', align: 'center', width: 50 },
				{ header: '에너지', name: 'readObjNm', align: 'center', width: 100 },
				{ header: '구분', name: 'eccNm', align: 'left', width: 150 },
			];

			switch (this.pageData.cmCycle) {
				case 'CYC_YEAR':
					var dateDiff =
						dateUtility.diff(this.pageData.fromDt, this.pageData.toDt, 'y') + 1;
					for (var i = 0; i < 10; i++) {
						if (i < dateDiff) {
							var tempObject = {
								header: dateUtility.addYear(i, 'YYYY', this.pageData.fromDt),
								name: 'qty' + String(i).padStart(2, '0'),
								align: 'right',
								width: 100,
								excelType: 'number',
								excelFormatter: '2',
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
							};
							myColumns.push(tempObject);
						}
					}
					break;

				case 'CYC_MONTH':
					var dateDiff =
						dateUtility.diff(this.pageData.fromDt, this.pageData.toDt, 'm') + 2;
					for (var i = 1; i < 13; i++) {
						if (i < dateDiff) {
							var tempObject = {
								header: dateUtility.addMonth(
									i - 1,
									'YYYY/MM',
									this.pageData.fromDt,
								),
								name: 'qty' + String(i).padStart(2, '0'),
								align: 'right',
								width: 100,
								excelType: 'number',
								excelFormatter: '2',
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
							};
							myColumns.push(tempObject);
						}
					}
					break;

				case 'CYC_DAY':
					var dateDiff =
						dateUtility.diff(this.pageData.fromDt, this.pageData.toDt) + 2;
					for (var i = 1; i < 32; i++) {
						if (i < dateDiff) {
							var tempObject = {
								header: dateUtility.addDate(
									i - 1,
									'MM/DD',
									this.pageData.fromDt,
								),
								name: 'qty' + String(i).padStart(2, '0'),
								align: 'right',
								width: 100,
								excelType: 'number',
								excelFormatter: '2',
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
							};
							myColumns.push(tempObject);
						}
					}
					break;

				case 'CYC_HOUR':
					for (var i = 0; i < 24; i++) {
						var tempObject = {
							header: i + '시',
							name: 'qty' + String(i).padStart(2, '0'),
							align: 'right',
							width: 100,
							excelType: 'number',
							excelFormatter: '2',
							formatter({ value }) {
								return Utility.setFormatIntDecimal(value, 2);
							},
						};
						myColumns.push(tempObject);
					}
					break;
			}

			var qtyList = [];
			for (i = 0; i < myColumns.length - 3; i++) {
				if (this.pageData.cmCycle == 'CYC_YEAR') {
					var val = parseInt(this.pageData.fromDt) + i;
					var val2 = 'QTY' + String(i).padStart(2, '0');
					qtyList.push({ qty: val, as: val2 });
				} else if (this.pageData.cmCycle == 'CYC_MONTH') {
					var val =
						this.pageData.fromDt.substr(0, 4) +
						'-' +
						this.pageData.fromDt.substr(4, 2);
					var val1 = new Date(val);
					val1.setMonth(val1.getMonth() + i);
					var val2 = val1
						.toISOString()
						.replaceAll('-', '')
						.substr(0, 4);
					var val3 = val1
						.toISOString()
						.replaceAll('-', '')
						.substr(4, 2);
					var val4 = 'QTY' + String(i + 1).padStart(2, '0');
					qtyList.push({ qtyY: val2, qtyM: val3, as: val4 });
				} else if (this.pageData.cmCycle == 'CYC_DAY') {
					var val =
						this.pageData.fromDt.substr(0, 4) +
						'-' +
						this.pageData.fromDt.substr(4, 2) +
						'-' +
						this.pageData.fromDt.substr(6, 2);
					var val1 = new Date(val);
					val1.setDate(val1.getDate() + i);
					var val2 =
						val1
							.toISOString()
							.replaceAll('-', '')
							.substr(0, 4) +
						val1
							.toISOString()
							.replaceAll('-', '')
							.substr(4, 2) +
						val1
							.toISOString()
							.replaceAll('-', '')
							.substr(6, 2);
					var val3 = 'QTY' + String(i + 1).padStart(2, '0');
					qtyList.push({ qty: val2, as: val3 });
				} else {
					qtyList = [];
				}
			}

			if (
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.energyList.length > 0
			) {
				const sendParams = {
					blocId: this.pageData.blocMstrList[this.chkBlocCd].blocId,
					sh_blocCd:
						this.pageData.cmCycle == 'CYC_DAY'
							? this.pageData.blocMstrList[this.chkBlocCd].blocId
							: null,
					cbEnrgCd: this.pageData.energyList[this.chkEnergyCd].cd,
					readObjId: this.pageData.energyList[this.chkEnergyCd].cd,
					cmCycle:
						this.pageData.cmCycle == 'CYC_YEAR'
							? 'year'
							: this.pageData.cmCycle == 'CYC_MONTH'
							? 'month'
							: this.pageData.cmCycle == 'CYC_DAY'
							? 'day'
							: 'hour',
					eqpmId: temp,
					eqpmNm: temp2,
					menuList: temp.join(),
					qtyList: qtyList,
					fromObjDt:
						this.pageData.cmCycle == 'CYC_HOUR'
							? this.pageData.fromDt.substr(0, 4) +
							  '-' +
							  this.pageData.fromDt.substr(4, 2) +
							  '-' +
							  this.pageData.fromDt.substr(6, 2)
							: this.pageData.fromDt,
					sh_startDt:
						this.pageData.cmCycle == 'CYC_DAY'
							? this.pageData.fromDt.substr(0, 4) +
							  '-' +
							  this.pageData.fromDt.substr(4, 2) +
							  '-' +
							  this.pageData.fromDt.substr(6, 2)
							: null,
					toObjDt:
						this.pageData.cmCycle == 'CYC_HOUR'
							? this.pageData.fromDt
							: this.pageData.toDt,
					sh_endDt:
						this.pageData.cmCycle == 'CYC_DAY'
							? this.pageData.toDt.substr(0, 4) +
							  '-' +
							  this.pageData.toDt.substr(4, 2) +
							  '-' +
							  this.pageData.toDt.substr(6, 2)
							: null,
				};

				if (this.pageData.facInfoList.length > 0) {
					res = await this.postApiReturn({
						apiKey: this.apiKey,
						resKey: 'sameTermReadDataList',
						sendParam: sendParams,
					});
				}
			} else {
				this.setPageData({ isFind: false });
			}
			for (i = 0; i < res.length; i++) {
				Object.assign(res[i], {
					_attributes: { rowSpan: { readObjNm: res.length } },
				});
			}

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

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

			this.loadGrid1 = true;

			this.setPageData({ isFind: false });

			this.$nextTick(() => {
				if (this.loadGrid1) {
					this.setChartData(res);
				}
			});
		},

		async setChartData(data) {
			let xAxisData = [];
			let seriesData = [];

			let seriesDataList = [];
			const myKey = this.pageData[this.gridName].column.filter(v => {
				return (
					v.header !== '번호' && v.header !== '에너지' && v.header !== '구분'
				);
			});

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

			xAxisData = myKey.map(obj => obj.header);
			seriesData = seriesDataList;
			function setChartOption(chartName, unitVal) {
				var option = {
					grid: {},
					xAxis: {
						type: 'category',
						data: xAxisData,
					},
					yAxis: {
						type: 'value',
						nameLocation: 'middle',
						nameGap: 50,
						name: unitVal,
						axisLabel: {
							textStyle: {
								fontSize: 10,
							},
						},
					},
					legend: {},
					series: seriesData,
				};
				return option;
			}

			this.setChartOption({
				chartKey: 'chart1',
				value: setChartOption('chart1', this.unit),
			});

			this.loadChart1 = true;
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정

	blocId: null, // 사업장
	blocMstrList: [],

	energyCd: '',
	energyList: [],

	rdbUseCost: 'use',

	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,
	},

	// popup 설정
	isMulti: true, //checkBox

	facInfo: {},
	facInfoList: [], // 선택된 공정/설비 데이타 리스트
	modalData: {}, // 모달 관련 데이타 저장소

	fromDt: '',
	toDt: '',

	/* Grid data 세팅 */
	// 로컬 gridName 값과 동일한 이름으로 세팅
	grid1: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {},
	},

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

	// 선택된 그룹코드 상세 데이터

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