<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="height: calc(100vh - 700px);">
			<Grid
				:ref="gridName"
				:is="loadGrid ? 'Grid' : null"
				:gridName="gridName"
				:parentPrgmId="parentPrgmId"
				@getRowsData="getRowData"
				:innerTabGridInfo="innerTabGridInfo"
			/>
		</div>
		<div style="height: 60vh;" class="mt-5">
			<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: 'rowEqpmIaoGrid',
			detailList: myEqpmIaoDetail,

			inputList_emMapDiv: [],
			inputList_cmInOut: [],
		};
	},
	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;
		},
		// myUseFgList() {
		// 	return this.pageData.useFgList;
		// },
		selectedObjId() {
			if (this.pageData.rowEqpmIaoGrid.rowGridSelectData === null) {
				return '';
			} else {
				return this.pageData.rowEqpmIaoGrid.rowGridSelectData.objKind;
			}
		},
		selectedCalcFg() {
			if (this.pageData.rowEqpmIaoGrid.rowGridSelectData === null) {
				return '';
			} else {
				return this.pageData.rowEqpmIaoGrid.rowGridSelectData.calcFg;
			}
		},
		selectedEqpmKindId() {
			return this.pageData.rowGridSelectData.eqpmKindId;
		},
		selectedEqpmGrpId() {
			return this.pageData.rowGridSelectData.eqpmGrpId;
		},
	},
	watch: {
		selectedObjId(val) {
			if (val === 'TAG') {
				// this.detailList[1].class = 'py-3 pl-4 pb-0';
				this.detailList[1].class = 'py-3 d-none';
				this.detailList[2].class = 'py-3 d-none';
				this.detailList[3].class = 'py-3 pl-4 pt-1 d-none';

				this.detailList[4].class = 'py-3';
				this.detailList[5].class = 'py-3 pl-4';
				this.detailList[6].class = 'py-3 pl-4 pt-0';
			} else {
				// }else if(val==="READ_PLC"){
				this.detailList[1].class = 'py-3 pl-4';
				this.detailList[2].class = 'py-3';
				this.detailList[3].class = 'py-3 pl-4 pt-0';

				this.detailList[4].class = 'py-3 d-none';
				this.detailList[5].class = 'py-3 d-none';
				this.detailList[6].class = 'py-3 d-none';
			}
		},
		selectedCalcFg(val) {
			if (val === true) {
				this.detailList[6].required = true;
				this.detailList[7].required = true;
			} else {
				this.detailList[6].required = false;
				this.detailList[7].required = false;
			}
		},
		selectedEqpmKindId(val) {
			if (val) {
				this.detailList[10].eqpmKindId = val;
			}
		},
		selectedEqpmGrpId(val) {
			// console.log('selectedEqpmGrpId : ', val);
			// if (!val) {
			// 	this.detailList[10].eqpmGrpId = '';
			// } else {
			// 	this.detailList[10].eqpmGrpId = val;
			// }
			// if(val){
			// 	this.detailList[10].eqpmGrpId = val;
			// }
			// else if(val == null || val == ''){
			// 	this.detailList[10].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,
			});

			// let addInfoDataKindList = [];
			// this.pageData.addInfoDataKindList.forEach(item => {
			//   const it = { text: item.commCdNm, value: item.commCd };
			//   addInfoDataKindList.push(it);
			// });

			const _this = this;
			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '설비 번호', name: 'eqpmId', hidden: true },
				{ header: '대상항목', name: 'objId', align: 'center', hidden: true },
				{ header: '대상항목', name: 'objNm', align: 'left', width: 350 },
				{
					header: '에너지원 명',
					name: 'ercId',
					align: 'left',
					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: 'left',
					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: '물리량', name: 'pysclQtyId', align: 'left', hidden: true },
				{ header: '물리량', name: 'pysclQtyNm', align: 'left' },
				{
					header: '물리량값',
					name: 'pysclQtyVal',
					align: 'left',
					hidden: true,
				},
				{
					header: 'inProdKind',
					name: 'inProdKind',
					align: 'left',
					hidden: true,
				},
				{ header: 'blocId', name: 'blocId', align: 'left', hidden: true },
				{
					header: '계산여부',
					name: 'calcFg',
					align: 'left',
					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' },
				{ 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.loadGrid = true;
		},
		async getRowData(data, gridName) {
			if (data.rowStat === 'I') {
				this.detailList[0].disabled = false;
				this.detailList[1].disabled = false;
				this.detailList[3].disabled = false;
				this.detailList[4].disabled = false;
				this.detailList[5].disabled = false;
			} else {
				this.detailList[0].disabled = true;
				this.detailList[1].disabled = true;
				this.detailList[3].disabled = true;
				this.detailList[4].disabled = true;
				this.detailList[5].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[0].disabled = false;
					this.detailList[1].disabled = false;
					this.detailList[3].disabled = false;
					this.detailList[4].disabled = false;
					this.detailList[5].disabled = false;
					break;

				case 'remove':
					this.$refs[this.gridName].removeRow();
					this.detailList[0].disabled = true;
					this.detailList[1].disabled = true;
					this.detailList[3].disabled = true;
					this.detailList[4].disabled = true;
					this.detailList[5].disabled = true;
					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) {
						// console.log('dataArr : ', dataArr);

						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)) {
								// calcFg는 체크해제시에 입력값이 false로 들어가있어서 제외
								if (
									!item[key] &&
									requiredKeyList.includes(key) &&
									key != 'calcFg'
								) {
									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',
										pysclQtyId: item.pysclQtyId ? item.pysclQtyId : '',
									})),
								},
								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 myEqpmIaoDetail = [
	{
		type: 'SelectBox',
		label: '대상 유형',
		cols: 6,
		class: 'py-3 pr-4',
		list: 'emMapDivList',
		// list: 'ercNmList',
		valueNm: 'objKind',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: true,
		disabled: false,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		type: 'ReadPlcPop',
		label: '대상 항목',
		valueNm: 'objId',
		cols: 6,
		class: 'py-3 pl-4 pb-0',
		required: true,
		disabled: true,
		bindNm: 'objNm',
		textCols: 12,
		labelCols: 12,
		iconShow: true,
	},
	{
		// 공백 처리
		type: 'Label',
		cols: 6,
		class: 'py-3',
		disabled: true,
		textCols: 12,
		labelCols: 12,
	},
	{
		type: 'InputText',
		valueNm: 'objNm',
		readonly: true,
		disabled: true,
		cols: 6,
		class: 'py-3 pl-4 pt-0',
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
// ============
	{
		type: 'EvtObjPop',
		labelContent: '대상 항목',
		valueNm: 'objId',
		valueNm2: 'objNm',
		bindNm: 'objNm',
		disabled: true,
		required: true,
		cols: 6,
		class: 'py-3 pl-4 d-none',
		disableContent: true,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		type: 'Label',
		cols: 6,
		class: 'py-3 d-none',
		disabled: true,
		textCols: 12,
		labelCols: 12,
	},
	{
		type: 'InputText',
		cols: 6,
		class: 'py-3 pl-4 d-none',
		valueNm: 'objNm',
		readonly: true,
		disabled: true,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	// --------------------------------------------
	{
		type: 'SelectBox',
		label: '에너지원',
		disabled: false,
		cols: 6,
		class: 'py-3 pr-4',
		list: 'ercNmList',
		valueNm: 'ercId',
		itemText: 'text',
		itemValue: 'value',
		required: false,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		type: 'SelectBox',
		label: '투입생산유형',
		disabled: false,
		cols: 6,
		class: 'py-3 pl-4',
		list: 'cmInoutList',
		valueNm: 'inProdKind',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: false,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '분배율(1~100)',
		valueNm: 'distRt',
		disabled: false,
		cols: 6,
		class: 'py-3 pr-4',
		align: 'right',
		inputType: 'number',
		min: 0,
		max: 100,
		required: false,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		type: 'CheckBox',
		label: '계산 여부',
		valueNm: 'calcFg',
		disabled: false,
		cols: 6,
		class: 'py-3 pl-4',
		value: { '1': true, '0': false },
		required: false,
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		type: 'EgrpPysclQtyPop',
		labelContent: '물리량',
		modalTitle: '물리량 선택',
		bindingItemList: {
			pysclQtyId: 'pysclQtyId',
			pysclQtyNm: 'pysclQtyNm',
		},
		// bindingData:'rowEqpmIaoGrid',
		valueNm: 'pysclQtyId',
		// valueNm:'calcProc',
		// valueNm2:'calcDesc',
		disabled: false,
		required: false,
		openMode: 'TAG',
		cols: 6,
		class: 'py-3 pr-4',
		eqpmGrpDisableFlag: true,
		// eqpmGrpId: '',
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
	{
		// 공백 처리
		type: 'Label',
		cols: 6,
		class: 'py-2',
		disabled: true,
		textCols: 12,
		labelCols: 12,
	},
	{
		type: 'InputText',
		valueNm: 'pysclQtyNm',
		disabled: true,
		readonly: true,
		cols: 6,
		class: 'py-3 pt-0 pr-4',
		align: 'right',
		textCols: 12,
		labelCols: 12,
		iconShow: true
	},
];
</script>
<style lang="scss" scoped >
::v-deep {
	.tui-grid-layer-state {
		top: 40px !important;
	}
}
</style>
