<template>
	<div>
		<div class="d-flex justify-space-between align-center my-5" >
			<span class="txt custom-subtitle-tab">설비 상수 정보</span>
			<Buttons :parentPrgmId="parentPrgmId" :bindingData="gridName" :btnActionsFnc="btnActions" />
		</div>
		<div ref="gridParent" style="min-height: calc(100vh - 800px);">
			<Grid :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName" :parentPrgmId="parentPrgmId"
				@getRowsData="getRowData" :innerTabGridInfo="innerTabGridInfo" />
		</div>
		<div style="min-height: calc(100vh - 900px);" class="mt-4">
			<component :is="'Form'" :parentPrgmId="parentPrgmId" :bindingData="gridName" :detailList="detailList"
				@gridEditingFinish="gridEditingFinish" />
		</div>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Buttons from '~/components/common/button/Buttons';
import Grid from '~/components/common/Grid';
import InputText from '~/components/common/input/InputText';
import Form from '~/components/common/form/Form';
import mixinGlobal from '@/mixin/global.js';
export default {
	mixins: [mixinGlobal],
	components: {
		Buttons,
		Grid,
		InputText,
		Form,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: false,
			gridName: 'rowEqpmConstGrid',
			detailList: myEqpmConstDetail,

			inputList_emMapDiv: [],
			inputList_cmInOut: [],
			dataPathMock: {
				'rowEqpmConstGrid': {
					column: [
						{ header: '대상항목', name: 'id', headerAlign: 'left' },
						{ header: '에너지원 명', name: 'lable', headerAlign: 'left' },
						{ header: '대상 유형', name: 'type', headerAlign: 'left' },
						{ header: '물리량', name: 'note', headerAlign: 'left' },
						{ header: '계산여부', name: 'field1', headerAlign: 'left' },
						{ header: '분배율', name: 'field2', headerAlign: 'left' }
					],
					data: dataPathDataExample,
					defaultRow: dataPathDataExample,
					option: {}
				}
			},

		};
	},
	computed: {
		...mapState({
			pageData(state) {
				return state.pageData[this.parentPrgmId];
			},
		}),
		// selectedCommCd() {
		// 	return this.pageData[this.gridName].data;
		// },
		selectedBlocId() {
			return this.pageData.rowGridSelectData.blocId;
		},
		selectedEqpmIaoId() {
			return this.pageData.rowGridSelectData.eqpmId;
		},
		selectedComId() {
			return this.pageData.rowGridSelectData.comId;
		},
		selectedEqpmKindId() {
			return this.pageData.rowGridSelectData.eqpmKindId;
		},
		selectedEqpmGrpId() {
			return this.pageData.rowGridSelectData.eqpmGrpId;
		},
		// myUseFgList() {
		// 	return this.pageData.useFgList;
		// },
	},
	watch: {
		selectedEqpmKindId(val) {
			if (val) {
				this.detailList[1].eqpmKindId = val;
			}
		},
		selectedEqpmGrpId(val) {
			// if(!val){
			// 	this.detailList[1].eqpmGrpId = '';
			// }else{
			// 	this.detailList[1].eqpmGrpId = val;
			// }
			// if(val){
			// 	this.detailList[1].eqpmGrpId = val;
			// }
			// else if(val == null || val == ''){
			// 	this.detailList[1].eqpmGrpId = '';
			// }
		},
	},
	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',
		}),
		init() {
			this.gridInit();
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			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: myOptions,
			});

			const _this = this;
			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '설비 번호', name: 'eqpmId', hidden: true },
				// { header: '대상항목', name: 'objId', align: 'center', hidden: true},
				{ header: '물리량 ID', name: 'pysclQtyId', align: 'left', minWidth: 230, },
				{ header: '물리량 명', name: 'pysclQtyNm', align: 'left', minWidth: 230, },
				{ header: '물리량값', name: 'pysclQtyVal', align: 'left', minWidth: 230, },
				// { header: '대상항목', name: 'objNm', align: 'left'},
				{ header: '대상항목', name: 'objId', align: 'left', minWidth: 230, },
				{
					header: '에너지원 명',
					name: 'ercId',
					align: 'left',
					hidden: true,
					formatter({ value }) {
						var retVal = '';

						for (var i = 0; i < _this.pageData.ercNmList.length; i++) {
							if (_this.pageData.ercNmList[i].value === value) {
								retVal = _this.pageData.ercNmList[i].text;
							}
						}

						return retVal;
					},
				},
				{
					header: '대상 유형',
					name: 'objKind',
					align: 'center',
					hidden: true,
					formatter({ value }) {
						var retVal = '';

						for (var i = 0; i < _this.pageData.emMapDivList.length; i++) {
							if (_this.pageData.emMapDivList[i].commCd === value) {
								retVal = _this.pageData.emMapDivList[i].commCdNm;
							}
						}

						return retVal;
					},
				},
				{
					header: 'inProdKind',
					name: 'inProdKind',
					align: 'left',
					hidden: true,
				},
				{ header: 'blocId', name: 'blocId', align: 'left', hidden: true },
				{
					header: '계산여부',
					name: 'calcFg',
					align: 'center',
					hidden: true,
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ header: '분배율', name: 'distRt', align: 'right', hidden: true },
				{ header: '등록 사용자', name: 'regUserNo', hidden: true },
				{ header: '등록 일자', name: 'regDttm', hidden: true },
				{ header: '수정 사용자', name: 'procUserNo', hidden: true },
				{ header: '수정 일자', name: 'procDttm', hidden: true },
				{ header: 'rowStat', name: 'rowStat', hidden: true },
			];

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

			this.$nextTick(() => {
				this.loadGrid = true;
			});
		},
		async getRowData(data, gridName) {
			if (data.rowStat === 'I') {
				this.detailList[1].disabled = false;
				this.detailList[3].disabled = false;
			} else {
				this.detailList[1].disabled = true;
				this.detailList[3].disabled = true;
			}

			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: Object.assign({}, data),
			});
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					this.detailList[1].disabled = false;
					this.detailList[3].disabled = false;
					break;

				case 'remove':
					this.detailList[1].disabled = true;
					this.detailList[3].disabled = true;
					this.$refs[this.gridName].removeRow();
					break;

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					var validCheck = true;

					var gridInstance = this.$refs[this.gridName];
					var gridData = gridInstance.getData();

					// check duplicate of pysclQtyId
					if (checkDuplicate(gridData, 'pysclQtyId')) {
						alert('물리량 값이 중복되었습니다.');
						break;
					}

					if (dataArr.length > 0) {
						var requiredKeyList = this.detailList
							.filter(item => {
								return item.class != 'py-2 d-none' && item.required == true;
							})
							.map(item => {
								return item.valueNm;
							});

						dataArr.map(item => {
							for (var key of Object.keys(item)) {
								// console.log('key : ', key);
								// console.log('item[key] : ', item[key]);
								if (!item[key] && requiredKeyList.includes(key)) {
									validCheck = false;
								}
							}
						});

						if (validCheck) {
							const sendParam = {
								datas: {
									dsEqpmIao: dataArr.map(item => ({
										...item,
										comId: this.selectedComId,
										blocId: this.selectedBlocId,
										eqpmId: this.selectedEqpmIaoId,
										calcFg: item.calcFg == true ? '1' : '0',
									})),
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveEqpmIao',
								sendParam: sendParam,
							});
							this.setPageData({ isFind: true });
						} else {
							alert('필수 입력값을 입력해주세요');
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data, bindingData) {
			this.$refs[this.gridName].editingFinish(data);
		},
		search() { },
	},
};

function checkDuplicate(data, targetKey) {
	var duplicateFlag = false;
	var set = new Set();

	for (var row of data) {
		if (set.has(row[targetKey])) {
			duplicateFlag = true;
			break;
		} else {
			if (row[targetKey]) {
				set.add(row[targetKey]);
			}
		}
	}

	return duplicateFlag;
}

const myEqpmConstDetail = [
	{
		type: 'SelectBox',
		label: '대상 유형',
		cols: 6,
		class: 'py-3 pr-4',
		list: 'emMapDivList2',
		valueNm: 'objKind',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: true,
		disabled: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
	},
	// ==================
	{
		type: 'EgrpPysclQtyPop',
		labelContent: '물리량',
		modalTitle: '물리량 선택',
		bindingItemList: {
			objId: 'pysclQtyId',
			objNm: 'pysclQtyNm',
			pysclQtyId: 'pysclQtyId',
			pysclQtyNm: 'pysclQtyNm',
		},
		valueNm: 'objId',
		disabled: true,
		required: true,
		openMode: 'CONST',
		cols: 6,
		class: 'py-3 pl-4',
		eqpmGrpDisableFlag: true,
		// eqpmGrpId:'',
		labelCols: 12,
		textCols: 12,
		iconShow: true,
	},
	{
		// 공백 처리
		type: 'Label',
		cols: 6,
		class: 'py-3',
		disabled: true,
	},
	{
		type: 'InputText',
		valueNm: 'pysclQtyNm',
		disabled: true,
		readonly: true,
		cols: 6,
		class: 'py-3 pt-1 pl-4',
		align: 'right',
		// class: 'py-2 d-none',
		labelCols: 12,
		textCols: 12,
		iconShow: true,
	},
	// ------------
	{
		type: 'InputText',
		label: '물리량 값',
		valueNm: 'pysclQtyVal',
		disabled: false,
		cols: 6,
		class: 'py-3 pr-4',
		align: 'right',
		inputType: 'number',
		min: 0,
		max: 100,
		required: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
	},
];

import { getPathDataExample } from '@/const/const'
const dataPathDataExample = getPathDataExample({
	id: 'INCHEON.HVAC.EQP_HT_CH001.UT_CH101.CHI_AMP_1A_PV',
	lable: 'INCHEON 고온 냉동기 101호기 - 호로1',
	type: '사용', note: '-',
	field1: '1111',
	field2: '2222',
});
</script>

<style lang="scss" scoped>
	::v-deep {
		.tui-grid-layer-state {
			top: 40px !important;
		}
	}
</style>
