<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">
							<v-row class="search-box" align="center" no-gutters>
								<v-col :cols="4">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>
										사업장
									</label>
								</v-col>
								<v-col :cols="7">
									<v-select
										v-model="blocId"
										:items="blocMstrList"
										item-text="blocNm"
										item-value="blocId"
										solo
										outlined
										:hide-details="true"
										append-icon="mdi-chevron-down"
										class="v-select__custom"
									></v-select>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3">
							<v-row class="search-box" align="center" no-gutters>
								<v-col :cols="4">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>
										검침대상유형
									</label>
								</v-col>
								<v-col :cols="7">
									<v-select
										v-model="roiGrpCode"
										:items="roiGrpCodeList"
										item-text="commCdNm"
										item-value="commCd"
										solo
										outlined
										:hide-details="true"
										append-icon="mdi-chevron-down"
										class="v-select__custom"
									></v-select>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3">
							<v-row class="search-box" align="center" no-gutters>
								<v-col :cols="4">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>
										검침대상
									</label>
								</v-col>
								<v-col :cols="7">
									<v-select
										v-model="mttCd"
										:items="mttCdList"
										item-text="mttNm"
										item-value="mttCd"
										solo
										outlined
										:hide-details="true"
										append-icon="mdi-chevron-down"
										class="v-select__custom"
									></v-select>
								</v-col>
							</v-row>
						</v-col>
						<v-col :cols="3" class="text-right">
							<v-btn :ripple="false" class="mr-1" @click="searchGrid2()"
								>조회</v-btn
							>
							<BtnExcelDownload
								class="mr-1"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
							/>
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="3">
							<component
								ref="fromPicker"
								:is="'Datepicker'"
								:parentPrgmId="myPrgmId"
								:label="'조회기간'"
							/>
						</v-col>
						<v-col :cols="4">
							<v-row class="search-box" align="center" no-gutters>
								<v-col :cols="3">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>정시만조회</label
									>
								</v-col>
								<v-col :cols="1">
									<v-checkbox
										v-model="timeChkValue"
										:color="isDarkMode ? '#fff' : '#4777d9'"
									></v-checkbox>
								</v-col>
							</v-row>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="3">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-5">
						<v-card-title class="pa-0 custom-title-4"
							>검침개소 리스트</v-card-title
						>
						<div>
							<v-btn :ripple="false" icon tile @click="btnTreeExpand()">
								<v-icon
									size="30"
									v-text="treeExpandAll ? 'mdi-chevron-up' : 'mdi-chevron-down'"
								></v-icon>
							</v-btn>
						</div>
					</div>
					<div style="height:calc(100% - 76px)" class="px-5">
						<div ref="treeGridParent" class="w100 h100">
							<component
								:ref="gridNameTree + myPrgmId"
								:is="loadTree ? 'Grid' : null"
								:gridName="gridNameTree"
								:parentPrgmId="myPrgmId"
								@getRowsData="getRowData"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
			<v-col :cols="9">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-5">
						<v-card-title class="pa-0 custom-title-4"
							>시간별검침정보</v-card-title
						>
						<div class="d-flex align-center">
							<v-select
								v-model="tagId"
								:items="tagIdList"
								item-text="tagNm"
								item-value="tagId"
								solo
								append-icon="mdi-chevron-down"
								class="v-select__custom"
								outlined
								hide-details
							></v-select>
							<v-col :cols="1"> </v-col>
							<Buttons
								:parentPrgmId="myPrgmId"
								:bindingData="gridName"
								:btnActionsFnc="btnActions"
							/>
						</div>
					</div>
					<div style="height:calc(100% - 76px)" class="px-5">
						<div ref="gridParent" class="w100 h100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								:editorGrid="true"
								@updateDataInfo="evtUpdateDataInfo"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import Utility from '~/plugins/utility';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
import Datepicker from '~/components/common/Datepicker';
import Grid from '~/components/common/Grid';
import Buttons from '~/components/common/button/Buttons';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';

let myTitle;
//const myPrgmId = "PRG0017";
let myPrgmId;
export default {
	mixins: [mixinGlobal],
	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: {
		SelectBlocMstr,
		Datepicker,
		Grid,
		Buttons,
		BtnExcelDownload,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			createdFlag: false,
			roiGrpCode: '',
			roiGrpCodeList: [],
			mttCd: '',
			mttCdList: [],
			blocId: '',
			blocMstrList: [],
			selectedRoiId: null,
			tagId: '',
			tagIdList: [],
			timeChkValue: false,
			treeExpandAll: true,
			loadTree: false,
			gridNameTree: 'treeGrid',
			loadGrid: false,
			gridName: 'rowGrid',
			searchFlag: false,
			selectedData: null,
		};
	},
	computed: {
		...mapState({
			isDarkMode: state => state.isDarkMode,
			pageData: state => state.pageData[myPrgmId],
		}),
		chkFromDt() {
			// console.log("this", this.pageData)
			return this.pageData.fromDt;
		},
	},
	watch: {
		async createdFlag(val) {
			if (val === true) {
				await this.init();
			}
		},
		async searchFlag(val) {
			if (val === true) {
				await this.search();
			}
		},
		async chkFromDt() {
			await this.searchGrid2();
		},
		blocId() {
			if (this.createdFlag === true) {
				this.searchFlag = true;
			}
		},
		mttCd(val) {
			if (this.createdFlag === true) {
				this.searchFlag = true;
			}
		},
		tagId(val) {
			if (this.createdFlag === true) {
				for (var i = 0; i < this.tagIdList.length; i++) {
					if (this.tagIdList[i]['tagId'] == this.tagId) {
						this.selectedRoiId = this.tagIdList[i]['readObjId'];
					}
				}
				this.setRowGridData();
			}
		},
		async roiGrpCode(val) {
			var idx = 0;
			for (var i = 0; i < this.roiGrpCodeList.length; i++) {
				if (this.roiGrpCodeList[i]['commCd'] == this.roiGrpCode) {
					idx = i;
					break;
				}
			}
			this.mttCdList = await this.postApiReturn({
				apiKey: 'selectMtt',
				resKey: 'mttData',
				sendParam: {
					mttTp: this.roiGrpCodeList[idx]['commCd'],
					mttGrp: this.roiGrpCodeList[idx]['userDefVal1'],
				},
			});
			if (this.mttCdList.length > 0) {
				this.mttCd = this.mttCdList[0]['mttCd'];
			}
		},
		async timeChkValue(val) {
			await this.searchGrid2();
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	async created() {
		this.blocMstrList = await this.postApiReturn({
			apiKey: 'selectBlocMstrCodeList',
			resKey: 'blocCodeLists',
			sendParam: {},
		});
		this.blocId = this.blocMstrList[0]['blocId'];
		this.roiGrpCodeList = await this.postApiReturn({
			apiKey: 'selectCodeList',
			resKey: 'codeLists',
			sendParam: {
				commGrpCd: 'CM_MTTTP',
				useFg: '1',
			},
		});
		this.roiGrpCode = this.roiGrpCodeList[0]['commCd'];
		this.mttCdList = await this.postApiReturn({
			apiKey: 'selectMtt',
			resKey: 'mttData',
			sendParam: {
				mttTp: this.roiGrpCodeList[0]['commCd'],
				mttGrp: this.roiGrpCodeList[0]['userDefVal1'],
			},
		});
		this.mttCd = this.mttCdList[0]['mttCd'];
		this.createdFlag = true;
	},
	async mounted() {
		// await this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
		}),
		...mapActions({
			getCodeList: 'modules/search/getCodeList',
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
		}),
		async init() {
			this.gridInit();
			await this.getTreeData();
		},
		async search() {
			await this.getTreeData();
			this.searchFlag = false;
		},
		async searchGrid2() {
			await this.setRowGridData();
		},
		gridInit() {
			const treeGridHeight = this.$refs.treeGridParent.offsetHeight - 35;
			const gridHeight = this.$refs.gridParent.offsetHeight - 45;

			const myOptionsTree = {
				treeColumnOptions: {
					name: 'readPlcNm',
				},
				scrollX: false,
			};

			const myOptions = {};

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

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

			var columnList = [
				{
					header: 'TAG 명',
					name: 'tagNm',
					aling: 'center',
					width: 450,
				},
				{
					header: '검침일자',
					name: 'readDt',
					align: 'center',
					formatter({ value }) {
						return Utility.setFormatDate(value, 'YYYY-MM-DD');
					},
				},
				{
					header: '검침시간',
					name: 'readTm',
					align: 'center',
				},
				{
					header: '검침값',
					name: 'readVal',
					align: 'right',
					editor: 'text',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '배율(%)',
					name: 'mgnf',
					align: 'center',
				},
				{
					header: '값(검침값*배율)',
					name: 'readValMgnf',
					align: 'right',
					excelType: 'number',
					excelFormatter: '2',
					formatter: numberFormatter,
				},
				{
					header: '단위',
					name: 'unit',
					align: 'center',
				},
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: columnList,
			});
		},
		async getTreeData() {
			this.loadTree = false;
			if (this.blocMstrList.length > 0) {
				const res = await this.postApiReturn({
					apiKey: 'selectReadPlc',
					resKey: 'readPlacereg',
					sendParam: {
						blocId: this.blocId,
						fromObjDt: Utility.setFormatDate(
							this.pageData.fromDt,
							'YYYY-MM-DD',
						),
						readObjKind: this.roiGrpCode,
						readObjId: this.mttCd,
					},
				});

				if (res.length === 0) {
					this.tagId = '';
					this.tagIdList = [];
					this.selectedRoiId = null;
				}

				this.setGridColumn({
					gridKey: this.gridNameTree,
					value: [
						{
							header: '개소',
							name: 'readPlcNm',
						},
					],
				});

				const setTreeData = await this.setTree({
					treeKey: 'READ_PLC_ID',
					value: res,
				});

				await this.setGridData({
					gridKey: this.gridNameTree,
					value: setTreeData.ROOT,
				});

				this.loadTree = true;

				// gridData 초기화하는 부분
				if (
					this.$store.state.pageData[this.myPrgmId].treeGrid.data === undefined
				) {
					this.setGridData({
						gridKey: this.gridName,
						value: [],
					});
				}

				this.$nextTick(() => {
					this.$refs[this.gridNameTree + this.myPrgmId].focus({
						rowKey: 0,
						columnName: 'readPlcNm',
						setScroll: true,
					});
				});

				if (this.$refs[this.gridNameTree + this.myPrgmId] != undefined) {
					this.$refs[this.gridNameTree + this.myPrgmId].expandAll();
				}
			}
		},
		async setTagIdList(readPlcId) {
			this.tagIdList = await this.postApiReturn({
				apiKey: 'selectTagNmList',
				resKey: 'tagNmListData',
				// apiKey : 'selectReadPlcTagRel',
				// resKey : 'readPlcTagRelData',
				sendParam: {
					readPlc: readPlcId,
					// 'readPlcId':readPlcId,
					useFg: '1',
				},
			});
			if (this.tagIdList.length === 0) {
				this.tagId = '';
				this.selectedRoiId = null;
				this.tagIdList.push({
					tagId: '',
					tagNm: '',
					readPlcId: null,
					readObjId: null,
					reprTagFg: null,
				});
			} else if (this.selectedRoiId == null) {
				for (var i = 0; i < this.tagIdList.length; i++) {
					if (this.tagIdList[i]['reprTagFg'] == 1) {
						this.tagId = this.tagIdList[i]['tagId'];
						this.selectedRoiId = this.tagIdList[i]['readObjId'];
					}
				}
				if (this.tagId === '') {
					this.tagId = this.tagIdList[0]['tagId'];
					this.selectedRoiId = this.tagIdList[0]['readObjId'];
				}
			} else {
				for (var i = 0; i < this.tagIdList.length; i++) {
					if (this.tagIdList[i]['readObjId'] == this.selectedRoiId) {
						this.tagId = this.tagIdList[i]['tagId'];
					}
				}
				if (this.tagId === '') {
					this.tagId = this.tagIdList[0]['tagId'];
					this.selectedRoiId = this.tagIdList[0]['readObjId'];
				}
			}
		},
		async setRowGridData() {
			this.loadGrid = false;

			var res = [];
			res = await this.postApiReturn({
				apiKey: 'selectAutoRsltMng',
				resKey: 'autoReadRsltData',
				sendParam: {
					blocId: this.blocId,
					fromObjDt: Utility.setFormatDate(this.pageData.fromDt, 'YYYY-MM-DD'),
					readObjId: this.mttCd,
					mttTp: this.roiGrpCode,
					readDt: Utility.setFormatDate(this.pageData.fromDt, 'YYYYMMDD'),
					readPlc: this.selectedData.readPlcId,
					readPlcNm: this.selectedData.readPlcNm,
					tmFg: this.timeChkValue === false ? 0 : 1,
					tagId: this.tagId,
				},
			});

			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
				};
				return newObj;
			});

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

			this.loadGrid = true;
		},
		async getRowData(data) {
			this.selectedData = data;
			await this.setTagIdList(this.selectedData.readPlcId);
			await this.setRowGridData();
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					break;

				case 'remove':
					this.$refs[this.gridName].removeRow();
					break;

				case 'save':
					this.loadGrid = false;
					dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						const sendParam = {
							datas: { dsAutoRsltMng: dataArr },
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveAutoRsltMng',
							sendParam: sendParam,
						});
						this.setGridData({
							gridKey: this.gridName,
							value: [],
						});
						this.loadGrid = true;
						this.searchFlag = true;
					} else {
						alert('저장할 내용이 없습니다.');
						this.loadGrid = true;
					}
					break;

				default:
					break;
			}
		},
		evtUpdateDataInfo(data) {
			var gridInstance = this.$refs.rowGrid.$el.__vue__.$el.__vue__
				.gridInstance;
			gridInstance.invoke(
				'setValue',
				data.rowIdxKey,
				'readValMgnf',
				(data.value * data.rowData.mgnf) / 100.0,
			);
		},
		btnTreeExpand() {
			this.treeExpandAll = !this.treeExpandAll;
			if (this.treeExpandAll)
				this.$refs['treeGrid' + this.myPrgmId].expandAll();
			else this.$refs['treeGrid' + this.myPrgmId].collapseAll();
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	cmCycle: 'CYC_HOUR',
	fromDt: Utility.setFormatDate(new Date(), 'YYYY/MM/DD'),
	treeGrid: {
		data: [],
		column: [],
		option: {},
	},
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			readDt: null,
			readVal: 0,
			regDttm: null,
			readTm: null,
			rowStat: '',
		},
		buttonAuth: {
			save: true,
		},
	},
	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};
function numberFormatter({ value }) {
	return Utility.setFormatIntDecimal(Number(value), 2);
}
</script>
<style lang="scss">
@import '@/assets/scss/common.scss';
</style>
