<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
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
								:label="'에너지'"
							/>
						</v-col>
						<v-col :cols="3">
							<component :is="'SelectCmCycle2'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col cols="3" 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="3">
							<v-row class="search-box" align="center" no-gutters>
								<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-col cols="7">
									<v-text-field
										id="startpicker"
										ref="startpicker"
										v-model="fromDtValue"
										:class="'v-input__custom'"
										readonly
										outlined
										:hide-details="true"
									>
										<template #append>
											<v-icon size="20">$icoCalendar</v-icon>
										</template>
										<template #append-outer>
											<div
												ref="startpicker-container"
												id="startpicker-container"
											></div>
										</template>
									</v-text-field>
								</v-col>
							</v-row>
						</v-col>
						<v-col cols="3">
							<v-row class="search-box">
								<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-col cols="7">
									<v-text-field
										id="endpicker"
										ref="endpicker"
										v-model="toDtValue"
										:class="'v-input__custom'"
										readonly
										outlined
										:hide-details="true"
									>
										<template #append>
											<v-icon size="20">$icoCalendar</v-icon>
										</template>
										<template #append-outer>
											<div
												ref="endpicker-container"
												id="endpicker-container"
											></div>
										</template>
									</v-text-field>
								</v-col>
							</v-row>
						</v-col>
						<v-col cols="6">
							<component
								:is="'SelectReadPlcPop'"
								:parentPrgmId="myPrgmId"
								:label="'비교대상'"
								:textFieldLength="6"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12" style="height: 60%;">
				<v-card class="pa-5">
					<component
						class="w100 h100"
						:is="loadChart ? 'Chart' : null"
						:parentPrgmId="myPrgmId"
						:chartName="'rowGridChart'"
						ref="rowGridChart"
					/>
				</v-card>
			</v-col>
			<v-col :cols="12" style="height: 40%;">
				<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
							: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 Grid from '~/components/common/Grid';
// import SelectBlocMstr from "@/components/common/select/SelectBlocMstr";
// import SelectEnergy from "@/components/common/select/SelectEnergy";
import SelectBlocMstr from '@/components/common/select/SelectBlocMstrForPop';
import SelectEnergy from '@/components/common/select/SelectEnergyForPop';
import SelectCmCycle from '@/components/common/select/SelectCmCycle';
import SelectCmCycle2 from '@/components/common/select/SelectCmCycle2';
import BtnSearch from '~/components/common/button/BtnSearch';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Utility from '~/plugins/utility';
import TuiDatepicker from 'tui-date-picker';
import SelectReadPlcPop from '~/components/common/modal/OutSideWeatherPlcMultiPop';
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: {
		Grid,
		SelectBlocMstr,
		SelectEnergy,
		SelectCmCycle,
		SelectCmCycle2,
		BtnSearch,
		BtnExcelDownload,
		Utility,
		TuiDatepicker,
		SelectReadPlcPop,
		Chart,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			loadChart: false,
			unit: '',
			apiKey: 'selectSameReadPlcMonth',
			startDatepickerInstance: null,
			endDatepickerInstance: null,
			startDtValue: null,
			endDtValue: null,
			timePicker: false,
			datePickerSearchFlag: 3,
		};
	},
	created() {
		const today = Utility.setFormatDate('today', 'YYYY-MM-DD');
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		// chkCmCycle(){
		myCmCycle() {
			return this.pageData.cmCycle;
		},
		chkBlocCd() {
			// 사업장 선택 감지
			return this.pageData.blocId;
		},
		chkEnergyCd() {
			// 에너지 선택 감지
			return this.pageData.energyCd;
		},
		chkFacInfo() {
			// 공정/설비 변경 감지
			return this.pageData.facInfo;
		},

		// datepicker_computed[시작]
		myOptions() {
			let returnObj = {};
			switch (this.myCmCycle) {
				case 'CYC_MONTH':
					returnObj = {
						type: 'year',
						viewFormat: 'YYYY',
						pickerFormat: 'YYYY',
						sendFormat: 'YYYY',
					};
					break;

				case 'CYC_WEEK':
					returnObj = {
						type: 'date',
						viewFormat: 'YYYY-MM-DD',
						pickerFormat: 'YYYY-MM-dd',
						sendFormat: 'YYYYMMDD',
					};
					break;

				case 'CYC_DAY':
					returnObj = {
						type: 'month',
						viewFormat: 'YYYY-MM',
						pickerFormat: 'yyyy-MM',
						sendFormat: 'YYYYMM',
					};
					break;
				case 'CYC_HOUR':
					returnObj = {
						type: 'date',
						viewFormat: 'YYYY-MM-DD' + (this.timePicker ? ' HH:mm:ss' : ''),
						pickerFormat: 'yyyy-MM-dd' + (this.timePicker ? ' HH:mm A' : ''),
						sendFormat: this.timePicker ? 'YYYY-MM-DD HH:mm:ss' : 'YYYYMMDD',
					};
					// returnObj = { type: "day", format: "YYYY-MM-DD HH:mm:ss" };
					break;

				default:
					break;
			}
			return returnObj;
		},
		fromDtValue() {
			return this.startDtValue;
		},
		toDtValue() {
			return this.endDtValue;
		},
		// datepicker_computed[끝]
		initFlag() {
			if (
				this.pageData.energyList.length > 0 &&
				this.pageData.blocMstrList.length > 0
			) {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		myCmCycle: function() {
			this.datePickerSearchFlag = 2;

			var day1 = new Date();
			var day2 = new Date();

			if (this.myCmCycle == 'CYC_MONTH') {
				day2.setFullYear(day1.getFullYear() - 1);
			} else if (this.myCmCycle == 'CYC_WEEK') {
				day2.setDate(day1.getDate() - 7);
			} else if (this.myCmCycle == 'CYC_DAY') {
				day2.setMonth(day1.getMonth() - 1);
			} else if (this.myCmCycle == 'CYC_HOUR') {
				day2.setDate(day1.getDate() - 1);
			}
			this.startDtValue = setDateWithFormat(day1, this.myOptions.type);
			this.endDtValue = setDateWithFormat(day2, this.myOptions.type);
			this.startDatepickerInstance.setDate(this.startDtValue);
			this.endDatepickerInstance.setDate(this.endDtValue);

			this.startDatepickerInstance.setDate(new Date(this.fromDtValue));
			this.endDatepickerInstance.setDate(new Date(this.toDtValue));
			this.startDatepickerInstance.setType(this.myOptions.type);
			this.endDatepickerInstance.setType(this.myOptions.type);

			// this.setPageData({ isFind: true });
		},
		chkBlocCd() {
			// this.setPageData({ isFind: true });
		},
		chkEnergyCd() {
			// this.setPageData({ isFind: true });
			this.initUnit();
		},
		chkFacInfo() {
			if (this.initFlag == true) {
				this.setPageData({ isFind: true });
			}
			// this.setPageData({ isFind: true });
		},

		// datepicker_watch[시작]
		fromDtValue(newVal, oldVal) {
			this.datePickerSearchFlag--;

			if (this.datePickerSearchFlag == 0) {
				this.datePickerSearchFlag = 1;
				this.setPageData({ isFind: true });
			}
		},
		toDtValue(newVal, oldVal) {
			this.datePickerSearchFlag--;

			if (this.datePickerSearchFlag == 0) {
				this.datePickerSearchFlag = 1;
				this.setPageData({ isFind: true });
			}
		},
		// datepicker_watch[끝]

		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() {
		this.tuiCalendarInit();
		// this.init();
	},
	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();
		},
		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);
			}
		},
		tuiCalendarInit() {
			const startContainer = document.getElementById('startpicker-container');
			const startTarget = document.getElementById('startpicker');
			const endContainer = document.getElementById('endpicker-container');
			const endTarget = document.getElementById('endpicker');

			// datepicker 초기값 생성
			var day1 = new Date();
			var day2 = new Date();
			day2.setFullYear(day1.getFullYear() - 1);
			this.startDtValue = setDateWithFormat(day1, 'year');
			this.endDtValue = setDateWithFormat(day2, 'year');
			this.pageData.cmCycle = 'CYC_MONTH';
			// datepicker 초기값 생성 끝

			// datepicker 생성
			this.startDatepickerInstance = new TuiDatepicker(startContainer, {
				date: day1,
				language: 'ko',
				type: this.myOptions.type,
				input: {
					element: startTarget,
					format: this.myOptions.pickerFormat,
				},
				timePicker: this.timePicker,
			});
			// datepicker 생성
			this.endDatepickerInstance = new TuiDatepicker(endContainer, {
				date: day2,
				language: 'ko',
				type: this.myOptions.type,
				input: {
					element: endTarget,
					format: this.myOptions.pickerFormat,
				},
				timePicker: this.timePicker,
			});
			// datepicker 생성 끝

			// datepicker 변경시 이벤트 추가
			this.startDatepickerInstance.on('change', () => this.getStartDt());
			this.endDatepickerInstance.on('change', () => this.getEndDt());
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		async search() {
			this.setLocalStorage();
			await this.getGridDatas();
		},

		async initUnit() {
			this.unit = this.pageData.energyList[this.pageData.energyCd].unit;
		},

		async gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 36;
			const myOptions = {};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			await this.getGridDatas();
			this.initUnit();
		},
		async getGridDatas() {
			this.loadChart = false;

			this.pageData.rowGrid.data = [];
			var res = [];
			var apiKeymapper = {
				CYC_MONTH: 'selectSameReadPlcMonth',
				CYC_WEEK: 'selectSameReadPlcWeek',
				CYC_DAY: 'selectSameReadPlcDay',
				CYC_HOUR: 'selectSameReadPlcTime',
			};
			this.apiKey = apiKeymapper[this.pageData.cmCycle];

			if (
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.energyList.length > 0
			) {
				const selectFacInfo = this.pageData.facInfo;
				const sendParams = {
					blocId: this.pageData.blocMstrList[this.chkBlocCd].blocId, //"BL0001",
					readPlc: selectFacInfo.readPlc,
					readPlcNm: selectFacInfo.readPlcNm,
					sh_baseDt: this.fromDtValue.replaceAll('-', ''),
					sh_compareDt: this.toDtValue.replaceAll('-', ''),
				};

				this.loadGrid = false;

				res = await this.postApiReturn({
					apiKey: this.apiKey,
					resKey: 'sameReadPlcData',
					sendParam: sendParams,
				});
			} else {
				this.setPageData({ isFind: false });
			}

			let myColumns = [{ header: '구분', name: 'readPlcNm', align: 'center' }];

			let timeList = [
				{
					header: '연도',
					name: 'date',
					align: 'center',
					formatter({ value }) {
						if (String(value).length == 4) {
							return value + '년';
						} else {
							return value;
						}
					},
				},
				{
					header: '주차',
					name: 'week',
					align: 'center',
					formatter({ value }) {
						return value;
					},
				},
				{
					header: '월',
					name: 'date',
					align: 'center',
					formatter({ value }) {
						if (String(value).length == 6) {
							return value.substr(0, 4) + '/' + value.substr(4, 2);
						} else {
							return value;
						}
					},
				},
				{
					header: '일',
					name: 'date',
					align: 'center',
					formatter({ value }) {
						if (String(value).length == 8) {
							return (
								value.substr(0, 4) +
								'/' +
								value.substr(4, 2) +
								'/' +
								value.substr(6, 2)
							);
						} else {
							return value;
						}
					},
				},
			];

			switch (this.pageData.cmCycle) {
				case 'CYC_MONTH':
					myColumns.push(timeList[0]);
					for (var i = 1; i < 13; i++) {
						var tempObject = {
							header: i + '월',
							name: 'corrVal' + String(i).padStart(2, '0'),
							// width : 150,
							align: 'right',
							formatter: numberFormatter,
						};
						myColumns.push(tempObject);
					}
					break;
				case 'CYC_WEEK':
					myColumns.push(timeList[1]);
					var headerList = [
						'일요일',
						'월요일',
						'화요일',
						'수요일',
						'목요일',
						'금요일',
						'토요일',
					];
					for (var i = 1; i < 8; i++) {
						var tempObject = {
							header: headerList[i - 1],
							name: 'corrVal' + String(i).padStart(2, '0'),
							// width : 150,
							align: 'right',
							formatter: numberFormatter,
						};
						myColumns.push(tempObject);
					}
					break;
				case 'CYC_DAY':
					myColumns.push(timeList[2]);
					for (var i = 1; i < 32; i++) {
						var tempObject = {
							header: i + '일',
							name: 'corrVal' + String(i).padStart(2, '0'),
							// width : 150,
							align: 'right',
							formatter: numberFormatter,
						};
						myColumns.push(tempObject);
					}
					break;
				case 'CYC_HOUR':
					myColumns.push(timeList[3]);
					for (var i = 0; i < 24; i++) {
						var tempObject = {
							header: i + '시',
							name: 'corrVal' + String(i).padStart(2, '0'),
							// width : 70,
							align: 'right',
							formatter: numberFormatter,
						};
						myColumns.push(tempObject);
					}
					break;
			}
			myColumns.push({
				header: '합계',
				name: 'corrVal',
				width: 50,
				align: 'right',
			});

			if (res.length >= 1) {
				// 기준일 <-> 비교일 순서 보정[시작]
				var tempRes = [...res];
				var tempIdx;
				res = [];
				for (var i = 0; i < tempRes.length ? tempRes.length : 0; i++) {
					if (tempRes[i].date == this.toDtValue.replaceAll('-', '')) {
						res.push({ ...tempRes[i] });
					} else {
						tempIdx = i;
					}
				}
				if (typeof tempIdx == 'number') {
					res.push({ ...tempRes[tempIdx] });
				}
				// 기준일 <-> 비교일 순서 보정[끝]

				var sumData = {
					readPlcNm: res[0].readPlcNm,
				};
				var columnList = Object.keys(res[0]);
				columnList = columnList.filter(item => item.startsWith('corrVal'));

				switch (this.pageData.cmCycle) {
					case 'CYC_MONTH':
						sumData[timeList[0].name] = '차이(기준-비교)';
						break;
					case 'CYC_WEEK':
						sumData[timeList[1].name] = '차이(기준-비교)';
						break;
					case 'CYC_DAY':
						sumData[timeList[2].name] = '차이(기준-비교)';
						break;
					case 'CYC_HOUR':
						sumData[timeList[3].name] = '차이(기준-비교)';
						break;
				}

				if (res.length >= 2) {
					for (var i = 0; i < columnList.length; i++) {
						sumData[columnList[i]] = res[0][columnList[i]];
					}

					for (var i = 0; i < columnList.length; i++) {
						sumData[columnList[i]] =
							Math.round(
								(sumData[columnList[i]] - res[1][columnList[i]]) * 100,
							) / 100;
					}
				} else {
					for (var i = 0; i < columnList.length; i++) {
						sumData[columnList[i]] = res[0][columnList[i]];
					}
				}

				res.push(sumData);

				Object.assign(res[0], {
					_attributes: { rowSpan: { readPlcNm: res.length } },
				});
			}

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

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

			this.setChartData(res);
		},

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

			this.$store.state.pageData[this.myPrgmId].rowGridChart.series = [];

			if (!data.length) {
				return;
			}

			let tmpLsit = [];
			let exceptionColumList = [
				'구분',
				'연도',
				'월',
				'주차',
				'월',
				'일',
				'합계',
			];
			const myKey = this.pageData[this.gridName].column.filter(v => {
				return !exceptionColumList.includes(v.header);
			});

			copiedData.pop();

			tmpLsit = copiedData.map(item => ({
				// name: item.plcNm,
				name: item.date,
				type: 'line',
				data: myKey.map(obj => item[obj.name] || 0),
			}));
			xAxisData = myKey.map(obj => obj.header);
			seriesData = tmpLsit;

			// this.setChartXAxisData({ chartKey: "rowGridChart", value: xAxisData });
			// this.setChartSeries({ chartKey: "rowGridChart", value: seriesData });

			var chartOption = {
				legend: {
					top: 'center',
					left: 'right',
					orient: 'vertical',
					textStyle: {
						color: '#95A0A9',
						fontSize: 10,
					},
				},
				grid: {
					top: '3%',
					right: '8%',
				},
				yAxis: {
					type: 'value',
					nameLocation: 'middle',
					nameGap: 40,
					name: this.unit,
				},
				xAxis: {
					data: xAxisData,
				},
				series: seriesData,
			};

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

			this.loadChart = true;
		},

		getStartDt() {
			const dt = this.startDatepickerInstance.getDate();
			this.startDtValue = setDateWithFormat(dt, this.myOptions.type);
		},
		getEndDt() {
			const dt = this.endDatepickerInstance.getDate();
			this.endDtValue = setDateWithFormat(dt, this.myOptions.type);
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	isMulti: false,
	isFind: false,
	blocId: null,
	blocMstrList: [],
	energyCd: null,
	energyList: [],
	cmCycle: 'CYC_MONTH', // 주기
	cmCycleList: [
		{ idx: 0, text: '월', value: 'CYC_MONTH' },
		{ idx: 1, text: '주', value: 'CYC_WEEK' },
		{ idx: 2, text: '일', value: 'CYC_DAY' },
		{ idx: 3, text: '시간', value: 'CYC_HOUR' },
	],
	defaultRange: {
		CYC_MONTH: 12,
		CYC_WEEK: 7,
		CYC_DAY: 31,
		CYC_HOUR: 0,
	},
	fromDt: '',
	toDt: '',
	dateFormat: {
		CYC_MONTH: 'YYYY',
		CYC_WEEK: 'YYYY-MM-DD',
		CYC_DAY: 'YYYY-MM',
		CYC_HOUR: 'YYYY-MM-DD',
	},
	tableId: null,
	gridId: null,
	facInfo: {},
	modalData: {},

	rowGrid: {
		data: [],
		option: {}, // myOptions
		column: [], // myColumns,
	},

	rowGridChart: Utility.defaultChartOption(true),

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

function setDateWithFormat(date, format) {
	var formattedDate = null;
	if (typeof date == 'string') {
		formattedDate = date;
	} else if (typeof date == 'object') {
		formattedDate = String(date.toISOString());
	}
	if (format == 'year') {
		formattedDate = formattedDate.substr(0, 4);
	} else if (format == 'month') {
		formattedDate = formattedDate.substr(0, 7);
	} else if (format == 'date') {
		formattedDate = formattedDate.substr(0, 10);
	}
	return formattedDate;
}

function numberFormatter({ value }) {
	return Utility.setFormatIntDecimal(value, 2);
}

function myLogger(msg, caller) {
	if (caller) {
	}
	if (msg.title) {
	}
	if (msg.content) {
	}
	if (typeof msg === 'string') {
	}
}
</script>
<style lang="scss" scoped>
#startpicker-container,
#endpicker-container {
	position: relative;
	z-index: 20;
}
.v-input__custom {
	flex: 0 0 auto;
	&.half {
		width: calc(50% - 20px);
	}
}
::v-deep {
	.tui-timepicker-row {
		display: flex;
		justify-content: space-around;
		background-color: #edf4fc;
		.tui-timepicker-column.tui-timepicker-colon {
			color: #000 !important;
		}
	}
}
</style>
