<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" />
						</v-col>
						<v-col :cols="3">
							<component
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
								:label="'검침대상'"
							/>
						</v-col>
						<v-col :cols="3"> </v-col>
						<v-col :cols="3" class="text-right">
							<v-btn :ripple="false" @click="searchInit">처음으로</v-btn>
							<v-btn :ripple="false" @click="search">조회</v-btn>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" :eager="true">
			<v-col style="height:100%;">
				<v-card class="px-5 py-5">
					<div ref="chartParent" id="test2" style="height: 100%;">
						<component
							class="w100 h100"
							:is="loadChart ? 'Chart' : null"
							:parentPrgmId="myPrgmId"
							:chartName="chartName"
							ref="treeGridChart"
							@dblclick="chartDblClick"
							@click="chartClick"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
import { mapState, mapMutations, mapActions } from 'vuex';
import Search from '~/components/common/search';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
import SelectEnergy from '@/components/common/select/SelectEnergy';
import Chart from '~/components/common/Chart';
import Utility from '~/plugins/utility';

let myTitle;
let myPrgmId;

export default {
	mixins: [mixinGlobal],
	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: {
		SelectBlocMstr,
		SelectEnergy,
		Chart,
		Search,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadChart: false,
			chartName: 'sankyChart',
		};
	},
	computed: {
		...mapState({
			isDarkMode: state => state.isDarkMode,
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkBlocCd() {
			// 사업장 코드
			return this.pageData.blocId;
		},
		chkEnergyCd() {
			// 에너지 선택 여부 감지
			return this.pageData.energyCd;
		},
		chkUpReadPlcId() {
			return this.pageData.upReadPlcId;
		},
		chkDarkMode() {
			return this.isDarkMode;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkBlocCd() {
			this.setPageData({ isFind: true });
		},
		chkEnergyCd() {
			this.setPageData({ isFind: true });
		},
		chkUpReadPlcId() {
			this.setPageData({ isFind: true });
		},
		chkDarkMode() {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {
		this.timer = setInterval(this.searchTimer, 10000); // 10초 주기마다 갱신
	},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.cancelAutoUpdate();
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setChartOption: 'setChartOption',
			setChartTitle: 'setChartTitle',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			chkOpenTabList: 'chkOpenTabList',
		}),
		cancelAutoUpdate() {
			clearInterval(this.timer);
		},
		init() {
			this.layoutInit();
			this.getChartData();
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		// 에너지 계통 실시간 조회
		async getChartData() {
			this.loadChart = false;

			let res = [];
			if (
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.energyList.length > 0
			) {
				res = await this.postApiReturn({
					apiKey: 'selectEnrgSystemMonitoringInfo',
					//resKey:"enrgSystemMonitoringInfoData",
					resKey: 'enrgSystemMonitoringInfoTreeData',
					// sendParm : sendParams
					sendParam: {
						upReadPlcId: this.pageData.upReadPlcId,
						energyCd: this.pageData.energyList[this.pageData.energyCd].cd,
						// sh_blocCd:"BL0001"
						blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId,
					},
				});
			}
			this.setPageData({ isFind: false });
			this.setChartData(res);
			this.loadChart = true;
			this.loadGrid = true;
		},
		async setChartData(data) {
			let makeData = [];
			let makeLinks = [];
			this.pageData.colorInx1st = 0;
			this.pageData.colorInx2st = 0;

			let datetime = '';
			for (var idx in data) {
				datetime = '검침 시간 : ' + data[0].datetime;
				if (data[idx].mapUpReadPlcId == 'ROOT') {
					for (var idxSub in data[idx]['childeVo']) {
						this.makeDataAndLinks(
							null,
							data[idx]['childeVo'][idxSub],
							makeData,
							makeLinks,
						);
					}
				} else {
					this.makeDataAndLinks(null, data[idx], makeData, makeLinks);
				}
			}

			const title = [
				{
					text: datetime,
					left: '3%',
					bottom: '10',
					textStyle: {
						color: this.isDarkMode
							? 'rgba(250,250,250,0.7)'
							: 'rgba(0,0,0,0.7)',
					},
				},
				{
					text: ' < ',
					left: '10',
					top: 'center',
					textStyle: {
						color: this.isDarkMode
							? 'rgba(250,250,250,0.7)'
							: 'rgba(0,0,0,0.7)',
					},
					triggerEvent: true,
				},
			];

			const option = {
				title: title,
				backgroundColor: '#FFFFFF',
				series: [
					{
						type: 'sankey',
						left: 50.0,
						top: 20.0,
						right: 50.0,
						bottom: 25.0,
						nodeGap: 10,
						nodeAlign: 'left',
						data: makeData,
						links: makeLinks,
						lineStyle: {
							color: 'source',
							curveness: 0.5,
						},
						triggerEvent: true,
						itemStyle: {
							//color: '#1f77b4',
							//borderColor: '#1f77b4'
						},
						label: {
							color: this.isDarkMode
								? 'rgba(250,250,250,0.7)'
								: 'rgba(0,0,0,0.7)',
							fontFamily: 'Arial',
							fontSize: 12,
						},
					},
				],
				tooltip: {
					trigger: 'item',
				},
			};
			this.setChartOption({ chartKey: this.chartName, value: option });
			this.loadChart = true;
		},
		async setChartSeriesData(data) {
			let makeData = [];
			let makeLinks = [];

			this.pageData.colorInx1st = 0;
			this.pageData.colorInx2st = 0;

			let datetime = '';
			for (var idx in data) {
				datetime = '검침 시간 : ' + data[0].datetime;
				if (data[idx].upReadPlcId == 'ROOT') {
					for (var idxSub in data[idx]['childeVo']) {
						this.makeDataAndLinks(
							null,
							data[idx]['childeVo'][idxSub],
							makeData,
							makeLinks,
						);
					}
				} else {
					this.makeDataAndLinks(null, data[idx], makeData, makeLinks);
				}
			}
			const title = [
				{
					text: datetime,
					left: '3%',
					bottom: '10',
					textStyle: {
						color: this.isDarkMode
							? 'rgba(250,250,250,0.7)'
							: 'rgba(0,0,0,0.7)',
					},
				},
				{
					text: ' < ',
					left: '10',
					top: 'center',
					textStyle: {
						color: this.isDarkMode
							? 'rgba(250,250,250,0.7)'
							: 'rgba(0,0,0,0.7)',
					},
					triggerEvent: true,
				},
			];
			const seriesData = [
				{
					type: 'sankey',
					left: 50.0,
					top: 20.0,
					right: 50.0,
					bottom: 25.0,
					nodeGap: 10,
					nodeAlign: 'left',
					data: makeData,
					links: makeLinks,
					lineStyle: {
						color: 'source',
						curveness: 0.5,
					},
					triggerEvent: true,
					itemStyle: {
						//color: '#1f77b4',
						//borderColor: '#1f77b4'
					},
					label: {
						color: this.isDarkMode
							? 'rgba(250,250,250,0.7)'
							: 'rgba(0,0,0,0.7)',
						fontFamily: 'Arial',
						fontSize: 12,
					},
				},
			];

			this.setChartSeries({ chartKey: this.chartName, value: seriesData });
			this.setChartTitle({ chartKey: this.chartName, value: title });
		},
		search() {
			let urlPath = this.$router.currentRoute.fullPath;
			let index = urlPath.indexOf('/ems/base/EnrgSystemMonitoringMngPage');
			if (index >= 0) {
				this.getChartData();
			}
		},
		searchInit() {
			this.pageData.upReadPlcId = 'ROOT';
		},
		async searchTimer() {
			let urlPath = this.$router.currentRoute.fullPath;
			let index = urlPath.indexOf('/ems/base/EnrgSystemMonitoringMngPage');
			if (index >= 0) {
				let res = [];
				if (
					this.pageData.blocMstrList.length > 0 &&
					this.pageData.energyList.length > 0
				) {
					res = await this.postApiReturn({
						apiKey: 'selectEnrgSystemMonitoringInfo',
						//resKey:"enrgSystemMonitoringInfoData",
						resKey: 'enrgSystemMonitoringInfoTreeData',
						// sendParm : sendParams
						sendParam: {
							upReadPlcId: this.pageData.upReadPlcId,
							energyCd: this.pageData.energyList[this.pageData.energyCd].cd,
							// sh_blocCd:"BL0001"
							blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId,
						},
					});
				}
				this.setPageData({ isFind: false });
				this.setChartSeriesData(res);
				this.loadChart = true;
				this.loadGrid = true;
			}
		},
		setView(value) {
			this.isFind = true;
		},
		makeDataAndLinks(parentsVo, chlVo, data, link) {
			let retVal = 0;
			//console.log("chlVo.has('childeVo') : ", chlVo["childeVo"]);
			if (chlVo['childeVo'] != null || chlVo['childeVo'] != undefined) {
				// 하위 자료가 있으면
				let subSum = 0;
				for (var idx in chlVo['childeVo']) {
					let subRet = this.makeDataAndLinks(
						chlVo,
						chlVo['childeVo'][idx],
						data,
						link,
					);
					subSum += subRet;
				}

				if (chlVo.instantVal > subSum) {
					//this.makeDataAndLinksOverVal(parentsVo, chlVo, data, link, chlVo.instantVal - subSum);
				}

				if (chlVo.instantVal != null && chlVo.instantVal > 0) {
					retVal = chlVo.instantVal;
				}

				const chartColor = this.getColor();
				data.push({
					name: chlVo.readPlcNm + '(' + chlVo.readPlcId + ')',
					readPlcId: chlVo.readPlcId,
					upReadPlcId: chlVo.upReadPlcId,
					downPlcCnt: chlVo.downPlcCnt,
					itemStyle: {
						color: chartColor,
						borderColor: chartColor,
					},
					label: {
						show: true,
						formatter:
							chlVo.readPlcNm +
							'\n순시 :' +
							Utility.setFormatIntDecimal(chlVo.instantVal, 2) +
							'\n적산 :' +
							Utility.setFormatIntDecimal(chlVo.addupVal, 2),
						rich: this.pageData.richData,
					},
					tooltip: {
						formatter:
							chlVo.readPlcNm +
							'<br />순시 :' +
							Utility.setFormatIntDecimal(chlVo.instantVal, 2) +
							'<br />적산 :' +
							Utility.setFormatIntDecimal(chlVo.addupVal, 2),
						// formatter: [
						//   '{title|{b}}{titlebg|}',
						//   '  {typeHead|순시 : }{value|' + Utility.setFormatIntDecimal(chlVo.instantVal,2) + '}',
						//   '  {typeHead|적산 : }{value|' + Utility.setFormatIntDecimal(chlVo.addupVal,2) + '}',
						// ].join('\n'),
						// backgroundColor: '#eee',
						// borderColor: '#777',
						// borderWidth: 1,
						// borderRadius: 4,
						// rich: this.pageData.richData
					},
				});

				if (parentsVo != null) {
					console.debug('parentsVo : ', parentsVo);
					console.debug('parentsVo.readPlcNm : ', parentsVo.readPlcNm);
					link.push({
						source: parentsVo.readPlcNm + '(' + parentsVo.readPlcId + ')',
						target: chlVo.readPlcNm + '(' + chlVo.readPlcId + ')',
						value: chlVo.instantVal,
					});
				}
			} else {
				// 하위 자료가 없으면.
				let labelFormatter = '';
				let labelPosition = 'left';

				if (chlVo.maxLvl < 3 || chlVo.maxLvl > chlVo.lvl) {
					labelFormatter =
						chlVo.readPlcNm +
						'\n순시 :' +
						Utility.setFormatIntDecimal(chlVo.instantVal, 2) +
						'\n적산 :' +
						Utility.setFormatIntDecimal(chlVo.addupVal, 2);
				} else {
					labelFormatter = chlVo.readPlcNm;
				}

				if (chlVo.maxLvl > chlVo.lvl) {
					labelPosition = 'right';
				}

				const chartColor = this.getColor();
				data.push({
					name: chlVo.readPlcNm + '(' + chlVo.readPlcId + ')',
					readPlcId: chlVo.readPlcId,
					upReadPlcId: chlVo.upReadPlcId,
					downPlcCnt: chlVo.downPlcCnt,
					itemStyle: {
						color: chartColor,
						borderColor: chartColor,
					},
					label: {
						show: true,
						formatter: labelFormatter,
						position: labelPosition,
					},
					tooltip: {
						formatter:
							chlVo.readPlcNm +
							'<br />순시 :' +
							Utility.setFormatIntDecimal(chlVo.instantVal, 2) +
							'<br />적산 :' +
							Utility.setFormatIntDecimal(chlVo.addupVal, 2),
						// formatter: [
						//   '{title|{b}}{titlebg|}',
						//   '  {typeHead|순시 : }{value|' + Utility.setFormatIntDecimal(chlVo.instantVal,2) + '}',
						//   '  {typeHead|적산 : }{value|' + Utility.setFormatIntDecimal(chlVo.addupVal,2) + '}',
						// ].join('\n'),
						// backgroundColor: '#eee',
						// borderColor: '#777',
						// borderWidth: 1,
						// borderRadius: 4,
						// rich: this.pageData.richData
					},
				});

				if (parentsVo != null) {
					console.debug('parentsVo : ', parentsVo);
					console.debug('parentsVo.readPlcNm : ', parentsVo.readPlcNm);
					link.push({
						source: parentsVo.readPlcNm + '(' + parentsVo.readPlcId + ')',
						target: chlVo.readPlcNm + '(' + chlVo.readPlcId + ')',
						value: chlVo.instantVal == null ? 0 : chlVo.instantVal,
					});
				}

				retVal = chlVo.instantVal == null ? 0 : chlVo.instantVal;
				if (retVal < 0) {
					retVal = 0;
				}
			}

			// if(parentsVo == null){

			// }else{

			// }
			return retVal;
		},
		makeDataAndLinksOverVal(parentsVo, chlVo, data, link, otherVal) {
			//console.log("makeDataAndLinksOverVal : ", chlVo, data, link, otherVal);
			let labelFormatter = '';
			let labelPosition = 'left';

			if (chlVo.maxLvl < 3 || chlVo.maxLvl > chlVo.lvl + 1) {
				labelFormatter =
					chlVo.readPlcNm +
					'_미검침 사용량\n순시 :' +
					Utility.setFormatIntDecimal(otherVal, 2);
			} else {
				labelFormatter = chlVo.readPlcNm + '_미검침 사용량';
			}

			if (chlVo.maxLvl > chlVo.lvl + 1) {
				labelPosition = 'right';
			}

			// const chartColor = this.getColor();
			data.push({
				name: chlVo.readPlcNm + '_미검침 사용량(' + chlVo.readPlcId + '_OTHER)',
				readPlcId: chlVo.readPlcId + '_OTHER',
				upReadPlcId: chlVo.upReadPlcId,
				downPlcCnt: 0,
				itemStyle: {
					color: '#FF0000',
					borderColor: '#FF0000',
				},
				label: {
					show: true,
					formatter: labelFormatter,
					position: labelPosition,
				},
				tooltip: {
					formatter:
						chlVo.readPlcNm +
						'_미검침 사용량<br />순시 :' +
						Utility.setFormatIntDecimal(otherVal, 2),
				},
			});

			link.push({
				source: chlVo.readPlcNm + '(' + chlVo.readPlcId + ')',
				target:
					chlVo.readPlcNm + '_미검침 사용량(' + chlVo.readPlcId + '_OTHER)',
				value: otherVal,
				lineStyle: {
					color: '#FF0000',
				},
			});
		},
		getColor() {
			let retColor = '';
			if (this.pageData.colorInx1st > 4) {
				this.pageData.colorInx1st = 0;
				this.pageData.colorInx2st += 1;
			}
			if (this.pageData.colorInx2st > 9) {
				this.pageData.colorInx2st = 0;
				this.pageData.colorInx1st += 1;
			}

			if (this.isDarkMode) {
				retColor = this.pageData.darkColorSet[this.pageData.colorInx1st][
					this.pageData.colorInx2st
				];
			} else {
				retColor = this.pageData.lightColorSet[this.pageData.colorInx1st][
					this.pageData.colorInx2st
				];
			}
			this.pageData.colorInx1st += 1;
			return retColor;
		},
		chartDblClick(event) {
			// console.log("chartDblClick : ", event);
			if (event.componentType == 'series' && event.data.downPlcCnt > 0) {
				this.pageData.upReadPlcId = event.data.readPlcId;
				this.pageData.parentsReadPlcId = event.data.upReadPlcId;
			}
		},
		chartClick(evnet) {
			// console.log("chartClick : ", evnet);
			//console.log(evnet.componentType, evnet.componentIndex, this.pageData.upReadPlcId, this.pageData.parentsReadPlcId);
			if (evnet.componentType == 'title' && evnet.componentIndex == 1) {
				// console.log("여기 오남 : ", this.pageData.upReadPlcId, this.pageData.parentsReadPlcId);
				this.pageData.upReadPlcId = this.pageData.parentsReadPlcId;
				// console.log("여기 오남 2 : ", this.pageData.upReadPlcId, this.pageData.parentsReadPlcId);
			}
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	upReadPlcId: 'ROOT',
	parentsReadPlcId: 'RPC000001',
	energyCd: 'ROI000001',
	energyList: [],
	blocId: '',
	blocMstrList: [],

	viewCheck: 'viewAll',

	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정

	colorInx1st: 0,
	colorInx2st: 0,

	/*chartdata 세팅 */
	sankyChart: {
		tooltip: {
			trigger: 'axis',
			confine: true,
			axisPointer: {
				type: 'shadow',
			},
		},
		grid: {
			left: '0',
			right: '0',
			top: '0',
		},
		legend: null,
		series: [],
		title: {},
		backgroundColor: '',
	},

	richData: {
		title: {
			color: '#eee',
			align: 'center',
		},
		titleBg: {
			backgroundColor: '#999',
			width: '100%',
			align: 'right',
			height: 25,
			borderRadius: [4, 4, 0, 0],
		},
		typeHead: {
			color: '#333',
			height: 24,
			width: 40,
			align: 'left',
		},
		value: {
			color: '#333',
			width: 70,
			padding: [0, 10, 0, 10],
			align: 'right',
		},
	},

	darkColorSet: [
		[
			'#01AE6A',
			'#04A166',
			'#089362',
			'#0B865D',
			'#0F7959',
			'#126C55',
			'#165E51',
			'#19514D',
			'#1D4448',
			'#1F3D46',
		],
		[
			'#FFB046',
			'#EAA345',
			'#D39545',
			'#BE8844',
			'#A77A44',
			'#926D43',
			'#7C5F42',
			'#665242',
			'#4C4141',
			'#453D41',
		],
		[
			'#F6637B',
			'#E15D75',
			'#CC576F',
			'#B75269',
			'#A24C63',
			'#8D465E',
			'#784058',
			'#633B52',
			'#4E354C',
			'#433249',
		],
		[
			'#944FE9',
			'#894BD8',
			'#7E47C7',
			'#7344B7',
			'#6740A5',
			'#5C3C95',
			'#513884',
			'#463473',
			'#3A3162',
			'#352F59',
		],
		[
			'#4385E3',
			'#407CD3',
			'#3D73C2',
			'#3A6AB2',
			'#3760A2',
			'#345792',
			'#304E81',
			'#2D4571',
			'#2A3B61',
			'#293758',
		],
	],
	lightColorSet: [
		[
			'#3CC380',
			'#4BC88A',
			'#5BCD94',
			'#6BD19E',
			'#7BD6A9',
			'#8ADBB3',
			'#99E0BD',
			'#A9E5C7',
			'#B9E9D1',
			'#C9EEDC',
		],
		[
			'#FFB13B',
			'#FFB74A',
			'#FFBE5B',
			'#FFC46A',
			'#FFCA7A',
			'#FFD089',
			'#FFD699',
			'#FFDDA9',
			'#FFE3B8',
			'#FFE9C8',
		],
		[
			'#F98694',
			'#F98F9C',
			'#FA99A5',
			'#FAA3AE',
			'#FBADB6',
			'#FBB6BF',
			'#FCC0C7',
			'#FCCAD0',
			'#FDD3D8',
			'#FDDDE1',
		],
		[
			'#CF74E5',
			'#D37FE7',
			'#D78AE9',
			'#DA95EB',
			'#DEA1ED',
			'#E2ACEF',
			'#E6B7F1',
			'#EAC2F4',
			'#EECDF6',
			'#F2D8F8',
		],
		[
			'#6A9BF4',
			'#76A3F5',
			'#82ABF6',
			'#8EB3F7',
			'#9ABBF8',
			'#A6C3F8',
			'#B1CBF9',
			'#BED3FA',
			'#C9DBFB',
			'#D6E3FC',
		],
	],
};
</script>
