<template>
	<div class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row>
						<v-col :cols="8" style="padding:0px">
							<!-- 조회기간 -->
							<DatePicker :parentPrgmId="parentPrgmId" label="조회기간" customClass="tab-datepicker" />
						</v-col>
						<v-col cols="4" class="d-flex justify-end align-center">
							<Buttons
							style="margin-top: 25px;"
								:parentPrgmId="parentPrgmId"
								:bindingData="gridName"
								:btnActionsFnc="btnActions"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<!-- Create the line between date picker and form -->
		<v-row class="mt-6 mb-7" no-gutters>
			<v-col>
				<div style="height: 1px; background-color: #0000000F;"></div>
			</v-col>
		</v-row>
		<v-row class="search-box" align="center" no-gutters style="height: 44px;">
			<v-col :cols="4">
				<label for="" class="search-box-label">
					<v-icon
					small
					:class="['mr-1','icon-blue']"
					>$icoBulletPoint</v-icon
					>
					월별 요금 정보
				</label>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12">
				<div
					ref="gridParent"
					class="w100"
					style="height: calc((100vh - 500px) / 2);"
				>
					<Grid
						:ref="gridName"
						:is="loadGrid ? 'Grid' : null"
						:gridName="gridName"
						:parentPrgmId="parentPrgmId"
						:editorGrid="true"
						:innerTabGridInfo="innerTabGridInfo"
						@getRowsData="getRowData"
					/>
				</div>
			</v-col>
		</v-row>
		<v-row class="search-box mt-2" align="center" no-gutters style="height: 44px;">
			<v-col :cols="4">
				<label for="" class="search-box-label">
					<!-- <v-icon x-small color="primary" class="mr-1"
						>mdi-record-circle</v-icon
					> -->
					<v-icon
					small
					:class="['mr-1','icon-blue']"
					>$icoBulletPoint</v-icon
					>
					월별 요금 정보
				</label>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12">
				<div
					ref="chartParent"
					class="h100 w100"
					style="height: calc((100vh - 500px) / 2);"
				>
					<component
						class="w100 h100"
						:is="loadChart ? 'Chart' : null"
						:parentPrgmId="parentPrgmId"
						:chartName="chartName"
					/>
				</div>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Buttons from '~/components/common/button/Buttons';
import BtnSearch from '~/components/common/button/BtnSearch';
import Utility from '~/plugins/utility';
import Grid from '~/components/common/Grid';
import Chart from '~/components/common/Chart';
import DatePicker from '~/components/common/Datepicker';
import SelectDate from '~/components/common/select/SelectDate';
import SelectDateVc from '~/components/common/select/SelectDateVc';
import Label from '~/components/common/form/Label';

export default {
	components: {
		Buttons,
		BtnSearch,
		Grid,
		Chart,
		DatePicker,
		SelectDate,
		SelectDateVc,
		Utility,
		Label,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: false,
			loadChart: false,
			gridName: 'rowDetailGrid',
			chartName: 'rowGridChart',
			rowKey: null,
			edtingFinishFlag: 'Y',
		};
	},
	computed: {
		...mapState({
			pageData(state) {
				return state.pageData[this.parentPrgmId];
			},
		}),
		swichDatePicker() {
			let picker = 'SelectDateVc';
			if (this.pageData.cmCycle == 'CYC_MONTH') {
				picker = 'SelectDate';
			}
			return picker;
		},
		chkRowdata() {
			return this.pageData[this.gridName].data;
		},
		chkLoadGrid() {
			return this.loadGrid;
		},
	},
	watch: {
		chkRowdata(val) {
			// console.log("chkRowdata", val);
			this.setChartData(val);
		},
		chkLoadGrid() {
			if (this.pageData[this.gridName].data > 0) {
				this.setChartData(this.pageData[this.gridName].data);
			}
		},
	},
	mounted() {
		this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartYAxisData: 'setChartYAxisData',
			setChartXAxisData: 'setChartXAxisData',
			setChartSeries: 'setChartSeries',
			setChartOption: 'setChartOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		init() {
			this.gridInit();
			this.setChartData(this.pageData[this.gridName].data);
		},
		numFormat(val) {
			return val.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 50;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				bodyHeight: gridHeight,
				minBodyHeight: gridHeight,
				header: {
					height: 38,
				},
				rowHeight: 37,
				minRowHeight: 37,
				selectionUnit: 'row',
				editingEvent: 'click',
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: myOptions,
			});

			const _this = this;
			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '에너지원 번호', name: 'ercId', hidden: true },
				{ header: '대상월', name: 'objMm', align: 'right', hidden: true },
				{ header: '대상 월', name: 'objYm', width: 100, align: 'center' },
				{
					header: '요금 단가',
					name: 'unitPrce',
					width: 100,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
				},
				{
					header: '피크 전력',
					name: 'peakPow',
					width: 100,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
				},
				{
					header: '기본 요금',
					name: 'baseChrg',
					width: 100,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
				},
				{
					header: '고지 요금',
					name: 'notiChrg',
					width: 100,
					align: 'right',
					editor: 'text',
					formatter: numberFormatter,
				},
				{
					header: '비고',
					name: 'rmrk',
					align: 'left',
					editor: 'text',
				},
				{
					header: '사업장',
					name: 'blocId',
					width: 100,
					align: 'center',
					hidden: true,
				},
				{ header: '등록 사용자', name: 'regUserNo', hidden: true },
				{ header: '등록 일자', name: 'regDttm', hidden: true },
				{ header: '수정 사용자', name: 'procUserNo', hidden: true },
				{ header: '수정 일자', name: 'procDttm', hidden: true },
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			this.loadGrid = true;
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					this.edtingFinishFlag = 'Y';
					break;

				case 'remove':
					await this.$refs[this.gridName].editingFinish({
						rowKey: this.rowKey,
					});
					this.$refs[this.gridName].removeRow();
					this.edtingFinishFlag = 'N';
					break;

				case 'save':
					if (this.edtingFinishFlag == 'Y') {
						await this.$refs[this.gridName].editingFinish({
							rowKey: this.rowKey,
						});
					}
					dataArr = this.$refs[this.gridName].save();
					this.setPageData({ isFind: true });
					if (dataArr.length > 0) {
						const sendParam = {
							datas: {
								dsEnrgChrgInfo: dataArr.map(item => ({
									...item,
									comId: this.selectedComId,
									tagId: this.selectedTagId,
								})),
							},
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveEnrgChrgPrcInfo',
							sendParam: sendParam,
						});
						this.setPageData({ isFind: true });
						this.edtingFinishFlag = 'Y';
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		async getRowData(data) {
			this.rowKey = data.rowKey;
			this.edtingFinishFlag = 'Y';
		},

		async setChartData(data) {
			// console.log("차트 옵션 세팅");
			let xAxisData = [];
			let seriesData = [];
			let seriesDataBaseChrg = {
				name: '기본요금',
				type: 'line',
				stack: 'Total',
				data: [],
			};
			let seriesDataNotiChrg = {
				name: '고지요금',
				type: 'line',
				stack: 'Total',
				data: [],
			};

			for (let idx in data) {
				xAxisData.push(data[idx].objYm);
				if (data[idx].baseChrg == null || data[idx].baseChrg == '') {
					seriesDataBaseChrg.data.push(0);
				} else {
					seriesDataBaseChrg.data.push(data[idx].baseChrg);
				}
				if (data[idx].notiChrg == null || data[idx].notiChrg == '') {
					seriesDataNotiChrg.data.push(0);
				} else {
					seriesDataNotiChrg.data.push(data[idx].notiChrg);
				}
			}
			seriesData.push(seriesDataBaseChrg);
			seriesData.push(seriesDataNotiChrg);

			this.setChartXAxisData({ chartKey: this.chartName, value: xAxisData });
			this.setChartSeries({ chartKey: this.chartName, value: seriesData });
			this.loadChart = true;
		},
	},
};

function numberFormatter({ value }) {
	return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
</script>
<style lang="scss" scoped>
	::v-deep {
		.tab-datepicker {
			width: 64% !important;
		}

		.tui-grid-layer-state {
			top: 40px !important;
		}

		.tui-grid-layer-selection,
		.tui-grid-cell-content-editor{
			height: 36px !important;
			// border: none;
		}
	}
</style>