<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="enrgUseViewFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="center" no-gutters>
						<v-col :cols="3">
							<v-row align="center" no-gutters>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>전력</strong
											>
										</div>
									</div>
								</v-col>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>{{ cumulUsage_elec
												}}<span class="body-2"> Kwh</span></strong
											>
										</div>
									</div>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3">
							<v-row align="center" no-gutters>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>가스</strong
											>
										</div>
									</div>
								</v-col>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>{{ cumulUsage_gas
												}}<span class="body-2"> Kg</span></strong
											>
										</div>
									</div>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3">
							<v-row align="center" no-gutters>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>스팀</strong
											>
										</div>
									</div>
								</v-col>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>{{ cumulUsage_stem
												}}<span class="body-2"> m³</span></strong
											>
										</div>
									</div>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3">
							<v-row align="center" no-gutters>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>에어</strong
											>
										</div>
									</div>
								</v-col>
								<v-col :cols="6">
									<div class="v-box " style="width:95%; min-width: 100px">
										<div class="text-center" style="width:100%">
											<strong class="custom-title-8" style="text-align: center;"
												>{{ cumulUsage_air
												}}<span class="body-2"> Ton</span></strong
											>
										</div>
									</div>
								</v-col>
							</v-row>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" :eager="true">
			<v-col style="height:100%;" :cols="12">
				<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="chartName"
						/>
					</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: 'treemapChart',

			// 바인딩 (사용량 표시용)
			cumulUsage_elec: 0,
			cumulUsage_gas: 0,
			cumulUsage_stem: 0,
			cumulUsage_air: 0,

			cumulAmt_elec: 0,
			cumulAmt_gas: 0,
			cumulAmt_stem: 0,
			cumulAmt_air: 0,

			currUsage_elec: 0,
			currUsage_gas: 0,
			currUsage_stem: 0,
			currUsage_air: 0,
		};
	},
	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;
		},
		chkDarkMode() {
			return this.isDarkMode;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkBlocCd() {
			this.setPageData({ isFind: true });
		},
		chkEnergyCd() {
			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); //5분 주기마다 갱신
	},
	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;
			const enrgUseViewFilterHeight = this.$refs.enrgUseViewFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px - ${enrgUseViewFilterHeight}px`;
		},
		// 에너지 계통 실시간 조회
		async getChartData() {
			// console.log("getChartData 시작");
			this.loadChart = false;

			let res = [];
			// console.log("this.pageData.blocMstrList.length : ", this.pageData.blocMstrList.length);
			// console.log("this.pageData.energyList.length : ", this.pageData.energyList.length);

			if (
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.energyList.length > 0
			) {
				res = await this.postApiReturn({
					apiKey: 'selectEnrgPlantStatusMonitoringInfo',
					//resKey:"enrgUseMonitoringInfoData",
					resKey: 'enrgPlantStatusMonitoringInfoTreeData',
					// sendParm : sendParams
					sendParam: {
						readObjId: this.pageData.energyList[this.pageData.energyCd].cd,
						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 = [];
			this.pageData.colorInx1st = 0;
			this.pageData.colorInx2st = 0;

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

			const option = {
				//       color: ['#5470c6',
				// '#91cc75',
				// '#fac858',
				// '#ee6666',
				// '#73c0de',
				// '#3ba272',
				// '#fc8452',
				// '#9a60b4',
				// '#ea7ccc'],
				tooltip: {
					// formatter: function (info) {
					//   var value = info.value;
					//   var treePathInfo = info.treePathInfo;
					//   var treePath = [];
					//   for (var i = 1; i < treePathInfo.length; i++) {
					//     treePath.push(treePathInfo[i].name);
					//   }
					//   return [
					//     '<div class="tooltip-title">' +
					//       echarts.format.encodeHTML(treePath.join('/')) +
					//       '</div>',
					//     'Disk Usage: ' + echarts.format.addCommas(value) + ' KB'
					//   ].join('');
					// }
				},
				series: [
					{
						name: '전력',
						type: 'treemap',
						visibleMin: 300,
						label: {
							show: true,
							formatter: '{b}',
						},
						upperLabel: {
							show: true,
							height: 30,
						},
						itemStyle: {
							borderColor: '#fff',
						},
						levels: [
							{
								itemStyle: {
									borderColor: '#777',
									borderWidth: 0,
									gapWidth: 1,
								},
								upperLabel: {
									show: false,
								},
							},
							{
								itemStyle: {
									borderColor: '#555',
									borderWidth: 5,
									gapWidth: 1,
								},
								emphasis: {
									itemStyle: {
										borderColor: '#ddd',
									},
								},
							},
							{
								colorSaturation: [0.35, 0.5],
								itemStyle: {
									borderWidth: 5,
									gapWidth: 1,
									borderColorSaturation: 0.6,
								},
							},
						],
						data: makeData,
					},
				],
			};

			this.setChartOption({ chartKey: this.chartName, value: option });
			this.loadChart = true;
		},
		async setChartSeriesData(data) {
			let makeData = [];

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

			const seriesData = {
				type: 'sunburst',
				data: makeData,
				radius: [0, '95%'],
				sort: undefined,
				emphasis: {
					focus: 'ancestor',
				},
				levels: [
					{},
					{
						r0: '15%',
						r: '35%',
						itemStyle: {
							borderWidth: 2,
						},
						label: {
							rotate: 'tangential',
						},
					},
					{
						r0: '35%',
						r: '70%',
						label: {
							align: 'right',
						},
					},
					{
						r0: '70%',
						r: '73%',
						label: {
							position: 'outside',
							padding: 3,
							silent: false,
						},
						itemStyle: {
							borderWidth: 3,
						},
					},
					{
						r0: '73%',
						r: '75%',
						label: {
							position: 'outside',
							padding: 3,
							silent: false,
						},
						itemStyle: {
							borderWidth: 3,
						},
					},
				],
			};

			this.setChartSeries({ chartKey: this.chartName, value: seriesData });
		},
		search() {
			let urlPath = this.$router.currentRoute.fullPath;
			let index = urlPath.indexOf('/ems/base/EnrgPlantStatusMonitoringMngPage');
			if (index >= 0) {
				this.getChartData();
			}
		},
		searchInit() {
			this.pageData.upEccId = 'ROOT';
		},
		async searchTimer() {
			let urlPath = this.$router.currentRoute.fullPath;
			let index = urlPath.indexOf('/ems/base/EnrgPlantStatusMonitoringMngPage');
			if (index >= 0) {
				let res = [];
				if (
					this.pageData.blocMstrList.length > 0 &&
					this.pageData.energyList.length > 0
				) {
					res = await this.postApiReturn({
						apiKey: 'selectEnrgUseMonitoringInfo',
						//resKey:"enrgUseMonitoringInfoData",
						resKey: 'enrgUseMonitoringInfoTreeData',
						// 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;
		},
		makeData(parentsVo, chlVo) {
			let retVal = {};
			//console.log("chlVo.has('childeVo') : ", chlVo["childeVo"]);
			if (chlVo['childeVo'] != null || chlVo['childeVo'] != undefined) {
				// 하위 자료가 있으면
				let subSum = 0;
				let chartChildren = [];
				for (var idx in chlVo['childeVo']) {
					let subRet = this.makeData(chlVo, chlVo['childeVo'][idx]);
					subSum += subRet.value;

					chartChildren.push(subRet.data);
				}

				if (chlVo.instantVal > subSum) {
					//chartChildren.push(this.makeDataOverVal(parentsVo, chlVo, chlVo.instantVal - subSum));
				}
				// const chartColor = this.getColor();
				const chdData = {
					value:
						chlVo.instantVal == null ||
						chlVo.instantVal == 0 ||
						chlVo.instantVal < subSum
							? subSum
							: chlVo.instantVal,
					name: chlVo.eccNm,
					path: chlVo.eccPath,
					children: chartChildren,
				};

				retVal = {
					data: chdData,
					value:
						chlVo.instantVal == null ||
						chlVo.instantVal == 0 ||
						chlVo.instantVal < subSum
							? subSum
							: chlVo.instantVal,
				};
			} else {
				// 하위 자료가 없으면.
				// const chartColor = this.getColor();
				const chdData = {
					value: chlVo.instantVal == null ? 0 : chlVo.instantVal,
					name: chlVo.eccNm,
					path: chlVo.eccPath,
				};
				retVal = {
					data: chdData,
					value: chlVo.instantVal == null ? 0 : chlVo.instantVal,
				};
			}

			return retVal;
		},
		makeDataOverVal(parentsVo, chlVo, otherVal) {
			const chdData = {
				name: chlVo.eccNm + '_미검침 사용량',
				eccId: chlVo.eccId + '_OTHER',
				upEccId: chlVo.upEccId,
				value: 1,
				itemStyle: {
					color: '#FF0000',
					curveness: 0.5,
				},
				tooltip: {
					formatter:
						chlVo.eccNm +
						'_미검침 사용량<br />순시 :' +
						Utility.setFormatIntDecimal(otherVal, 2),
				},
			};

			return chdData;
		},
		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;
		},
		labelGen(value, splitLangth) {
			let retVal = '';
			let subStrInx = 0;
			if (value.length <= splitLangth) {
				retVal = value;
			} else {
				subStrInx = this.sliceByByte(value, splitLangth);
				retVal +=
					value.substring(0, subStrInx) +
					'\n' +
					this.labelGen(value.substring(subStrInx + 1), splitLangth);
			}

			return retVal;
		},
		labelGen2(value, splitLangth, maxLineLength) {
			let retVal = '';
			let sumLength = 0;
			let subStrInx = 0;
			let splitVal = value.split(' ');
			for (let idx in splitVal) {
				if (splitVal[idx].length >= splitLangth) {
				} else {
				}
			}

			return retVal;
		},
		sliceByByte(str, maxByte) {
			let b = 0;
			let i = 0;
			let c = '';
			for (b = i = 0; (c = str.charCodeAt(i)); ) {
				b += c >> 7 ? 2 : 1;
				if (b > maxByte) {
					break;
				}
				i++;
			}

			return i;
		},
		chartDblClick(event) {
			//console.log("chartClick : ", 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: 'ROOT',
	energyCd: 'ROI000001',
	energyList: [],
	blocId: '',
	blocMstrList: [],

	viewCheck: 'viewAll',

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

	colorInx1st: 0,
	colorInx2st: 0,

	/*chartdata 세팅 */
	treemapChart: {
		tooltip: {},
		series: [
			{
				name: '전력',
				type: 'treemap',
				visibleMin: 300,
				label: {
					show: true,
					formatter: '{b}',
				},
				upperLabel: {
					show: true,
					height: 30,
				},
				itemStyle: {
					borderColor: '#fff',
				},
				levels: [
					{
						itemStyle: {
							borderColor: '#777',
							borderWidth: 0,
							gapWidth: 1,
						},
						upperLabel: {
							show: false,
						},
					},
					{
						itemStyle: {
							borderColor: '#555',
							borderWidth: 5,
							gapWidth: 1,
						},
						emphasis: {
							itemStyle: {
								borderColor: '#ddd',
							},
						},
					},
					{
						colorSaturation: [0.35, 0.5],
						itemStyle: {
							borderWidth: 5,
							gapWidth: 1,
							borderColorSaturation: 0.6,
						},
					},
				],
				data: [],
			},
		],
	},

	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>
