<template>
	<div>
		<v-row class="mt-3">
			<v-col :cols="6" class="py-2 pr-4">
				<InputText ref="effcIdxId" :parentPrgmId="parentPrgmId" label="효율지표 ID" valueNm="effcIdxId"
					:required="false" :readonly="true" :textCols="12" :labelCols="12" />
			</v-col>
			<v-col :cols="6" class="py-2 pl-4">
				<InputText ref="effcIdxNm" :parentPrgmId="parentPrgmId" label="효율지표 명" valueNm="effcIdxNm"
					:readonly="true" :required="false" :textCols="12" :labelCols="12" />
			</v-col>
			<v-col :cols="6" class="py-2 pr-4">
				<component :is="'SelectBox'" :propsValue="selectValue01" :itemList="selectValueList01" :label="'지표종류'"
					:textCols="12" :labelCols="12" :required="false" :readonly="true"
					@update:propsValue="selectValue01 = $event" />
			</v-col>
		</v-row>
		<div class="d-flex align-center justify-space-between pt-3 py-2">
			<v-card-title class="pa-0 custom-title-4">지표연결정보</v-card-title>
			<Buttons :parentPrgmId="parentPrgmId" :bindingData="gridName" :btnActionsFnc="btnActions" />
			<component v-show="false" ref="EgrpPysclQtyPop" :is="'EgrpPysclQtyPop'" :parentPrgmId="parentPrgmId"
				:item="EgrpPysclQtyPopItem" :labelContent="'물리량'" />
			<component v-show="false" ref="GdIdxPop" :is="'GdIdxPop'" :parentPrgmId="parentPrgmId" :item="GdIdxPopItem"
				:labelContent="'가이드지표'" />
		</div>
		<div  style="height:calc(100% - 76px)">
			<div ref="gridParent" style="height: calc(35vh);">
				<component :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName"
					:parentPrgmId="parentPrgmId" @getRowsData="getRowData" :innerTabGridInfo="innerTabGridInfo"
					 />
			</div>
		</div>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Buttons from '~/components/common/button/Buttons';
import Grid from '~/components/common/Grid';
// import Form from '~/components/common/form/Form';
import InputText from '@/components/common/input/InputText';
import SelectBox from '@/components/common/select/SelectBox';
import Utility from '~/plugins/utility';
import mixinGlobal from '@/mixin/global.js';
import EgrpPysclQtyPop from '~/components/common/modal/EgrpPysclQtyPop';
import GdIdxPop from '~/components/common/modal/GdIdxPop';
export default {
	mixins: [mixinGlobal],
	components: {
		Buttons,
		Grid,
		// Form,
		Utility,
		InputText,
		SelectBox,
		EgrpPysclQtyPop,
		GdIdxPop,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: false,
			gridName: 'effcInfoGrid',
			// 	"effcInfoGrid": {
			// 		data:
			// 			[
			// 				{
			// 					"eqpmKindId": "펌프",
			// 					"eqpmGrpId": "냉각수 시스템",
			// 					"totMethNm": "평균값"
			// 				},
			// 				{
			// 					"eqpmKindId": "모터",
			// 					"eqpmGrpId": "공기압 시스템",
			// 					"totMethNm": "최대값"
			// 				},
			// 				{
			// 					"eqpmKindId": "밸브",
			// 					"eqpmGrpId": "스팀 공급",
			// 					"totMethNm": "합계"
			// 				},
			// 				{
			// 					"eqpmKindId": "센서",
			// 					"eqpmGrpId": "온도 제어",
			// 					"totMethNm": "최소값"
			// 				},
			// 				{
			// 					"eqpmKindId": "컴프레서",
			// 					"eqpmGrpId": "에어 시스템",
			// 					"totMethNm": "중앙값"
			// 				}
			// 			]

			// 		,
			// 		column: [

			// 			{
			// 				header: '대상설비종류',
			// 				name: 'eqpmKindId',

			// 			},
			// 			{
			// 				header: '대상설비그룹',
			// 				name: 'eqpmGrpId',
			// 			},

			// 			{ header: '집계방법', name: 'totMethNm', align: 'center' },

			// 		]

			// 	}
			// },
			itemList: [],
			tagTpList: [],
			// detailList: myDetail,
			selectValueList01: [],
			selectValue01: null,
			EgrpPysclQtyPopItem: {
				dataList: [],
				openMode: 'ALL',
				bindingItemList: {
					infoPysclQtyId: 'pysclQtyId',
					infoPysclQtyCd: 'pysclQtyCd',
					infoPysclQtyNm: 'pysclQtyNm',
					infoPysclQtyTpNm: 'pysclQtyTpNm',
					infoTotMeth: 'upTotMeth',
					infoEqpmGrpId: 'eqpmGrpId',
					infoEqpmKindId: 'eqpmKindId',
					infoTotMethNm: 'upTotMethNm',
				},
			},
			GdIdxPopItem: {
				dataList: [],
				bindingItemList: {
					infoGdIdxId: 'gdIdxId',
					infoGdIdxNm: 'gdIdxNm',
					infoTotMeth: 'upTotMeth',
					infoTotMethNm: 'upTotMethNm',
					infoEqpmGrpId: 'eqpmGrpId',
					infoEqpmKindId: 'eqpmKindId',
				},
			},
			eqpmKindList: [],
			eqpmGrpList: [],
			addCheck: false,
			targetElem: '',
			gridColumn: [],
		};
	},
	computed: {
		...mapState({
			pageData(state) {
				return state.pageData[this.parentPrgmId];
			},
		}),
		selectedCommCd() {
			return this.pageData[this.gridName].data;
		},
		effcKind() {
			return this.pageData.effcKind;
		},
		infoPysclQtyId() {
			return this.pageData.infoPysclQtyId;
		},
		infoPysclQtyCd() {
			return this.pageData.infoPysclQtyCd;
		},
		infoPysclQtyNm() {
			return this.pageData.infoPysclQtyNm;
		},
		infoPysclQtyTpNm() {
			return this.pageData.infoPysclQtyTpNm;
		},
		infoGdIdxId() {
			return this.pageData.infoGdIdxId;
		},
		infoGdIdxNm() {
			return this.pageData.infoGdIdxNm;
		},
		infoTotMeth() {
			return this.pageData.infoTotMeth;
		},
		infoEqpmGrpId() {
			return this.pageData.infoEqpmGrpId;
		},
		infoEqpmKindId() {
			return this.pageData.infoEqpmKindId;
		},
		infoTotMethNm() {
			return this.pageData.infoTotMethNm;
		},
		initFlag() {
			if (this.eqpmKindList.length > 0 && this.eqpmGrpList.length > 0) {
				return true;
			} else {
				return false;
			}
		},
		targetElemDialog() {
			return this.targetElem.dialog;
		},
	},
	watch: {
		effcKind(val) {
			this.selectValue01 = val;
			// this.gridInit();
		},
		innerTabGridInfo(val) {
			if (val.tab == 1) {
				// this.gridInit();
				this.getRowGridData();
			}
		},
		infoPysclQtyId(val) {
			// console.log("@@ : ", val)
			const dt = {
				columnName: 'pysclQtyId',
				value: val,
			};
			this.$refs[this.gridName].getData().filter(item => {
				if (item.pysclQtyId == val && item.pysclQtyId != '') {
					alert('중복되는 물리량 입니다');
					this.$refs[this.gridName].removeRow();
				}
			});
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoPysclQtyCd(val) {
			const dt = {
				columnName: 'pysclQtyCd',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoPysclQtyNm(val) {
			const dt = {
				columnName: 'pysclQtyNm',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoPysclQtyTpNm(val) {
			const dt = {
				columnName: 'pysclQtyTpNm',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoGdIdxId(val) {
			this.$refs[this.gridName].getData().filter(item => {
				if (item.gdIdxId == val && item.gdIdxId != '') {
					alert('중복되는 가이드지표 입니다');
					this.$refs[this.gridName].removeRow();
				}
			});
			const dt = {
				columnName: 'gdIdxId',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoGdIdxNm(val) {
			const dt = {
				columnName: 'gdIdxNm',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoTotMeth(val) {
			const dt = {
				columnName: 'totMeth',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoTotMethNm(val) {
			const dt = {
				columnName: 'totMethNm',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoEqpmGrpId(val) {
			const dt = {
				columnName: 'eqpmGrpId',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		infoEqpmKindId(val) {
			const dt = {
				columnName: 'eqpmKindId',
				value: val,
			};
			this.$refs[this.gridName].editingFinish(dt);
		},
		async initFlag(val) {
			if (val) {
				await this.init();
			}
		},
		targetElemDialog(val) {
			if (!val) {
				if (this.$refs[this.gridName] != undefined) {
					//탭 처음 열릴때 오류 방지
					var gridData = this.$refs[this.gridName].getData();
					if (
						gridData[gridData.length - 1].gdIdxId == '' &&
						this.targetElem.myModalKey == 'gdIdxPop'
					) {
						this.$refs[this.gridName].removeRow();
					} else if (
						gridData[gridData.length - 1].pysclQtyId == '' &&
						this.targetElem.myModalKey == 'egrpPysclQtyPop'
					) {
						this.$refs[this.gridName].removeRow();
					}
				}
			}
		},
	},
	async created() {
		this.eqpmKindList = await this.postApiReturn({
			apiKey: 'selectEmsEqpmKindList',
			resKey: 'eqpmGrpPysclQtyMngData',
			sendParam: {},
		});
		this.eqpmGrpList = await this.postApiReturn({
			apiKey: 'selectEqpmGrp',
			resKey: 'eqpmGrpData',
			sendParam: {},
		});
	},
	mounted() {
		// this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setGridSelectData: 'setGridSelectData',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
			getCodeList: 'modules/search/getCodeList',
		}),
		async init() {
			await this.setSelectValueList01();
			await this.gridInit();
		},
		search() { },
		async setSelectValueList01() {
			this.selectValueList01 = [
				{
					text: '물리량',
					value: 'PYSCL',
				},
				{
					text: '가이드지표',
					value: 'GD_IDX',
				},
			];

			this.selectValue01 = this.pageData.effcKind;
		},
		async gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

			// this.loadGrid = false;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				// bodyHeight: gridHeight,
				// minBodyHeight: gridHeight,
				// header: {
				// 	height: 28,
				// },
				// rowHeight: 29,
				// minRowHeight: 29,
				// selectionUnit: 'row',
				// editingEvent: 'click',
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			const _this = this;
			let useFgSelectList = [];
			let myColumns = [
				{
					header: '대상설비종류',
					name: 'eqpmKindId',
					formatter({ value }) {
						var retVal = '';
						const newValue = _this.eqpmKindList.filter(
							item => item.eqpmKindId == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].eqpmKindNm;
						}
						return retVal;
					},
				},
				{
					header: '대상설비그룹',
					name: 'eqpmGrpId',
					formatter({ value }) {
						var retVal = '';
						const newValue = _this.eqpmGrpList.filter(
							item => item.eqpmGrpId == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].eqpmGrpNm;
						}
						return retVal;
					},
				},
				{
					header: '물리량ID',
					name: 'pysclQtyId',
					width: 200,
					align: 'center',
					hidden: true,
				},
				{ header: '물리량', name: 'pysclQtyCd', hidden: true, minWidth: 200 },
				{ header: '물리량명', name: 'pysclQtyNm', hidden: true },
				{ header: '물리량타입', name: 'pysclQtyTpNm', hidden: true },
				{ header: '가이드지표', name: 'gdIdxId', hidden: true },
				{ header: '가이드지표명', name: 'gdIdxNm', hidden: true },
				{ header: '집계방법', name: 'totMeth', hidden: true },
				{ header: '집계방법', name: 'totMethNm', align: 'center' },
			];

			if (this.selectValue01 == 'PYSCL') {
				myColumns[2].hidden = false;
				myColumns[3].hidden = false;
				myColumns[4].hidden = false;
				myColumns[5].hidden = false;
				myColumns[6].hidden = true;
				myColumns[7].hidden = true;
				this.targetElem = this.$refs.EgrpPysclQtyPop;
			} else {
				this.targetElem = this.$refs.GdIdxPop;
				myColumns[2].hidden = true;
				myColumns[3].hidden = true;
				myColumns[4].hidden = true;
				myColumns[5].hidden = true;
				myColumns[6].hidden = false;
				myColumns[7].hidden = false;
			}
			this.gridColumn = myColumns;
			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			await this.getRowGridData();
			// this.$nextTick(() => {
			//   this.loadGrid = true;
			// });
		},
		async getRowGridData() {
			var myColumns = this.gridColumn;
			this.loadGrid = false;
			var apiKey =
				this.selectValue01 == 'PYSCL' ? 'selectPysclList' : 'selectGdiList';

			if (this.selectValue01 == 'PYSCL') {
				myColumns[2].hidden = false;
				myColumns[3].hidden = false;
				myColumns[4].hidden = false;
				myColumns[5].hidden = false;
				myColumns[6].hidden = true;
				myColumns[7].hidden = true;
				this.targetElem = this.$refs.EgrpPysclQtyPop;
			} else {
				this.targetElem = this.$refs.GdIdxPop;
				myColumns[2].hidden = true;
				myColumns[3].hidden = true;
				myColumns[4].hidden = true;
				myColumns[5].hidden = true;
				myColumns[6].hidden = false;
				myColumns[7].hidden = false;
			}

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

			var res = await this.postApiReturn({
				apiKey: apiKey,
				resKey: 'effcIdxInfoData',
				sendParam: {
					effcIdxId: this.pageData.effcIdxId,
				},
			});

			var newRes = [];
			if (res.length > 0) {
				newRes = res.map(item => {
					return {
						...item,
						rowStat: null,
					};
				});
			}
			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});

			// this.$nextTick(() => {
			this.loadGrid = true;
			// });
		},
		async getRowData(data) {
			if (this.addCheck) {
				this.setPageData({
					infoPysclQtyId: data.pysclQtyId,
					infoPysclQtyCd: data.pysclQtyCd,
					infoPysclQtyNm: data.pysclQtyNm,
					infoPysclQtyTpNm: data.pysclQtyTpNm,
					infoGdIdxId: data.gdIdxId,
					infoGdIdxNm: data.gdIdxNm,
					infoTotMeth: data.totMeth,
					infoEqpmGrpId: data.eqpmGrpId,
					infoEqpmKindId: data.eqpmKindId,
				});
				this.addCheck = false;
			}
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					var defaultRow = {
						eqpmKindId: '',
						eqpmGrpId: '',
						pysclQtyId: '',
						pysclQtyCd: '',
						pysclQtyNm: '',
						pysclQtyTpNm: '',
						upTotMeth: null,
						gdIdxId: '',
						gdidxNm: '',
						rowStat: null,
					};
					if (this.targetElem.myModalKey == 'gdIdxPop') {
						this.GdIdxPopItem['dataList'] = this.$refs[this.gridName]
							.getData()
							.map(item => {
								return item.gdIdxId;
							});
					} else if (this.targetElem.myModalKey == 'egrpPysclQtyPop') {
						this.EgrpPysclQtyPopItem['dataList'] = this.$refs[this.gridName]
							.getData()
							.map(item => {
								return item.pysclQtyId;
							});
					}
					this.$refs[this.gridName].addRow(defaultRow);
					this.addCheck = true;
					this.$nextTick(() => {
						this.$refs[this.gridName].focus({
							rowKey: this.$refs[this.gridName].getData().length - 1,
							setScroll: true,
						});
					});
					// var targetElem;
					// if(this.selectValue01 == 'PYSCL'){
					//   targetElem = this.$refs.EgrpPysclQtyPop;
					// }else{
					//   targetElem = this.$refs.GdIdxPop;
					// }

					this.targetElem.dialogOpenCloseEvent(this.targetElem.dialog);
					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: {
								dsArg: dataArr.map(item => ({
									...item,
									useFg: item.useFg === true ? '1' : '0',
									effcIdxId: this.pageData.effcIdxId,
								})),
							},
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveArgList',
							sendParam: sendParam,
						});
						// this.setPageData({ isFind: true });
						this.setPageData({
							tabSaveCheck: true,
						});
						await this.getRowGridData();
						// this.loadGrid = true;
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
	},
};
</script>
