<template>
	<v-row class="search-box" align="center" no-gutters >
		<v-dialog
			ref="popModal"
			v-model="dialog"
			width="900"
			overlay-color="#000"
			overlay-opacity="0.8"
			scrollable
		>
			<v-card style="height: 100%">
				<v-card-title class="pa-5 pb-0 d-flex align-center justify-space-between">
					<span class="custom-title-4">사용량 계획</span>
					<v-icon @click="closePop()">mdi-close</v-icon>
				</v-card-title>

				<div class="pa-5">
					<!-- <v-text-field label="위치정보 선택"></v-text-field> -->
					<v-row align="center" no-gutters>
						<v-col :cols="4.5">
							<InputText
								:parentPrgmId="parentPrgmId"
								:label="'설비명'"
								:valueNm="'eqpmNm'"
								:readonly="true"
							/>
						</v-col>
					</v-row>
					<v-row align="end" no-gutters class="mt-4 d-flex justify-center">
						<v-col :cols="5.5" class="mr-2">
							<component
								:is="'SelectBox'"
								ref="SelectBox1"
								:labelCols='12'
								:textCols='12'
								:propsValue="selectValue01"
								:itemList="selectValueList01"
								:label="'대상월'"
								@update:propsValue="selectValue01 = $event"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="5.5" class="mr-2">
							<component
								:is="'SelectBox'"
								ref="SelectBox2"
								:labelCols='12'
								:textCols='12'
								:propsValue="selectValue02"
								:itemList="selectValueList02"
								:label="'전년대비절감율'"
								@update:propsValue="selectValue02 = $event"
								customClass="select-large"
							/>
						</v-col>
						<a-button class="ant-btn-popup-default" color="primary" dark @click="search()" icon="check-circle" size="large">
							<!-- <template #icon>
								<ClockCircleOutlined />
							</template> -->
							적용
						</a-button>
						<!-- <v-col :cols="2" class="text-right">
						</v-col> -->
					</v-row>
				</div>
				<!-- <v-divider></v-divider> -->
				
				<!-- <div id="chartParent" ref="chartParent" style="height: 100px"> -->
				<div :style="'height: calc(50vh)'">
					<!-- <div id="chartParent" ref="chartParent" :style="'height: 80%'"> -->
					<div id="chartParent" ref="chartParent" style="height: 100%" class="px-6">
						<component
							class="w100 h100 py-7 custom-chart"
							:is="loadChart ? 'Chart' : null"
							:parentPrgmId="parentPrgmId"
							:modalId="modalId"
							:modalDataKey="modalDataKey"
							:chartName="chartName"
							:ref="chartName"
						/>
					</div>
					<!-- <v-divider></v-divider> -->
					<!-- <div style="height: 20%; margin: auto; width: 90%; display: flex; align-items: center;"> -->
						<!-- <div style="height: 70%; width:10%; float: left; border: 1px solid blue; background-color: #A2A2A2">
							설정
						</div>
						<div style="height: 70%; width:90%; margin-left:10%; border: 1px solid blue;">
							<v-row align="center" no-gutters class="pa-5 d-flex align-center justify-center;">
								<v-col :cols="4">
								
								</v-col>
								<v-col :cols="4">
									
								</v-col>
								<v-col :cols="2" class="text-right">
									<v-btn color="primary" dark @click="setChart()">적용</v-btn>
								</v-col>
							</v-row>
						</div> -->
						<!-- <v-row align="center" no-gutters>
						<v-row
							:cols="12"
							class="d-flex align-center justify-space-between pa-3"
						>
							
							<v-col :cols="4">
								
							</v-col>
							<v-col :cols="4">
								
							</v-col>
							<v-col :cols="2" class="text-right">
								<v-btn color="primary" dark @click="setChart()">적용</v-btn>
							</v-col>
						</v-row> -->
					<!-- </div> -->
				</div>
				
					<!-- <div id="gridParent" ref="gridParent" style="height: 500px">
						<component
							:ref="'gridName' + parentPrgmId"
							:is="loadGrid && dialog ? 'Grid' : null"
							:gridName="gridName"
							:dataPath="searchParam.modifyEnrgUsePlanModalDataKey.modifyEnrgUsePlanModalData"
							:parentPrgmId="parentPrgmId"
							:bindingData="bindingData"
							@getRowsData="getRowData"
							@dblClick="setUpdate()"
						/>
					</div> -->
				
				<v-card-actions class="pa-5 d-flex align-center justify-end">
					<a-button color="primary" class="mr-2 ant-btn-popup-default" dark @click="closePop()">취소</a-button>					
					<a-button color="primary" type="primary" dark @click="setUpdate()">확정</a-button>
				</v-card-actions>
			</v-card>
		</v-dialog>
	</v-row>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import selectCodeList from '@/components/common/select/selectCodeList';
import InputText from '~/components/common/input/InputText';
import Chart from '~/components/common/Chart';
import SelectBox from '@/components/common/select/SelectBox';

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
			default: '비교대상 최대(20개)',
		},
		label: {
			type: String,
			require: false,
			default: '전력 계약 정보',
		},
		valueNm: {
			type: String,
			require: false,
			default: '',
		},
		title: {
			type: String,
			require: false,
			default: '전력 계약 목록',
		},
		labelCols: {
			type: Number,
			require: false,
			default: 4,
		},
		textCols: {
			type: Number,
			require: false,
			default: 7,
		},
		item: {
			type: Object,
			require: true,
		},
		bindingData: {
			type: String,
			require: false,
		}
	},
	components: {
		Grid,
		selectCodeList,
		InputText,
		Chart,
		SelectBox,
		// Tree
	},
	data() {
		return {
			labelPrepend: true,
			chartName: 'modifyEnrgUsePlanChart',
			modalId: 'modifyEnrgUsePlanModal',
			modalDataKey: 'modifyEnrgUsePlanModalDataKey',
			// gridName: 'rowElecContGrid',
			loadChart: false,	
			// selectedTargetMonth: 'all',
			dialog: false,
			selectValue01: null,
			selectValueList01: [],
			selectValue02: null,
			selectValueList02: [],
			nowModalChartData: [],
			nowSeriesData: [],


			activeRowData: {},
			checkedRowDataList: [],
		};
	},
	computed: {
		...mapState({
			// searchParam: state => state.pageData,
			// searchParam(state) {
			// 	return state.pageData[this.parentPrgmId];
			// },
			myBindingData(state) {
				//return state.pageData[this.parentPrgmId]["rowGridSelectData"];
				if (!this.bindingData) {
					return state.pageData[this.parentPrgmId]['rowGridSelectData'];
				} else {
					return state.pageData[this.parentPrgmId][this.bindingData][
						'rowGridSelectData'
					];
				}
			},
			rowGrid2SelectData(state) {
				if (!this.bindingData) {
					return state.pageData[this.parentPrgmId].rowGrid2SelectData;
				} else {
					return state.pageData[this.parentPrgmId][this.bindingData]
						.rowGrid2SelectData;
				}
			},
			popupDialogFg(state) {
				return state.pageData[this.parentPrgmId].popupDialogFg;
			}
		}),
		chkDialog(){
			return this.dialog
		},
		chkPopupDialogFg() {
			// 모달 열기/닫기 값
			// return this.dialog
			return this.popupDialogFg;
		},
		
		// 	get() {
		// 		// if(this.searchParam.rowGridSelectData){
		// 		//     return this.searchParam.rowGridSelectData[this.item.valueNm];
		// 		// }
		// 		return this.myBindingData ? this.myBindingData[this.item.valueNm] : '';
		// 	},
		// 	set(value) {
		// 		// return value;
		// 		// return this.myBindingData({ [this.item.valueNm]: value });
		// 		//return this.setPageData({ [this.item.valueNm]: value });
		// 		return this.myBindingData({ [this.item.valueNm]: value });
		// 	},
		// },
	},
	watch: {
		async chkDialog(val){
			if (val) {
				// await this.getData();
				this.nowModalChartData = this.rowGrid2SelectData;
				this.setChart();				
			} else {
				this.closePop();
			}			
		},
		chkPopupDialogFg(val) {
			this.dialog = val;
			
		},
		selectValue01(value){
			this.setSelectValueList02();
			// if(this.selectValue02 == '0'){
			// 	this.search();
			// }else{
			// 	this.setSelectValueList02();
			// }
		},
		selectValue02(value){
			
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modifyEnrgUsePlanModal: {modifyEnrgUsePlanModalDataKey},
		});
	},
	created() {
		this.setSelectValueList01();
		this.setSelectValueList02();
		this.init();
		// if(this.searchParam.isMulti == true){
		//   this.setPageData({
		//     facInfoList : localStorage.getItem(this.parentPrgmId + "CheckedRow") !=null ? JSON.parse(localStorage.getItem(this.parentPrgmId + "CheckedRow")) : {}
		//   });
		// }else{
		//   this.setPageData({
		//     facInfo : localStorage.getItem(this.parentPrgmId + "CheckedRow") !=null ? JSON.parse(localStorage.getItem(this.parentPrgmId + "CheckedRow")) : {}
		//   });
		// }
	},
	mounted(){
		// this.initTest(); return;
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setWidgetPageData: 'setWidgetPageData',
			setModalChartOption: 'setModalChartOption',
			setModalChartSeries: 'setModalChartSeries',
			setModalChartTooltip: 'setModalChartTooltip'
		}),
		...mapActions({
			postApiReturn: 'modules/list/postApiReturn',
		}),
		
		init() {
			this.setChart();
		},		
		setSelectValueList01(){
			this.selectValueList01 = [{'text' : '전체', 'value': 'all'}];
			for(var i=1; i<=12; i++){
				let qty = 'qty' + i.toString().padStart(2, '0');
				this.selectValueList01.push(
					{
						'text' : i+'월',
						'value': qty
					}
				);
			}
			this.selectValue01 = this.selectValueList01[0].value;
		},
		setSelectValueList02(){
			for(var i=0; i<=100; i+=5){
				this.selectValueList02.push(
					{
						'text' : i + '%',
						'value': String(i)
					}
				);
			}
			this.selectValue02 = this.selectValueList02[0].value;
		},
		// 계약 정보 조회
		setUpdate() {
			this.dialog = false;
			let nowSeriesData = this.nowSeriesData;
			let nowPlanData = nowSeriesData.filter(item => {
				return item.name == '계획';
			})[0];
			let nowPastData = nowSeriesData.filter(item => {
				return item.name == '전년실적';
			})[0];
			let qtyList = [];
			let qtyDict = {};
			for(var i=0; i<nowPlanData.data.length; i++){
				qtyList.push('qty' + (i+1).toString().padStart(2, '0'));
				qtyDict['qty' + (i+1).toString().padStart(2, '0')] = i;
				let dt = {
					columnName: 'qty' + (i+1).toString().padStart(2, '0'),
					value: nowPlanData['data'][i],
					// targetRowNum: this.rowGrid2SelectData[1].rowKey,
					rowKey: this.rowGrid2SelectData[1].rowKey,
					rowEditingFg : true
				}
				this.$emit('gridEditingFinish', dt);
				
			}
			
			let rowGrid2SelectData = this.rowGrid2SelectData;
			let newRowGrid2SelectData = rowGrid2SelectData.map(item => {
				qtyList.map(obj => {
					if(item.gubun == '2PLAN'){
						item[obj] = nowPlanData['data'][qtyDict[obj]];
					}else{
						item[obj] = nowPastData['data'][qtyDict[obj]];
					}
				})
				return item;
				
			})

			this.setPageData({rowGrid2SelectData: newRowGrid2SelectData});
		
		},
		closePop(){
			this.dialog = false;
			this.setPageData({popupDialogFg : false});
			this.selectValue01 = this.selectValueList01[0].value;
			this.selectValue02 = this.selectValueList02[0].value;
			this.nowSeriesData = [];
			this.nowModalChartData = [];
		},
		async initTestChart(){
			this.loadChart = false;
			let xAxisData = [];
			let seriesData = [];
			let data = [];
			let targetMonthList = [];
			let _this = this;

			const dataItemLine = []; // { gubun: '2PLAN' };
			const dataItemBar = []; //{ gubun: '1PLAN' };

			const getRanNum = (n) => Math.floor(Math.random()*n + 1);

			for(var i=1; i<=12; i++){
				let qty = 'qty' + i.toString().padStart(2, '0');
				targetMonthList.push(qty);
				xAxisData.push(i);
				dataItemLine.push(getRanNum(100));
				dataItemBar.push(getRanNum(100));
			}
			data = [
				{gubun: '1PLAN'}, {gubun: '2PLAN'}, 
			];
			
			seriesData = data.map(item => ({
				name: item.gubun == '2PLAN' ? '계획' : '전년실적',
				type: item.gubun == '2PLAN' ? 'line' : 'bar',
				data: item.gubun == '2PLAN' ? dataItemLine : dataItemBar
			}));
			this.nowSeriesData = seriesData;
			let option = {
				grid: {
					top: "3%",
				},
				xAxis:{
					type: 'category',
					data: xAxisData
				},
				yAxis:{
					type:'value',
					nameLocation : 'middle',
					nameGap :45
				},
				legend: {
					icon: 'circle',
				},
				series: seriesData,
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'cross'
					}
				}
			};
			
			await this.$nextTick(() => { });
			
			this.setModalChartOption({ 
				prgmId: this.$route.query.prgmId,
				chartKey: this.chartName,
				modalId: this.modalId,
				modalDataKey: this.modalDataKey,
				value: option,
			});
			this.loadChart = true;
			// this.$nextTick(() => {
			// })
		},
		async setChart(){
			this.loadChart = false;
			let xAxisData = [];
			let seriesData = [];
			let data = [];
			data = this.nowModalChartData;			
			let targetMonthList = [];
			let _this = this;
			let tooltipData = {
				trigger:'axis',
				confine: true,
				axisPointer:  {
					type: "shadow"
				},
				// valueFormatter: (value) => '$' +parseFloat(value).toFixed()
				formatter: function(params){
					var toolTipTitle = params[0].name[0];
					let res = "<div style='margin: 0px 0 0;line-height:1;'><div style='font-size:14px;color:#666;font-weight:400;line-height:1;'>"+toolTipTitle+"</div>";            
					for (var i = 0; i < params.length; i++) {
						let tempVal = parseFloat(params[i].value);
						if(Number.isFinite(tempVal)){
							tempVal = tempVal.toFixed();
						}else{
							if(!isNaN(tempVal)){
							tempVal = 0;
							}
						}
						res += "<div style='margin: 10px 0 0;line-height:1;'><div style='margin: 0px 0 0;line-height:1;'>"
							+"<span style='font-size:14px;color:#666;font-weight:400;margin-left:2px'>"+ params[i].marker 
							+ " "+params[i].seriesName+" "
							+"</span>"
							+"<span style='float:right;margin-left:20px;font-size:14px;color:#666;font-weight:900'>"
							+ _this.numberFormatter(tempVal)
							+"</b></span>"
							+"</div><div style='clear:both'></div></div>";
					}
					res += "</div>"
					return res;
				}
			}

			for(var i=1; i<=12; i++){
				let qty = 'qty' + i.toString().padStart(2, '0');
				targetMonthList.push(qty);
				xAxisData.push(i);
			}
			// data = data.map(item => ({
			// 	...item,
			// 	qty01: Math.floor(Math.random()*100),
			// 	qty02: Math.floor(Math.random()*100),
			// 	qty03: Math.floor(Math.random()*100),
			// 	qty07: Math.floor(Math.random()*100)
			// }));
			seriesData = data.map(item => ({
				name: item.gubun == '2PLAN' ? '계획' : '전년실적',
				type: item.gubun == '2PLAN' ? 'line' : 'bar',
				data: targetMonthList.map(obj => item[obj] || null),
				// data: targetMonthList.map(obj => item[obj] || 0)
			}));
			this.nowSeriesData = seriesData;
			// xAxisData = myKey.map(obj => obj.header);

			let option = {
				grid: {
				top: "3%",
				},
				xAxis:{
				type: 'category',
				data: xAxisData
				},
				yAxis:{
				type:'value',
				// name: this.unitMapper[this.pageData.energyCd],
				nameLocation : 'middle',
				nameGap :45
				},
				legend: {
				},
				series: seriesData,
				tooltip: tooltipData
			};
			await this.$nextTick(() => {
				
			});
			this.setModalChartOption(
				{ 
					prgmId: this.$route.query.prgmId,
					chartKey: this.chartName,
					modalId: this.modalId,
					modalDataKey: this.modalDataKey,
					value: option,
				}
			);
			this.loadChart = true;
			// this.setModalChartTooltip(
			// 	{
			// 		prgmId: this.$route.query.prgmId,
			// 		chartKey: this.chartName,
			// 		modalId: this.modalId,
			// 		modalDataKey: this.modalDataKey,
			// 		value: tooltipData
			// 	}
			// );
			
		},
		search() {
			// this.setChart();
			this.setSeriesData();
		},
		async setSeriesData(){
			this.loadChart = false;
			let targetMonth = this.selectValue01;
			let targetRatio = (100-this.selectValue02)/100;
			let nowSeriesData = this.nowSeriesData;
			let seriesData = [];
			let sData = [];
			let sData2 = [];			
			sData = nowSeriesData.filter(item => {
				return item.name == '전년실적';
			})[0]['data'];
			sData2 = nowSeriesData.filter(item => {
				return item.name == '계획';
			})[0]['data'];
			if(targetMonth.includes('qty')){
				targetMonth = parseInt(targetMonth.slice(-2));
			}
			for(var i=0; i<sData.length; i++){
				if(targetMonth == 'all' || i+1 == targetMonth){
					sData2[i] = sData[i] * targetRatio;
				}
			}
			seriesData = nowSeriesData.map(item => ({
				...item,
				data: item.name == '계획' ? sData2 : item.data
			}));
			
			await this.$nextTick(() => {
				
			});
			this.setModalChartSeries(
				{ 
					prgmId: this.$route.query.prgmId,
					chartKey: this.chartName,
					modalId: this.modalId,
					modalDataKey: this.modalDataKey,
					value: seriesData,
				}
			);	
			this.loadChart = true;
			this.nowSeriesData = seriesData;
		},
		numberFormatter(value) {
			return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		}
	},
};

let modifyEnrgUsePlanModalDataKey = 
{
	modifyEnrgUsePlanChart: Utility.defaultChartOption(true)
};
// 전력량 요금(원/kWh)
</script>