<template>
	<div class="l-layout">
		<v-row ref="rowParent">
			<v-col :cols="12">
				<v-card class="pa-3 widget-card">
					<div class="d-flex align-center justify-space-between">
						<v-card-title class="pa-0">에너지 사용현황</v-card-title>
						<v-card-subtitle class="mt-0 pa-0">
							<v-icon
								v-show="widgetPrgmId"
								class="mr-1"
								size="25"
								@click="btnAction('widgetCallPage')"
								>mdi-note-search</v-icon
							>
							<v-icon
								v-show="widgetPopFg"
								size="25"
								@click="btnAction('popWidget')"
								>mdi-plus-box-multiple</v-icon
							>
						</v-card-subtitle>
					</div>
					<v-card-actions class="d-flex justify-sm-end pb-0 pr-0 pt-1">
						<v-row>
							<v-col cols="3" sm="3" md="4" lg="6"></v-col>
							<v-col
								cols="6"
								sm="6"
								md="5"
								lg="4"
								class="d-flex align-center justify-end"
							>
								<v-radio-group
									v-model="rdbEnrgUsage"
									hide-details
									dense
									row
									class="mt-0"
									style="float:right"
								>
									<v-radio
										label="금일"
										value="hour"
										:color="isDarkMode ? '#2d8cf6' : '#4777d9'"
										on-icon="mdi-record-circle"
										:ripple="false"
									></v-radio>
									<v-radio
										label="금월"
										value="month"
										:color="isDarkMode ? '#2d8cf6' : '#4777d9'"
										on-icon="mdi-record-circle"
										:ripple="false"
									></v-radio>
								</v-radio-group>
							</v-col>
							<v-col cols="3" sm="3" md="3" lg="2">
								<v-select
									v-model="selectValue"
									:items="this.energyList"
									item-text="enrgNm"
									item-value="cd"
									solo
									outlined
									:hide-details="true"
									append-icon="mdi-chevron-down"
									class="v-select__widget pr-2"
								></v-select>
							</v-col>
						</v-row>
					</v-card-actions>
					<div class="d-flex align-center justify-space-between">
						<div :style="{ width: '100%', height: '200px' }">
							<component
								class="w100 h100"
								:is="loadChart_01 ? 'Chart' : null"
								:parentPrgmId="parentPrgmId"
								:widgetId="'EnrgUseReptWidget'"
								:widgetData="'EnrgUseReptWidgetData'"
								:chartName="chart_01"
								ref="chart_01"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex'; // , mapActions
import Vue from 'vue';
import DateUtility from '~/plugins/dateUtility';
import Utility from '~/plugins/utility';
import Chart from '~/components/common/Chart';

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		widgetId: {
			type: String,
			require: true,
		},
		widgetPrgmId: {
			type: Boolean,
			default: true,
		},
		widgetPopFg: {
			type: Boolean,
			default: true,
		},
		widgetReflashMm: {
			type: Number,
			require: true,
		},
	},
	components: {
		DateUtility,
		Chart,
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: 'isDarkMode',
		}),
		selectValue: {
			get() {
				return this.energyCd;
			},
			set(value) {
				this.energyCd = value;
			},
		},
	},
	watch: {
		rdbEnrgUsage() {
			this.getEnrgUsage();
		},
		energyCd() {
			this.setUnitLabel();
			this.getEnrgUsage();
		},
	},
	beforeCreate() {
		this.$store.commit('setWidgetPageData', {
			prgmId: this.$route.query.prgmId,
			EnrgUseReptWidget: { EnrgUseReptWidgetData },
		});
	},
	async created() {
		this.energyList = await this.postApiReturn({
			apiKey: 'selectEnergy',
			resKey: 'energyData',
			sendParam: {
				useFg: 1,
			},
		});
		this.energyCd = this.energyList[0].cd;
		this.unit = this.energyList[0].unit;
		this.search();
		this.timer = setInterval(this.search, this.widgetReflashMm);
	},
	beforeDestroy() {
		window.clearTimeout(this.timer);
	},
	mounted() {},
	data() {
		return {
			blocNm: '',
			//차트
			chart_01: 'enrgUsage',
			loadChart_01: false,
			//바인딩
			rdbEnrgUsage: 'hour',
			rdbElecQual: 'Kw',
			energyCd: '',
			energyList: [],
			unit: '',
		};
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setWidgetChartOption: 'setWidgetChartOption',
			openDashboardWidget: 'openDashboardWidget',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postApiReturn: 'modules/list/postApiReturn',
			getEnergyList: 'modules/search/getEnergyList',
		}),
		setBlocNm() {
			this.blocNm = this.$store.state.userInfo.blocNm;
			if (this.blocNm != '') {
				this.blocNm = '[' + this.blocNm + ']';
			}
		},
		setUnitLabel() {
			this.energyList.filter(item => {
				if (item.cd == this.energyCd) {
					this.unit = item.unit;
				}
			});
		},
		async search() {
			this.setBlocNm();
			await this.getEnrgUsage();
		},
		async getEnrgUsage() {
			this.loadChart_01 = false;
			let paramApiKey = '';
			let markAreaData = [];
			let markColor = {
				MAX: 'rgba(238, 102, 102, 0.1)',
				MID: 'rgba(250, 200, 88, 0.1)',
				MIN: 'rgba(145, 204, 117, 0.1)',
			};
			if (this.rdbEnrgUsage == 'hour') {
				paramApiKey = 'selectEnrgUsageHour';
				if (this.energyCd == 'ROI000001') {
					let res3 = [];

					// 부하시간 가져오기
					res3 = await this.postApiReturn({
						apiKey: 'selectPeakKine',
						resKey: 'peakData',
						sendParam: {
							readObjId: this.energyCd,
							toObjDt: Utility.setFormatDate(new Date(), 'YYYYMMDD'),
						},
					});
					markAreaData = res3.map(item => [
						{
							name: item.commCdNm,
							xAxis:
								parseInt(item.strtTm.split(':')[0].replace(/(^0+)/, '')) == 23
									? 0
									: parseInt(item.strtTm.split(':')[0].replace(/(^0+)/, '')),
							itemStyle: {
								color: markColor[item.peakKine],
							},
							label: {
								distance: [0],
								fontSize: 9,
								color: '#fff',
							},
						},
						{
							xAxis: parseInt(item.endTm.split(':')[0].replace(/(^0+)/, '')),
						},
					]);
				}
			} else {
				paramApiKey = 'selectEnrgUsageMonth';
			}

			let res = await this.postApiReturn({
				apiKey: paramApiKey,
				resKey: 'enrgUsageData',
				sendParam: {
					readObjId: this.energyCd,
				},
			});

			this.$nextTick(() => {
				this.setChart01Data(res, markAreaData);
			});
		},

		//차트Setting
		async setChart01Data(data, markAreaData) {
			this.$store.state.pageData[
				this.parentPrgmId
			].EnrgUseReptWidget.EnrgUseReptWidgetData.series = [];
			if (!data.length) {
				return;
			}

			let xAxisData = [];
			let seriesData = [];
			let legendData = [];
			let arrDarkColors = ['rgba(1, 174, 106, 0.7)', 'rgba(67, 133, 227, 0.7)'];
			let arrLightColors = [
				'rgba(207, 116, 229, 0.7)',
				'rgba(106, 155, 244, 0.7)',
			];
			const arrColors = this.isDarkMode ? arrDarkColors : arrLightColors;

			if (this.rdbEnrgUsage == 'month') {
				var qtyNumber, qtyStr;
				for (var i = 1; i < 32; i++) {
					qtyNumber = i.toString().padStart(2, '0');
					qtyStr = 'qty' + qtyNumber;
					xAxisData.push(i + '일');
				}

				for (var i = 0; i < data.length; i++) {
					var tempObj = {};
					tempObj['name'] = data[i]['type'];
					if (data[i]['type'] == '금월 사용량') {
						tempObj['type'] = 'bar';
					} else {
						tempObj['type'] = 'line';
					}
					tempObj['data'] = [];
					tempObj['color'] = arrColors[i];
					tempObj['lineStyle'] = { width: 2 };
					// tempObj['areaStyle']	 = {
					//     opacity: 0.5,
					//     color: arrColors[i]
					// };
					tempObj['smooth'] = true;
					tempObj['showSymbol'] = false;

					legendData.push(data[i]['type']);

					for (var j = 0; j < 31; j++) {
						qtyNumber = (j + 1).toString().padStart(2, '0');
						qtyStr = 'qty' + qtyNumber;
						if (data[i].hasOwnProperty(qtyStr)) {
							tempObj['data'].push(
								parseFloat(
									Utility.setFormatIntDecimal(
										parseFloat(data[i][qtyStr]),
										2,
									).replace(',', ''),
								),
							);
							// tempObj['data'].push(parseFloat(data[i][qtyStr]));
						} else {
							tempObj['data'].push(0);
						}
					}
					seriesData.push(tempObj);
				}
			} else if (this.rdbEnrgUsage == 'hour') {
				var qtyNumber, qtyStr;
				for (var i = 0; i < 24; i++) {
					qtyNumber = i.toString().padStart(2, '0');
					qtyStr = 'qty' + qtyNumber;
					xAxisData.push(i + '시');
				}

				for (var i = 0; i < data.length; i++) {
					var tempObj = {};
					tempObj['name'] = data[i]['type'];
					if (data[i]['type'] == '금일 사용량') {
						tempObj['type'] = 'bar';
					} else {
						tempObj['type'] = 'line';
					}
					tempObj['data'] = [];
					tempObj['color'] = arrColors[i];
					tempObj['lineStyle'] = { width: 2 };
					if (markAreaData != null) {
						tempObj['markArea'] = {
							data: markAreaData,
						};
					}
					// tempObj['areaStyle']	 = {
					//     opacity: 0.5,
					//     color: arrColors[i]
					// };
					tempObj['smooth'] = true;
					tempObj['showSymbol'] = false;
					legendData.push(data[i]['type']);

					for (var j = 0; j < 24; j++) {
						qtyNumber = j.toString().padStart(2, '0');
						qtyStr = 'qty' + qtyNumber;
						if (data[i].hasOwnProperty(qtyStr)) {
							tempObj['data'].push(
								Utility.setFormatIntDecimal(
									parseFloat(data[i][qtyStr]),
									2,
								).replace(',', ''),
							);
							// tempObj['data'].push(parseFloat(data[i][qtyStr]));
						} else {
							tempObj['data'].push(0);
						}
					}
					//console.log("data : " ,tempObj);
					seriesData.push(tempObj);
				}
			}

			var chartOption = {
				series: seriesData,
				grid: {
					left: '1%',
					right: '2%',
					top: '15%',
					bottom: '15%',
					containLabel: true,
				},
				legend: {
					data: legendData,
					bottom: 'bottom',
					icon: 'bar',
				},
				xAxis: {
					type: 'category',
					//boundaryGap: false,
					splitLine: false,
					data: xAxisData,
					axisLabel: {
						fontSize: 9,
					},
				},
				yAxis: {
					type: 'value',
					name: this.unit,
					splitLine: false,
					nameTextStyle: {
						fontSize: 12,
						fontWeight: 'bold',
					},
					axisLabel: {
						color: '#767D83',
						fontSize: 9,
					},
				},
				tooltip: {
					trigger: 'axis',
				},
			};

			this.setWidgetChartOption({
				prgmId: this.$route.query.prgmId,
				widgetKey: 'EnrgUseReptWidget',
				widgetData: 'EnrgUseReptWidgetData',
				chartKey: 'enrgUsage',
				value: chartOption,
			});

			this.loadChart_01 = true;
		},
		btnAction(action) {
			switch (action) {
				case 'popWidget':
					this.openDashboardWidget({
						prgmId: this.$route.query.prgmId,
						widgetId: this.widgetId,
					});
					break;
				case 'widgetCallPage':
					this.$parent.$parent.$parent.openWidgetPrgm(this.widgetId);
					break;
			}
		},
	},
};
const EnrgUseReptWidgetData = {
	enrgUsage: Utility.defaultChartOption(true),
};
</script>

<style lang="scss" scoped>
.v-avatar {
	border-radius: 21px;
	font-size: 1.75rem;
}
.v-virtual-scroll-wrapper {
	overflow-y: auto;
	max-height: 210px;
}
.v-radio > label {
	font-size: 0.8rem;
}
.v-list-item {
	min-height: 30px;
	line-height: 1;
}
.v-list-item__content > * {
	line-height: 1;
}
.v-select__widget > .v-input__control > .v-input__slot {
	min-width: 60%;
}
</style>
