<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="4">
							<component
								:is="'SelectBlocMstr'"
								ref="SelectBlocMstr"
								:parentPrgmId="myPrgmId"
								:labelCols="4"
								:textCols="7"
							/>
						</v-col>
						<v-col :cols="4">
							<DatePicker
								:parentPrgmId="myPrgmId"
								label="조회기간"
								:labelCols="4"
								:textCols="7"
							/>
						</v-col>
						<v-col cols="4" class="d-flex justify-end align-center">
							<BtnSearch @click="search" class="mr-1" />
							<BtnExcelDownload :parentPrgmId="myPrgmId" :gridName="gridName" />
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="4">
							<component
								:is="'FtnPlcMultiPop'"
								:parentPrgmId="myPrgmId"
								:labelCols="4"
								:textCols="7"
							/>
						</v-col>
						<v-col :cols="4" hidden>
							<component
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
								:label="'에너지'"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col style="height: 100%">
				<v-card class="pa-5">
					<div ref="chartParent" style="height: 40vh">
						<component
							class="w100 h100"
							:is="loadChart ? 'Chart' : null"
							:parentPrgmId="myPrgmId"
							:chartName="'rowGridChart'"
							ref="rowGridChart"
						/>
					</div>
					<div style="height: 30px"></div>
					<div ref="gridParent" class="pd-2" style="height: 20vh">
						<component
							:is="loadGrid ? 'Grid' : null"
							:gridName="gridName"
							:parentPrgmId="myPrgmId"
							ref="rowGrid"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstrForPop';
import SelectEnergy from '@/components/common/select/SelectEnergyForPop';
import DatePicker from '~/components/common/Datepicker';
import FtnPlcMultiPop from '~/components/common/modal/FtnPlcMultiPop2';
import BtnSearch from '~/components/common/button/BtnSearch';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Utility from '~/plugins/utility';
import Grid from '~/components/common/Grid';
import Chart from '~/components/common/Chart';

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,
		DatePicker,
		FtnPlcMultiPop,
		BtnSearch,
		BtnExcelDownload,
		Utility,
		Grid,
		Chart,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			loadChart: false,
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			return this.pageData.isFind;
		},
		chkFacInfo() {
			return this.pageData.facInfo;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkFacInfo() {
			this.setPageData({ isFind: true });
		},
	},
	beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartXAxisData: 'setChartXAxisData',
			setChartYAxisData: 'setChartYAxisData',
			setChartSeries: 'setChartSeries',
			setChartOption: 'setChartOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			chkOpenTabList: 'chkOpenTabList',
		}),
		async init() {
			await this.makeGrid();
		},
		async search() {
			await this.makeGrid();
		},
		async makeGrid() {
			this.loadGrid = false;
			const gridHeight = this.$refs.gridParent.offsetHeight - 36;

			const myOptions = {
				scrollX: false,
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			var res = await this.makeResponse();
			var columnList = [
				{ header: '회사번호', name: 'comId', align: 'center', hidden: true },
				{ header: 'no', name: 'no', align: 'center' },
				{ header: '일자', name: 'totDttm', align: 'center' },
				{
					header: '경부하',
					name: 'minQty',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '경부하-비율(%)',
					name: 'minRto',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '중부하',
					name: 'midQty',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '중부하-비율(%)',
					name: 'midRto',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '최대부하',
					name: 'maxQty',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '최대부하-비율(%)',
					name: 'maxRto',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '총사용량',
					name: 'totQty',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '비용',
					name: 'cost',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
			];

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

			this.setGridData({
				gridKey: this.gridName,
				value: res,
			});

			await this.makeChart(res);
			this.loadGrid = true;
			this.setPageData({ isFind: false });
		},
		async makeChart(data) {
			this.$store.state.pageData[this.myPrgmId].rowGridChart.series = [];
			this.loadChart = false;

			// if(!data.length){
			//   return;
			// }
			var xAxisData = [];
			var seriesData = [];

			var xAxisData = data.map(el => el.totDttm.substring(5, 10));

			seriesData.push({
				name: '경부하',
				type: 'bar',
				stack: 'stack1',
				data: data.map(el => el.minQty),
				yAxisIndex: 0,
			});

			seriesData.push({
				name: '중부하',
				type: 'bar',
				stack: 'stack1',
				data: data.map(el => el.midQty),
				yAxisIndex: 0,
			});

			seriesData.push({
				name: '최대부하',
				type: 'bar',
				stack: 'stack1',
				data: data.map(el => el.maxQty),
				yAxisIndex: 0,
			});

			seriesData.push({
				name: '비용',
				type: 'line',
				data: data.map(el => el.cost),
				yAxisIndex: 1,
			});

			var chartOption = {
				grid: {
					top: '3%',
				},
				yAxis: [
					{
						type: 'value',
						name: 'kwh',
						position: 'left',
						axisLine: {
							show: true,
						},
					},
					{
						type: 'value',
						name: '원',
						position: 'right',
						axisLine: {
							show: true,
						},
					},
				],
				xAxis: {
					type: 'category',
					data: xAxisData,
				},
				series: seriesData,
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'cross',
					},
				},
			};

			this.setChartOption({ chartKey: 'rowGridChart', value: chartOption });
			this.setChartYAxisData({
				chartKey: 'rowGridChart',
				value: [
					{
						type: 'value',
						name: 'kwh',
						position: 'left',
						axisLine: {
							show: false,
						},
						nameLocation: 'middle',
						nameGap: 50,
						splitLine: {
							show: true,
						},
					},
					{
						type: 'value',
						name: '원',
						position: 'right',
						axisLine: {
							show: false,
						},
						nameLocation: 'middle',
						nameGap: 70,
						splitLine: {
							show: true,
						},
					},
				],
			});

			this.loadChart = true;
		},
		makeSendParam() {
			var param = {
				fromDt:
					this.pageData.fromDt.substring(0, 4) +
					'-' +
					this.pageData.fromDt.substring(4, 6) +
					'-' +
					this.pageData.fromDt.substring(6, 8),
				toDt:
					this.pageData.toDt.substring(0, 4) +
					'-' +
					this.pageData.toDt.substring(4, 6) +
					'-' +
					this.pageData.toDt.substring(6, 8),
				eccId: this.pageData.facInfo.eccId,
			};
			return param;
		},
		async makeResponse() {
			var resultColumnList = [
				'comId',
				'cost',
				'maxQty',
				'maxRto',
				'midQty',
				'midRto',
				'minQty',
				'minRto',
				'totDttm',
				'totQty',
			];

			var res = await this.postApiReturn({
				apiKey: 'selectLoadElecPowCmpr',
				resKey: 'loadElecPowCmpr',
				sendParam: this.makeSendParam(),
			});

			if (!res.length || res.length < 1) {
				return res;
			}

			for (var i = 0; i < res.length; i++) {
				res[i]['totDttm'] = res[i]['totDttm'].replaceAll('-', '/');
			}

			var fromDt = new Date(
				this.pageData.fromDt.substring(0, 4),
				this.pageData.fromDt.substring(4, 6),
				this.pageData.fromDt.substring(6, 8),
			);
			var toDt = new Date(
				this.pageData.toDt.substring(0, 4),
				this.pageData.toDt.substring(4, 6),
				this.pageData.toDt.substring(6, 8),
			);
			var diffDay = (toDt.getTime() - fromDt.getTime()) / (1000 * 60 * 60 * 24);

			for (var i = 0; i < diffDay + 1; i++) {
				var tempDt = new Date(
					this.pageData.fromDt.substring(0, 4),
					this.pageData.fromDt.substring(4, 6) - 1,
					this.pageData.fromDt.substring(6, 8),
				);
				tempDt.setDate(tempDt.getDate() + i);
				tempDt =
					tempDt.getFullYear() +
					'/' +
					(tempDt.getMonth() + 1).toString().padStart(2, '0') +
					'/' +
					tempDt
						.getDate()
						.toString()
						.padStart(2, '0');

				if (res[i] == undefined || res[i]['totDttm'] != tempDt) {
					res.splice(i, 0, {
						totDttm: tempDt,
						comId: '',
						cost: 0,
						totQty: 0,
						maxQty: 0,
						maxRto: 0,
						midQty: 0,
						midRto: 0,
						minQty: 0,
						minRto: 0,
					});
				}
			}

			for (var i = 0; i < res.length; i++) {
				for (var j = 0; j < resultColumnList.length; j++) {
					res[i]['no'] = i + 1;
					if (res[i][resultColumnList[j]] === undefined) {
						res[i][resultColumnList[j]] = 0;
					}
				}
			}

			return res;
		},
	},
};

var dt1 = new Date();
var dt2 = new Date(dt1.setMonth(dt1.getMonth() - 1));

const defaultData = {
	isFind: false,

	blocId: '',
	blocMstrList: [],
	energyCd: '',
	energyList: [],

	cmCycle: 'CYC_DAY',
	cmCycleList: [
		{ idx: 0, text: '연', value: 'CYC_YEAR' },
		{ idx: 1, text: '월', value: 'CYC_MONTH' },
		{ idx: 2, text: '일', value: 'CYC_DAY' },
		{ idx: 3, text: '시간', value: 'CYC_HOUR' },
	],
	defaultRange: {
		CYC_YEAR: 10,
		CYC_MONTH: 12,
		CYC_DAY: 30,
		CYC_HOUR: 0,
	},
	fromDt: Utility.setFormatDate(dt2, 'YYYYMMDD'),
	toDt: Utility.setFormatDate(new Date(), 'YYYYMMDD'),

	isMulti: false,
	modalData: {},
	facInfo: {},

	rowGrid: {
		data: [],
		option: {},
		column: [],
	},

	rowGridChart: Utility.defaultChartOption(true),

	xlsFileInfo: {
		rowGrid: {
			fileName: null,
			sheetName: null,
		},
	},
};

function numberFormatter({ value }) {
	return Utility.setFormatIntDecimal(value, 2);
}
</script>
<style lang="scss">
@import '@/assets/scss/common.scss';
</style>
