<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">
							<div hidden>
								<component
									:is="'SelectBlocMstr'"
									ref="SelectBlocMstr"
									:parentPrgmId="parentPrgmId"
									:hidden="true"
								/>
							</div>
							<component
								ref="MainReadReptReadObjMultiPop"
								:is="'MainReadReptReadObjMultiPop'"
								:parentPrgmId="parentPrgmId"
								:eqpmYn="0"
								:labelCols="2"
								:textCols="10"
								:popTitle="'검침대상 목록'"
								:widgetId="'ElecQualWidget'"
								@chDialogViewElecQualWidget="dialogViewChange"
							/>
							<v-tooltip bottom>
								<template v-slot:activator="{ on, attrs }">
									<v-icon
										class="mr-1"
										size="25"
										v-bind="attrs"
										v-on="on"
										@click="readObjDialog"
										>mdi-tooltip-plus</v-icon
									>
								</template>
								<span>품질</span>
							</v-tooltip>
							<component
								:is="'ReadPlcWidgetPop'"
								:parentPrgmId="parentPrgmId"
								:widGetKey="'ElecQualWidget'"
								:widgetDataKey="'ElecQualWidgetData'"
								:isMulti="true"
								@chDialogViewElecQualWidget="dialogViewChange"
								:mntrFg="'1'"
							/>
							<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>
					<div class="row">
						<div :style="{ width: '100%', height: '230px' }">
							<component
								class="w100 h100"
								:is="loadChart ? 'Chart' : null"
								:parentPrgmId="parentPrgmId"
								:chartName="chartName"
								:widgetId="'ElecQualWidget'"
								:widgetData="'ElecQualWidgetData'"
								ref="chart"
							/>
						</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';
import ReadPlcWidgetPop from '~/components/common/modal/ReadPlcWidgetPop';
import MainReadReptReadObjMultiPop from '~/components/common/modal/MainReadReptReadObjMultiPop';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';

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,
		ReadPlcWidgetPop,
		SelectBlocMstr,
		MainReadReptReadObjMultiPop,
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: 'isDarkMode',
		}),
	},
	watch: {},
	beforeCreate() {
		this.$store.commit('setWidgetPageData', {
			prgmId: this.$route.query.prgmId,
			// defaultData: defaultData,
			ElecQualWidget: { ElecQualWidgetData: ElecQualWidget },
		});
	},
	created() {
		this.search();
		this.timer = setInterval(this.search, this.widgetReflashMm);
	},
	beforeDestroy() {
		window.clearTimeout(this.timer);
	},
	mounted() {},
	data() {
		return {
			loadChart: false,
			selectedQualityKind: null,
			selectedReadPlcId: null,
			paramReadObjId: 'ROI00005',
			chartName: 'elecQualityChart',
			// readPlcPopItem:readPlcPopItem,
		};
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setWidgetChartOption: 'setWidgetChartOption',
			openDashboardWidget: 'openDashboardWidget',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postApiReturn: 'modules/list/postApiReturn',
		}),
		async search() {
			await this.getElecQuality();
		},
		async getElecQuality() {
			this.loadChart = false;
			var plcKindList =
				this.searchParam['ElecQualWidget']['ElecQualWidgetData'].plcKindList
					.length > 0
					? this.searchParam['ElecQualWidget'][
							'ElecQualWidgetData'
					  ].plcKindList.map(item => {
							return item.readPlcId;
					  })
					: null;
			var readObjId =
				this.searchParam['ElecQualWidget']['ElecQualWidgetData'].readObjList
					.length > 0
					? this.searchParam['ElecQualWidget']['ElecQualWidgetData']
							.readObjList[0].readObjId
					: 'ROI000005';
			//console.log('plcKindList : ', plcKindList);
			const res = await this.postApiReturn({
				apiKey: 'selectWidgetElecQuality',
				resKey: 'elecQualData',
				sendParam: {
					readObjId: readObjId,
					readPlcIdList: plcKindList,
				},
			});

			await this.setChartData(res);
		},
		async setChartData(data) {
			this.$store.state.pageData[
				this.parentPrgmId
			].ElecQualWidget.ElecQualWidgetData.series = [];
			//console.log('res : ', data);
			if (!data.length) {
				return;
			}
			var xAxisData = [];
			var seriesData = [];
			var legendData = [];
			var yName = data[0]['readObjUnit'];

			var readPlcIdChk = data[0]['readPlcId'];
			for (var i = 0; i < data.length; i++) {
				if (readPlcIdChk == data[i]['readPlcId']) {
					xAxisData.push(
						data[i]['readDttm']
							? Utility.setFormatDate(data[i]['readDttm'], 'HH:mm')
							: '',
					);
				}
			}
			var tempObj = {};
			tempObj['data'] = [];
			for (var i = 0; i < data.length; i++) {
				if (i > 0) {
					if (readPlcIdChk == data[i]['readPlcId']) {
						tempObj['data'].push(data[i]['readVal']);
						if (i == data.length - 1) {
							seriesData.push(tempObj);
						}
					} else {
						seriesData.push(tempObj);
						//비교 readPlc 변경
						readPlcIdChk = data[i]['readPlcId'];
						tempObj = {};
						tempObj['data'] = [];
						tempObj['name'] = data[i]['readPlcNm'];
						tempObj['type'] = 'line';
						tempObj['data'].push(data[i]['readVal']);
						legendData.push(data[i]['readPlcNm']);
					}
				} else {
					tempObj['name'] = data[i]['readPlcNm'];
					tempObj['type'] = 'line';
					tempObj['data'].push(parseFloat(data[i]['readVal']));
					legendData.push(data[i]['readPlcNm']);
				}
			}

			var chartOption = {
				grid: {
					top: '15%',
					bottom: '15%',
				},
				legend: {
					type: 'scroll',
					pageIconColor: '#18579e',
					pageIconInactiveColor: '#ffffff66',
					pageTextStyle: { color: '#fff' },
					data: legendData,
				},
				xAxis: {
					data: xAxisData,
				},
				yAxis: {
					name: yName,
					splitLine: {
						show: true,
						lineStyle: {
							color: this.isDarkMode ? '#fff' : '#cccccc',
							opacity: this.isDarkMode ? 0.2 : 1,
							type: 'dotted',
							width: 2,
						},
					},
				},
				series: seriesData,
			};
			// console.log('utility chartoption : ', Utility.defaultChartOption());

			this.setWidgetChartOption({
				prgmId: this.$route.query.prgmId,
				widgetKey: 'ElecQualWidget',
				widgetData: 'ElecQualWidgetData',
				chartKey: 'elecQualityChart',
				value: chartOption,
			});

			this.loadChart = true;
		},
		async dialogViewChange() {
			await this.search();
		},
		readObjDialog() {
			this.$store.state.pageData[this.parentPrgmId]['ElecQualWidget'][
				'ElecQualWidgetData'
			].enrgDiv = 'MTT_ELEC';
			this.$refs['MainReadReptReadObjMultiPop'].dialog = 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 ElecQualWidget = {
	elecQualityChart: Utility.defaultChartOption(true),
	blocId: 0,
	blocMstrList: [],
	modalData: {},
	rowGridSelectData: null,
	rowGridSelectKey: 0,
	plcKindList: [],
	isMulti: false,
	readObjList: [],
	readObj: null,
};
</script>

<style lang="scss" scoped>
.v-avatar {
	border-radius: 21px;
	font-size: 1.75rem;
}
.v-virtual-scroll-wrapper {
	overflow-y: auto;
	max-height: 210px;
}
</style>
