<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="3">
							<component :is="'SelectBlocMstr'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col :cols="3">
							<component
								:is="'SelectEnergy'"
								:parentPrgmId="myPrgmId"
								:label="'검침대상'"
							/>
						</v-col>
						<v-col :cols="3">
							<component :is="'RadioView'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col :cols="3" class="text-right">
							<BtnSearch @click="search" />
							<BtnExcelDownload
								style="vertical-align: middle;"
								class="d-inline-flex"
								:parentPrgmId="myPrgmId"
								:gridName="gridNameTree"
							/>
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="3">
							<component
								:is="'DatePicker'"
								:label="'기간'"
								:parentPrgmId="myPrgmId"
							/>
						</v-col>
						<v-col :cols="4">
							<component
								:is="'RadioCmCycle'"
								:label="'주기'"
								:parentPrgmId="myPrgmId"
								:labelCols="3"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" :eager="true">
			<v-col style="height:100%;">
				<v-card class="px-5 py-5">
					<div ref="chartParent" id="test2" style="height: 56%;">
						<component
							class="w100 h100"
							:is="loadChart ? 'Chart' : null"
							:parentPrgmId="myPrgmId"
							:chartName="chartName"
							ref="treeGridChart"
						/>
					</div>
					<div ref="treeGridParent" id="test" style="height: 44%;">
						<component
							:ref="gridNameTree"
							:is="loadTree ? 'Grid' : null"
							:gridName="gridNameTree"
							:parentPrgmId="myPrgmId"
							@getRowsData="getRowData"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import BtnSearch from '~/components/common/button/BtnSearch';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
import SelectEnergy from '@/components/common/select/SelectEnergy';
import DatePicker from '@/components/common/Datepicker';
import RadioCmCycle from '@/components/common/RadioCmCycle';
import RadioView from '@/components/common/RadioView';
import InputText from '@/components/common/input/InputText';
import Grid from '~/components/common/Grid';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Chart from '~/components/common/Chart';
import Utility from '~/plugins/utility';
import dateUtility from '~/plugins/dateUtility';

let myTitle;
//const myPrgmId = "PRG0024";
let myPrgmId;
export default {
	async asyncData(context) {
		const myState = context.store.state;
		// context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
		// myTitle = myState.activeMenuInfo.menuNm;
		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: {
		BtnSearch,
		SelectBlocMstr,
		SelectEnergy,
		DatePicker,
		RadioCmCycle,
		RadioView,
		InputText,
		Grid,
		Chart,
		BtnExcelDownload,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadTree: false,
			loadChart: false,
			gridNameTree: 'treeGrid',
			chartName: 'treeGridChart',
			defaultRowKey: 1,
			selRowKey: null,
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkViewCheck() {
			return this.pageData.viewCheck;
		},
		chkBlocCd() {
			// 사업장 코드
			return this.pageData.blocId;
		},
		chkCmCycle() {
			return this.pageData.cmCycle;
		},
		chkEnergyCd() {
			// 에너지 선택 여부 감지
			return this.pageData.energyCd;
		},
		selectedCommCdData() {
			return this.pageData.selectedCommCdData;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkBlocCd() {
			this.setPageData({ isFind: true });
		},
		chkViewCheck() {
			this.setView(this.pageData.viewCheck);
		},
		chkEnergyCd() {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setChartOption: 'setChartOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		init() {
			this.layoutInit();

			this.gridInit();
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		gridInit() {
			const treeGridHeight = this.$refs.treeGridParent.offsetHeight - 36;

			const myOptionsTree = {
				treeColumnOptions: {
					name: 'readPlcNm',
				},
				columnOptions: {
					//frozenCount : 1,
					minWidth: 100,
					resizable: true,
				},
				scrollX: true,
			};

			this.setGridOption({
				gridKey: this.gridNameTree,
				// value: myOptionsTree
				value: Object.assign(
					Utility.defaultGridOption(treeGridHeight),
					myOptionsTree,
				),
			});

			this.getTreeData();
		},
		//메뉴 리스트
		async getTreeData() {
			this.loadTree = false;

			if (
				this.pageData.energyList.length > 0 &&
				this.pageData.blocMstrList.length > 0
			) {
				const res = await this.postApiReturn({
					apiKey: 'selectReadResultRet',
					resKey: 'readPlcData',
					// sendParm : sendParams
					sendParam: {
						sh_readObjId: this.pageData.energyList[this.chkEnergyCd].cd,
						// sh_mttTp: "MTT00001",
						sh_searchType:
							this.pageData.cmCycle == 'CYC_YEAR'
								? 'month'
								: this.pageData.cmCycle == 'CYC_MONTH'
								? 'day'
								: 'time',
						sh_date:
							this.pageData.cmCycle == 'CYC_YEAR'
								? this.pageData.fromDt
								: this.pageData.cmCycle == 'CYC_MONTH'
								? Utility.setFormatDate(this.pageData.fromDt, 'YYYY/MM')
								: Utility.setFormatDate(this.pageData.fromDt, 'YYYY/MM/DD'),
						// sh_blocCd:"BL0001"
						sh_blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId,
					},
				});

				let columnList = [
					{
						header: '개소',
						name: 'readPlcNm',
						width: 300,
					},
					{
						header: 'readPlc',
						name: 'readPlc',
						hidden: true,
					},
					{
						header: 'upReadPlc',
						name: 'upReadPlc',
						hidden: true,
					},
				];
				switch (this.pageData.cmCycle) {
					case 'CYC_YEAR':
						for (var i = 1; i < 13; i++) {
							var tempObj = {
								header:
									Utility.setFormatDate(this.pageData.fromDt, 'YYYY') +
									'/' +
									String(i).padStart(2, '0'),
								name: 'qty' + String(i - 1).padStart(2, '0'),
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
								align: 'right',
								excelType: 'number',
								excelFormatter: '2',
							};
							columnList.push(tempObj);
						}
						break;
					case 'CYC_MONTH':
						for (
							var i = 1;
							i <= dateUtility.getLastDay('D', this.pageData.fromDt);
							i++
						) {
							var tempObj = {
								header:
									Utility.setFormatDate(this.pageData.fromDt, 'MM') +
									'/' +
									String(i).padStart(2, '0'),
								name: 'qty' + String(i - 1).padStart(2, '0'),
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
								align: 'right',
								excelType: 'number',
								excelFormatter: '2',
							};
							columnList.push(tempObj);
						}
						break;
					case 'CYC_DAY':
						for (var i = 0; i < 24; i++) {
							var tempObj = {
								header: String(i).padStart(1, '0') + '시',
								name: 'qty' + String(i).padStart(2, '0'),
								formatter({ value }) {
									return Utility.setFormatIntDecimal(value, 2);
								},
								align: 'right',
								excelType: 'number',
								excelFormatter: '2',
							};
							columnList.push(tempObj);
						}
						break;
				}
				this.setGridColumn({
					gridKey: this.gridNameTree,
					value: columnList,
				});

				const setTreeData = await this.setTree({
					gridKey: this.gridNameTree,
					treeKey: 'READ_PLC',
					isId: true,
					value: res.map(item => ({
						...item,
						readPlc: item.readPlcId,
					})),
				});
				this.xlsDataBind(res);
				await this.setGridData({
					gridKey: this.gridNameTree,
					value: setTreeData.ROOT,
				});

				// setTreeData["ROOT"][0]['_attributes'] = {expanded : true};
				// this.$refs["treeGrid"].expandAll();
				this.loadTree = true;

				this.$nextTick(() => {
					if (setTreeData != null) {
						this.$refs[this.gridNameTree].focus({
							// rowKey: this.chkRowGridSelectKey || 0,
							rowKey:
								this.selRowKey != null ? this.selRowKey : this.defaultRowKey,
							setScroll: true,
						});
					}
				});

				this.setChartData([]);
				this.loadChart = true;
			}
		},
		async setChartData(data) {
			let xAxisData = [];
			let seriesData = [];
			let tmpList = [];
			let series = {};
			let exceptionColumList = ['개소', 'readPlc', 'upReadPlc'];

			const myKey = this.pageData[this.gridNameTree].column.filter(v => {
				return !exceptionColumList.includes(v.header);
			});
			tmpList = Object.values(data);
			tmpList.shift();
			series.name = tmpList.shift();
			series.type = 'bar';
			series.data = tmpList;

			xAxisData = myKey.map(obj => obj.header);

			seriesData.push(series);
			var option = {
				xAxis: {
					data: xAxisData,
				},
				yAxis: {
					type: 'value',
					name: this.pageData.energyList[this.pageData.energyCd].unit,
					nameLocation: 'middle',
					nameGap: 40,
				},
				legend: {
					xtStyle: {
						color: '#95A0A9',
						fontSize: 10,
					},
				},
				series: seriesData,
			};

			this.setChartOption({ chartKey: this.chartName, value: option });
		},
		async getRowData(data) {
			this.loadChart = false;
			this.selRowKey = data.rowKey;
			let length =
				this.pageData.cmCycle == 'CYC_YEAR'
					? 12
					: this.pageData.cmCycle == 'CYC_MONTH'
					? 31
					: 24;
			var pageDataObj = {
				readPlc: data.readPlc,
				readPlcNm: data.readPlcNm,
			};
			for (var i = 0; i < length; i++) {
				if (data['qty' + String(i).padStart(2, '0')] == null) {
					data['qty' + String(i).padStart(2, '0')] = 0;
				}
				pageDataObj['qty' + String(i).padStart(2, '0')] =
					data['qty' + String(i).padStart(2, '0')];
			}

			this.setChartData(pageDataObj);
			this.loadChart = true;
		},
		async setView(value) {
			switch (value) {
				case 'viewAll':
					this.loadTree = false;
					this.loadChart = false;
					this.$refs.treeGridParent.style.height = '44%';
					this.$refs.chartParent.style.height = '56%';
					this.gridInit();
					this.loadChart = true;

					break;

				case 'viewGrid':
					this.loadChart = false;
					this.$refs.chartParent.style.height = '0%';
					this.$refs.treeGridParent.style.height = '100%';
					this.gridInit();

					break;
				case 'viewChart':
					this.loadTree = false;
					this.loadChart = true;
					this.$refs.chartParent.style.height = '100%';
					this.$refs.treeGridParent.style.height = '0%';
					break;
			}
			this.isFind = true;
		},
		async search() {
			await this.getTreeData();
			await this.setPageData({
				isFind: false,
			});
		},
		xlsDataBind(res) {
			const xlsRowData = res.map(item => {
				const obj = {
					...item,
					useFg: item.useFg == '1' ? '사용' : '사용안함',
					prgmTpCd: item.prgmTpCd == '1' ? '프로그램' : '팝업',
				};
				return obj;
			});
			this.setPageData({
				xlsFileInfo: {
					[this.gridNameTree]: {
						rowData: xlsRowData,
					},
				},
			});
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	readPlc: '',
	energyCd: 'MTT00001',
	energyList: [],
	blocId: null,
	blocMstrList: [],
	defaultRange: {
		CYC_YEAR: 0,
		CYC_MONTH: 0,
		CYC_DAY: 0,
	},
	cmCycle: 'CYC_DAY',
	viewCheck: 'viewAll',
	fromDt: Utility.setFormatDate(new Date(), 'YYYYMMDD'), // 조회 시작일
	// cmCycleList:[],
	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정
	/* data 세팅 */
	treeGrid: {
		data: [],
		column: [],
		option: {},
	},
	/*chartdata 세팅 */
	treeGridChart: Utility.defaultChartOption(true),

	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		treeGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};
</script>
<style lang="scss">
@import '@/assets/scss/common.scss';
</style>
//
<style scoped lang="scss">
//   ::v-deep {
//     .tui-grid {
//         &-row-odd,
//         &-row-even {
//           .tui-grid-cell {
//             .tui-grid-tree-depth i {
//               width: 10px !important;
//               height: 6px !important;
//               background: url("@/assets/images/ico_grid_open.png")
//                 no-repeat
//                 center /
//                 100%
//                 auto !important;
//             }

//             &.tui-grid-cell-has-tree {
//               .tui-grid-tree-extra-content + .tui-grid-cell-content {
//                 position: relative;
//                 &:before {
//                   content: "";
//                   width: 10px !important;
//                   height: 8px !important;
//                   display: inline-block;
//                   margin-right: 6px;
//                   background: url("@/assets/images/ico_grid_list.png")
//                     no-repeat
//                     center /
//                     100%
//                     auto !important;
//                   vertical-align: middle;
//                 }

//               }

//               [class*="tui-grid-tree-button-"] + .tui-grid-cell-content {
//                 &:before {
//                   content: none;
//                 }
//               }
//             }
//           }

//           &:hover {
//             .tui-grid-cell {
//               background-color: #1a4e87;

//               .tui-grid-tree-depth i {
//                 background-image: url("@/assets/images/ico_grid_open_active.png") !important;
//               }

//               .tui-grid-cell-content {
//                 color: map-deep-get($config, "dark", "activate");
//                 &:before {
//                   background-image: url("@/assets/images/ico_grid_list_active.png") !important;
//                 }
//               }
//             }
//           }
//         }

//         &-cell-current-row {
//           .tui-grid-cell {
//             .tui-grid-tree-depth i {
//               background-image: url("@/assets/images/ico_grid_open_active.png") !important;
//             }

//             .tui-grid-cell-content {
//               color: map-deep-get($config, "dark", "activate");
//               &:before {
//                 background-image: url("@/assets/images/ico_grid_list_active.png") !important;
//               }
//             }
//           }
//         }
//     }
//   }
//
</style>
