<template>
	<div ref="mainDiv" class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="end" no-gutters>
						<v-col :cols="3">
							<component :is="'SelectBox'" ref="SelectBox1" :propsValue="selectValue01"
								:itemList="selectValueList01" :label="'설비종류'"
								@update:propsValue="selectValue01 = $event" labelCols="12" :textCols="12"
								:customClass="'select-large fixed-width'" :iconShow="true" />
						</v-col>
						<v-col :cols="3">
							<component :is="'SelectBox'" ref="SelectBox2" :propsValue="selectValue02"
								:itemList="selectValueList02" :label="'설비그룹'"
								@update:propsValue="selectValue02 = $event" labelCols="12" :textCols="12"
								:customClass="'select-large fixed-width'" :iconShow="true" />
						</v-col>
						<v-col :cols="3">
							<component :is="'SelectBox'" ref="SelectBox3" :propsValue="selectValue03"
								:itemList="selectValueList03" :label="'물리량타입'"
								@update:propsValue="selectValue03 = $event" labelCols="12" :textCols="12"
								:customClass="'select-large fixed-width'" :iconShow="true" />
						</v-col>
						<v-col :cols="3" class="text-right">
							<BtnSearch @click="search" size="large" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents" class="mt-3">
			<v-col :cols="5" class="h100 pr-2">
				<v-card class="pb-5">
					<v-card-title class="d-flex align-center justify-space-between pa-5">
						물리량 리스트

						<Buttons :parentPrgmId="myPrgmId" :bindingData="gridName" :detailList="detailList"
							:btnActionsFnc="btnActions" />
					</v-card-title>
					<div class="px-5" style="height:calc(100% - 76px)">
						<div ref="gridParent" class="w100 h100">
							<component :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName"
								:parentPrgmId="myPrgmId" @getRowsData="getRowData"
								@sendSelectedRowStatInfo="getSelectedRowStatInfo" :selectedRowDataWatchFlag="true"
								:preventFocusChangeEventFlag="true"
								:preventFocusChangeEventTargetGridList="editingGridList" />
						</div>
					</div>
				</v-card>
			</v-col>
			<v-col :cols="7" class="h100 pl-2">
				<v-card class="pb-5 px-4">
					<v-card-title class="px-0">물리량 상세</v-card-title>
					<v-row no-gutters>
						<v-col :cols="6" class="py-3 pr-4">
							<InputText :parentPrgmId="myPrgmId" label="물리량 ID" valueNm="pysclQtyId" :labelCols="12"
								:textCols="12" :required="requiredValueList[0]" :disabled="disabledValueList[0]"
								:readonly="readOnlyValueList[0]" placeholder="시스템 자동입력" />
						</v-col>
					</v-row>
					<v-row no-gutters>
						<v-col :cols="6" class="py-3 pr-4">
							<component :is="'SelectBox'" ref="SelectBox4" :propsValue="formEqpmGrpId"
								:itemList="formSelectValueList01" :label="'설비그룹'" :required="requiredValueList[1]"
								:disabled="disabledValueList[1]" :readonly="readOnlyValueList[1]"
								@update:propsValue="formEqpmGrpId = $event" :labelCols="12" :textCols="12" />
						</v-col>
						<v-col :cols="6" class="py-3 pl-4">
							<InputTextReg :parentPrgmId="myPrgmId" label="물리량코드" valueNm="pysclQtyCd" :labelCols="12"
								:textCols="12" :required="requiredValueList[2]" :disabled="disabledValueList[2]"
								:readonly="readOnlyValueList[2]" />
						</v-col>
					</v-row>
					<v-row no-gutters>
						<v-col :cols="6" class="py-3 pr-4">
							<InputText :parentPrgmId="myPrgmId" label="물리량명" valueNm="pysclQtyNm" :labelCols="12"
								:textCols="12" :required="requiredValueList[3]" :disabled="disabledValueList[3]"
								:readonly="readOnlyValueList[3]" />
						</v-col>
					</v-row>
					<v-row no-gutters>
						<v-col :cols="6" class="py-3 pr-4">
							<component :is="'SelectBox'" ref="SelectBox5" :propsValue="formPysclQtyTp"
								:itemList="formSelectValueList02" :label="'물리량타입'"
								@update:propsValue="formPysclQtyTp = $event" :required="requiredValueList[4]"
								:disabled="disabledValueList[4]" :readonly="readOnlyValueList[4]" :labelCols="12"
								:textCols="12" />
						</v-col>
						<v-col :cols="6" class="py-3 pl-4">
							<component :is="'SelectBox'" ref="SelectBox6" :propsValue="formUpTotMeth"
								:itemList="formSelectValueList04" :label="'상위집계방법'"
								@update:propsValue="formUpTotMeth = $event" :required="requiredValueList[5]"
								:disabled="disabledValueList[5]" :readonly="readOnlyValueList[5]" :labelCols="12"
								:textCols="12" />
						</v-col>
					</v-row>
					<v-row no-gutters>
						<v-col :cols="6" class="py-3 pr-4">
							<component :is="'SelectBox'" ref="SelectBox7" :propsValue="formUnit"
								:itemList="formSelectValueList03" :label="'단위'" @update:propsValue="formUnit = $event"
								:required="requiredValueList[6]" :disabled="disabledValueList[6]"
								:readonly="readOnlyValueList[6]" :labelCols="12" :textCols="12" />
						</v-col>
						<v-col :cols="6" class="py-3 pl-4" v-show="argContentShowFlag">
							<component :is="'EqpmCalcPop'" :parentPrgmId="myPrgmId" ref="EqpmCalcPop" :openMode="'P'"
								:modalTitle="'계산코드'" :labelContent="'계산코드'" :item="calcItem" :labelCols="12"
								:textCols="12" />
						</v-col>
					</v-row>
					<v-row no-gutters v-show="argContentShowFlag">
						<v-col :cols="12" class="py-3">
							<component :is="'TextArea'" :parentPrgmId="myPrgmId" ref="TextArea" :item="calcDescItem" />
						</v-col>
					</v-row>
					<v-row no-gutters v-show="argContentShowFlag">
						<v-col :cols="12" class="py-2">
							<label for="">
								<v-icon small
									:class="['mr-1', requiredValueList[7] ? 'icon-orange' : 'icon-blue']">$icoBulletPoint</v-icon>
								계산Argument
							</label>
						</v-col>
						<v-col :cols="6" class="py-2">
							<InputText :parentPrgmId="myPrgmId" label="ARG갯수" valueNm="argCnt" :labelCols="12"
								:textCols="12" :iconShow="true" :required="requiredValueList[7]"
								:disabled="disabledValueList[7]" :readonly="readOnlyValueList[7]" />
						</v-col>
						<v-col :cols="4"> </v-col>
						<v-col :cols="12" class="py-2" align="right">
							<a-button type="primary" @click="btnAction('add')" class="v-btn-add-text mr-1" icon="plus">추가</a-button>
							<a-button type="danger" @click="btnAction('remove')" ghost danger icon="delete">삭제</a-button>
						</v-col>
					</v-row>
					<v-row style="height:calc(30% - 76px)" v-show="argContentShowFlag">
						<v-col :cols="12" style="height:100%">
							<div ref="gridParent2" style="height:100%">
								<component :ref="gridName2" :is="loadGrid2 ? 'Grid' : null" :gridName="gridName2"
									:parentPrgmId="myPrgmId" @getRowsData="getRowData2" />
							</div>
						</v-col>
					</v-row>
					<component v-show="false" :is="'EgrpPysclQtyPop'" :parentPrgmId="myPrgmId" ref="EgrpPysclQtyPop"
						:item="EgrpPysclQtyPopItem" @dialogOpenCloseEvent="egrpPysclQtyPopOpenCloseEvent" />
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import BtnSearch from '~/components/common/button/BtnSearch';
import Buttons from '~/components/common/button/Buttons';
import InputText from '@/components/common/input/InputText';
import InputTextReg from '@/components/common/input/InputTextReg';
import Form from '~/components/common/form/Form';
import Grid from '~/components/common/Grid';
import EqpmCalcPop from '~/components/common/modal/EqpmCalcPop';
import Utility from '~/plugins/utility';
import SelectBox from '@/components/common/select/SelectBox';
import TextArea from '~/components/common/form/TextArea';
import Label from '~/components/common/form/Label';
import EgrpPysclQtyPop from '~/components/common/modal/EgrpPysclQtyPop';

let myTitle;
let myPrgmId;

export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		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,
		SelectBox,
		Buttons,
		InputText,
		Form,
		Grid,
		EqpmCalcPop,
		TextArea,
		InputTextReg,
		Label,
		EgrpPysclQtyPop,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			gridName2: 'rowGrid2',

			initedFlag: false,

			selectValue01: null, // 설비종류     : EMS_EQPM_KIND
			selectValue02: null, // 설비그룹     : EMS_EQPM_GRP
			selectValue03: null, // 물리량타입   : EM_PYSCL_QTY_TP
			selectValueList01: [],
			selectValueList02: [],
			selectValueList03: [],

			formSelectValueList01: [],
			formSelectValueList02: [],
			formSelectValueList03: [],
			formSelectValueList04: [],

			formEqpmGrpId: '', // formSelectValue01
			formPysclQtyTp: '', // formSelectValue02
			formUpTotMeth: '', // formSelectValue03
			formUnit: '', // formSelectValue04

			formatterSelectList01: [],
			formatterSelectList02: [],

			loadGrid: false,
			dataPathExample: {
				"rowGrid": {
					data: [
						{
							"pysclQtyId": "001",
							"pysclQtyCd": "TEMP001",
							"pysclQtyNm": "온도",
							"pysclQtyTp": "실수"
						},
						{
							"pysclQtyId": "002",
							"pysclQtyCd": "PRESS001",
							"pysclQtyNm": "압력",
							"pysclQtyTp": "실수"
						},
						{
							"pysclQtyId": "003",
							"pysclQtyCd": "FLOW001",
							"pysclQtyNm": "유량",
							"pysclQtyTp": "정수"
						},
						{
							"pysclQtyId": "004",
							"pysclQtyCd": "HUMID001",
							"pysclQtyNm": "습도",
							"pysclQtyTp": "실수"
						},
						{
							"pysclQtyId": "005",
							"pysclQtyCd": "VOLT001",
							"pysclQtyNm": "전압",
							"pysclQtyTp": "실수"
						}
					]

					,
					column: [
						{
							header: '물리량 ID',
							name: 'pysclQtyId',
							width: 100,
							align: 'center',
						},
						{ header: '물리량코드', name: 'pysclQtyCd', minWidth: 255 },
						{ header: '물리량명', name: 'pysclQtyNm', width: 150 },
						{
							header: '물리량타입',
							name: 'pysclQtyTp',
							width: 80,
						},

					],

				}
			},
			loadGrid2: false,
			detailList: myDetail,

			readOnlyValueList: [
				true, // 물리량 ID
				false, // 설비그룹
				false, // 물리량코드
				false, // 물리량명
				false, // 물리량타입
				false, // 상위집게방법
				false, // 단위
				true, // 계산Argument
			],
			disabledValueList: [
				true, // 물리량 ID
				false, // 설비그룹
				false, // 물리량코드
				false, // 물리량명
				false, // 물리량타입
				false, // 상위집게방법
				false, // 단위
				false, // 계산Argument
			],

			requiredValueList: [
				false, // 물리량 ID
				true, // 설비그룹
				true, // 물리량코드
				true, // 물리량명
				true, // 물리량타입
				true, // 상위집게방법
				false, // 단위
				false, // 계산Argument
			],

			editingGridList: [],

			calcItem: {
				valueNm: 'calcProc',
				valueNm2: 'argCnt',
				// 'valueNm2':'calcDesc',
				disabled: false,
				required: false,
			},
			calcDescItem: {
				valueNm: 'calcDesc',
				disabled: false,
				required: false,
				label: '계산설명',
				cols: 12,
				textCols: 12,

				padding: false,
			},
			argContentShowFlag: true,

			EgrpPysclQtyPopItem: {
				bindingItemList: {
					grid2ArgPysclQtyId: 'pysclQtyId',
					grid2PysclQtyCd: 'pysclQtyCd',
				},
				openMode: null,
				dataList: [],
				eqpmGrpDisableFlag: true,
			},
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		rowGridSelectData() {
			if (this.pageData.rowGridSelectKey == null) {
				return '';
			} else {
				return this.pageData.rowGridSelectData;
			}
		},
		formPysclQtyId() {
			if (this.pageData.rowGridSelectKey == null) {
				return '';
			} else {
				return this.pageData.pysclQtyId;
			}
		},
		// formEqpmGrpId(){
		// 	if(this.pageData.rowGridSelectKey == null){
		// 		return null;
		// 	}else{
		// 		return this.pageData.eqpmGrpId;
		// 	}
		// },
		formPysclQtyCd() {
			if (this.pageData.rowGridSelectKey == null) {
				return '';
			} else {
				return this.pageData.pysclQtyCd;
			}
		},
		formPysclQtyNm() {
			if (this.pageData.rowGridSelectKey == null) {
				return '';
			} else {
				return this.pageData.pysclQtyNm;
			}
		},
		// formPysclQtyTp(){
		// 	if(this.pageData.rowGridSelectKey == null){
		// 		return null;
		// 	}else{
		// 		return this.pageData.pysclQtyTp;
		// 	}
		// },
		// formUpTotMeth(){
		// 	if(this.pageData.rowGridSelectKey == null){
		// 		return null;
		// 	}else{
		// 		return this.pageData.upTotMeth;
		// 	}
		// },
		// formUnit(){
		// 	if(this.pageData.rowGridSelectKey == null){
		// 		return null;
		// 	}else{
		// 		return this.pageData.unit;
		// 	}
		// },
		formCalcProc() {
			if (this.pageData.rowGridSelectKey == null) {
				return '';
			} else {
				return this.pageData.calcProc;
			}
		},
		formCalcDesc() {
			if (this.pageData.rowGridSelectKey == null) {
				return '';
			} else {
				return this.pageData.calcDesc;
			}
		},
		grid2ArgSeq() {
			return this.pageData.grid2ArgSeq;
		},
		grid2PysclQtyId() {
			return this.pageData.grid2PysclQtyId;
		},
		grid2ArgPysclQtyId() {
			return this.pageData.grid2ArgPysclQtyId;
		},
		grid2PysclQtyCd() {
			return this.pageData.grid2PysclQtyCd;
		},
	},
	watch: {
		// 설비종류 : EMS_EQPM_KIND
		async selectValue01(value) {
			if (this.initedFlag) {
				await this.getSelectValueList02();
				await this.getFormSelectValueList01();
			}
		},
		// 설비그룹 : EMS_EQPM_GRP
		async selectValue02(value) {
			if (this.initedFlag) {
				await this.search();
			}
		},
		// 물리량타입 : EM_PYSCL_QTY_TP
		async selectValue03(value) {
			if (this.initedFlag) {
				await this.search();
			}
		},
		rowGridSelectData(val) {
			// console.log('val[rowGridSelectData] : ', val);
		},
		formPysclQtyId(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}
			const dt = {
				columnName: 'pysclQtyId',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		formEqpmGrpId(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			this.setPageData({
				eqpmGrpId: val,
			});

			const dt = {
				columnName: 'eqpmGrpId',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		formPysclQtyCd(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'pysclQtyCd',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		formPysclQtyNm(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'pysclQtyNm',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		async formPysclQtyTp(val) {
			if (val == 'CALC1' || val == 'CALC2') {
				// 계산코드, 계산설명, 계산Argument disabled 해제
				this.disabledValueList[7] = false;
				this.calcItem['disabled'] = false;
				this.calcDescItem['disabled'] = false;

				// 계산코드 필수처리
				this.calcItem['required'] = true;

				// 계산코드 내용 처리
				this.argContentShowFlag = true;
			} else {
				// 계산코드, 계산설명, 계산Argument disabled 처리
				this.disabledValueList[7] = true;
				this.calcItem['disabled'] = true;
				this.calcDescItem['disabled'] = true;

				// 계산코드 필수처리 해제
				this.calcItem['required'] = false;

				// 계산코드 내용 처리
				this.argContentShowFlag = false;
			}
			// disabled 처리할 컬럼 데이터 제거, 빈 그리드 표시
			await this.removeDisabledContent(val);

			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'pysclQtyTp',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		formUpTotMeth(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'upTotMeth',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		formUnit(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'unit',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		formCalcProc(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'calcProc',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);

			this.setPageData({
				rowGridSelectData: {
					...this.rowGridSelectData,
					calcProc: val,
				},
			});
		},
		formCalcDesc(val) {
			if (editingValidCheck(this.$refs, this.gridName)) {
				return;
			}

			const dt = {
				columnName: 'calcDesc',
				value: val,
			};
			this.$refs['rowGrid'].editingFinish(dt);
		},
		grid2ArgSeq(val) {
			if (editingValidCheck(this.$refs, this.gridName2)) {
				return;
			}

			const dt = {
				columnName: 'argSeq',
				value: val,
			};
			this.$refs['rowGrid2'].editingFinish(dt);
		},
		grid2PysclQtyId(val) {
			if (editingValidCheck(this.$refs, this.gridName2)) {
				return;
			}

			const dt = {
				columnName: 'pysclQtyId',
				value: val,
			};
			this.$refs['rowGrid2'].editingFinish(dt);
		},
		grid2ArgPysclQtyId(val) {
			if (editingValidCheck(this.$refs, this.gridName2)) {
				return;
			}

			const dt = {
				columnName: 'argPysclQtyId',
				value: val,
			};
			this.$refs['rowGrid2'].editingFinish(dt);
		},
		grid2PysclQtyCd(val) {
			if (editingValidCheck(this.$refs, this.gridName2)) {
				return;
			}

			const dt = {
				columnName: 'pysclQtyCd',
				value: val,
			};
			this.$refs['rowGrid2'].editingFinish(dt);
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() { },
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.initedFlag = false;
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapActions({
			getCodeList: 'modules/search/getCodeList',
			getAddGrpInfoList: 'modules/search/getAddGrpInfoList',
		}),
		async init() {
			await this.getSelectValueList01();
			await this.getSelectValueList03();
			await this.setGrid2FormatterList();
			await this.setFormSelectBoxData();
			this.gridInit();
			this.gridInit2();
			await this.search();
			this.initedFlag = true;
		},
		setEditingGridList() {
			this.editingGridList = [];

			var gridInstance = this.$refs[this.gridName2];
			this.editingGridList.push(gridInstance);
		},
		async search() {
			// this.initContentData();
			await this.getRowGridData();
		},
		async setGrid2FormatterList() {
			// 전체 설비그룹 리스트
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmGrpList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {
					// eqpmKindId:this.selectValue01
				},
			});

			this.formatterSelectList01 = res;

			// 전체 물리량 리스트
			var res2 = await this.postApiReturn({
				apiKey: 'selectEmsEgrpPysclQtyDefList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {},
			});

			this.formatterSelectList01 = res;
			this.formatterSelectList02 = res2;
		},
		async setFormSelectBoxData() {
			await this.getFormSelectValueList01();
			await this.getFormSelectValueList02();
			await this.getFormSelectValueList03();
			await this.getFormSelectValueList04();
		},
		async getFormSelectValueList01() {
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmGrpList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {
					eqpmKindId: this.selectValue01,
				},
			});

			if (res.length > 0) {
				this.formSelectValueList01 = await res.map(item => {
					return {
						text: item.eqpmGrpNm,
						value: item.eqpmGrpId,
						data: {
							...item,
						},
					};
				});
			}
		},
		async getFormSelectValueList02() {
			var res = await this.postApiReturn({
				apiKey: 'selectCommCd',
				resKey: 'commCdData',
				sendParam: {
					commGrpCd: 'EM_PYSCL_QTY_TP',
					useFg: '1',
				},
			});

			if (res.length > 0) {
				this.formSelectValueList02 = await res.map(item => {
					return {
						text: item.commCdNm,
						value: item.commCd,
						data: {
							...item,
						},
					};
				});
			}
		},
		async getFormSelectValueList03() {
			var res = await this.postApiReturn({
				apiKey: 'selectCommCd',
				resKey: 'commCdData',
				sendParam: {
					commGrpCd: 'CM_UNIT',
					useFg: '1',
				},
			});

			if (res.length > 0) {
				this.formSelectValueList03 = await res.map(item => {
					return {
						text: item.commCdNm,
						value: item.commCd,
						data: {
							...item,
						},
					};
				});
			}
		},
		async getFormSelectValueList04() {
			var res = await this.postApiReturn({
				apiKey: 'selectCommCd',
				resKey: 'commCdData',
				sendParam: {
					commGrpCd: 'EM_UP_TOT_METH',
					useFg: '1',
				},
			});

			if (res.length > 0) {
				this.formSelectValueList04 = await res.map(item => {
					return {
						text: item.commCdNm,
						value: item.commCd,
						data: {
							...item,
						},
					};
				});
			}
		},
		async getSelectValueList01() {
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmKindList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {},
			});

			if (res.length > 0) {
				this.selectValueList01 = await res.map(item => {
					return {
						text: item.eqpmKindNm,
						value: item.eqpmKindId,
						data: {
							...item,
						},
					};
				});
				this.selectValue01 = this.selectValueList01[0].value;
			} else {
				this.selectValueList01 = [];
				this.selectValue01 = null;
			}

			await this.getSelectValueList02();
		},
		async getSelectValueList02() {
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmGrpList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {
					eqpmKindId: this.selectValue01,
				},
			});

			if (res.length > 0) {
				this.selectValueList02 = await res.map(item => {
					return {
						text: item.eqpmGrpNm,
						value: item.eqpmGrpId,
						data: {
							...item,
						},
					};
				});
				this.selectValue02 = this.selectValueList02[0].value;
			} else {
				this.selectValueList02 = [];
				this.selectValue02 = null;
			}
		},
		async getSelectValueList03() {
			var res = await this.postApiReturn({
				apiKey: 'selectCommCd',
				resKey: 'commCdData',
				sendParam: {
					commGrpCd: 'EM_PYSCL_QTY_TP',
					useFg: '1',
				},
			});

			if (res.length > 0) {
				this.selectValueList03 = await res.map(item => {
					return {
						text: item.commCdNm,
						value: item.commCd,
						data: {
							...item,
						},
					};
				});
			} else {
				this.selectValueList03 = [];
			}

			this.selectValueList03.unshift({
				text: '전체',
				value: '',
			});

			this.selectValue03 = this.selectValueList03[0].value;
		},
		async getRowData(data) {
			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
				pysclQtyId: data.pysclQtyId,
				eqpmGrpId: data.eqpmGrpId,
				pysclQtyCd: data.pysclQtyCd,
				pysclQtyNm: data.pysclQtyNm,
				pysclQtyTp: data.pysclQtyTp,
				upTotMeth: data.upTotMeth,
				unit: data.unit,
				calcProc: data.calcProc,
				calcDesc: data.calcDesc,
				argCnt: data.argCnt,
			});

			this.formEqpmGrpId = data.eqpmGrpId;
			this.formPysclQtyTp = data.pysclQtyTp;
			this.formUpTotMeth = data.upTotMeth;
			this.formUnit = data.unit;

			await this.getRowGridData2();
		},
		async getRowData2(data) {
			this.setPageData({
				grid2ArgSeq: data.argSeq,
				grid2PysclQtyId: data.pysclQtyId,
				grid2ArgPysclQtyId: data.argPysclQtyId,
				grid2PysclQtyCd: data.pysclQtyCd,
			});
		},
		getSelectedRowStatInfo(data) {
			if (data) {
				var rowStat = data.rowStat;
				if (rowStat === 'I') {
					this.disabledValueList[1] = false;
					this.disabledValueList[4] = false;
				} else if (rowStat === 'U') {
					this.disabledValueList[1] = true;
					this.disabledValueList[4] = true;
				} else if (rowStat === 'D') {
					this.disabledValueList[1] = true;
					this.disabledValueList[4] = true;
				} else if (rowStat === null) {
					this.disabledValueList[1] = true;
					this.disabledValueList[4] = true;
				}
			}
		},
		initContentData() {
			this.setPageData({
				rowGridSelectKey: null,
				// rowGridSelectData: null,
				pysclQtyId: null,
				eqpmGrpId: null,
				pysclQtyCd: null,
				pysclQtyNm: null,
				pysclQtyTp: null,
				upTotMeth: null,
				unit: null,
				calcProc: null,
				calcDesc: null,
				argCnt: null,
			});
			this.formEqpmGrpId = null;
			this.formPysclQtyTp = null;
			this.formUpTotMeth = null;
			this.formUnit = null;
		},
		async gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			const _this = this;
			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				header: {
					height: 37,
				},
				rowHeight: 'auto',
			};

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

			var columnList = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{
					header: '물리량 ID',
					name: 'pysclQtyId',
					width: 100,
					align: 'center',
				},
				{ header: '설비그룹 ID', name: 'eqpmGrpId', hidden: true },
				{ header: 'argCnt', name: 'argCnt', hidden: true },
				{ header: '물리량코드', name: 'pysclQtyCd', minWidth: 255 },
				{ header: '물리량명', name: 'pysclQtyNm', width: 150 },
				{ header: 'unit', name: 'unit', hidden: true },
				{ header: 'upTotMeth', name: 'upTotMeth', hidden: true },
				{
					header: '물리량타입',
					name: 'pysclQtyTp',
					width: 80,
					formatter: function (data) {
						var resultValue = '';
						var pysclQtyTp = data.row.pysclQtyTp;

						resultValue = _this.formSelectValueList02
							.filter(item => {
								return item.value == pysclQtyTp;
							})
							.map(item => {
								return item.text;
							})[0];

						return resultValue;
					},
				},
				{ header: 'calcMeth', name: 'calcMeth', hidden: true }, // 예비컬럼?
				// { header: 'calcProc', name: 'calcProc'},
				{ header: 'calcProc', name: 'calcProc', hidden: true },
				{ header: 'calcDesc', name: 'calcDesc', hidden: true },
				{ header: 'regUserNo', name: 'regUserNo', hidden: true },
				{ header: 'regDttm', name: 'regDttm', hidden: true },
				{ header: 'procUserNo', name: 'procUserNo', hidden: true },
				{ header: 'procDttm', name: 'procDttm', hidden: true },
				{ header: 'rowStat', name: 'rowStat', hidden: true },
			];

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

			await this.getRowGridData();
		},
		async gridInit2() {
			const gridHeight = this.$refs.gridParent2.offsetHeight;
			const _this = this;
			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				header: {
					height: 37,
				},
				rowHeight: 'auto',
			};

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

			var columnList = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '물리량 ID', name: 'pysclQtyId', hidden: true },
				{ header: '순번', name: 'argSeq', editor: 'text' },
				{ header: '물리량 ID', name: 'argPysclQtyId' },
				{
					header: '설비그룹',
					name: 'eqpmGrpId',
					formatter: function (data) {
						var resultValue = '';
						var pysclQtyId = '';
						var eqpmGrpId = '';

						pysclQtyId = data.row.argPysclQtyId;

						eqpmGrpId = _this.formatterSelectList02
							.filter(item => {
								return item.pysclQtyId === pysclQtyId;
							})
							.map(item => {
								return item.eqpmGrpId;
							})[0];

						resultValue = _this.formatterSelectList01
							.filter(item => {
								return item.eqpmGrpId === eqpmGrpId;
							})
							.map(item => {
								return item.eqpmGrpNm;
							});

						return resultValue;
					},
				},
				{ header: '물리량 코드', name: 'pysclQtyCd' },
				{ header: 'regUserNo', name: 'regUserNo', hidden: true },
				{ header: 'regDttm', name: 'regDttm', hidden: true },
				{ header: 'procUserNo', name: 'procUserNo', hidden: true },
				{ header: 'procDttm', name: 'procDttm', hidden: true },
				{ header: 'rowStat', name: 'rowStat', hidden: true },
			];

			this.setGridColumn({
				gridKey: this.gridName2,
				value: columnList,
			});

			// await this.getRowGridData2();
		},
		async getRowGridData() {
			var _this = this;
			this.loadGrid = false;

			this.editingGridList = [];
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEgrpPysclQtyDefList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {
					eqpmGrpId: this.selectValue02,
					pysclQtyTp: this.selectValue03,
				},
			});

			if (res.length == 0) {
				this.initContentData();
			}

			// this.initContentData();

			var newRes = res.map(item => {
				return {
					...item,
					rowStat: null,
					calcProc: item.calcProc ? item.calcProc : '',
					calcDesc: item.calcDesc ? item.calcDesc : '',
					argCnt: item.argCnt ? item.argCnt : '',
				};
			});

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

			this.loadGrid = true;

			this.$nextTick(async () => {
				if (res.length > 0) {
					this.$refs['rowGrid'].focus({
						//rowKey: 0,
						rowKey:
							this.pageData.rowGridSelectKey == '' ||
								this.pageData.rowGridSelectKey == null
								? 0
								: this.pageData.rowGridSelectKey ==
									this.$refs['rowGrid'].getData().length - 1
									? this.pageData.rowGridSelectKey
									: 0,
						columnName: 'pysclQtyId',
						setScroll: true,
					});
				}
			});
		},
		async getRowGridData2() {
			var _this = this;
			this.loadGrid2 = false;

			if (this.pageData.pysclQtyId) {
				var res = await this.postApiReturn({
					apiKey: 'selectEmsEgrpPysclArgList',
					resKey: 'eqpmGrpPysclQtyMngData',
					sendParam: {
						pysclQtyId: this.pageData.pysclQtyId,
					},
				});
			} else {
				var res = [];
			}

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

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

			this.loadGrid2 = true;
			// this.setEditingGridList();

			this.$nextTick(() => {
				this.setEditingGridList();
			});
		},
		async btnActions(action) {
			let dataArr = [];
			let dataArr2 = [];

			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					break;

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

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					dataArr2 = this.$refs[this.gridName2].save();

					// 계산코드, 계산설명 수정사항 제거
					// if(this.formPysclQtyTp == 'TAG' || this.formPysclQtyTp == 'CONST'){
					// 	for(var i=0; i<dataArr.length; i++){
					// 		delete dataArr[i]['calcDesc'];
					// 		delete dataArr[i]['calcProc'];
					// 	}
					// }

					if (!(await this.saveValidCheck1(dataArr))) {
						break;
					}

					if (this.formPysclQtyTp != 'TAG' && this.formPysclQtyTp != 'CONST') {
						if (!(await this.saveValidCheck2(dataArr2))) {
							break;
						}
					}

					var sendParam = {
						datas: {
							eqpmGrpPysclQtyMngData: dataArr.map(item => {
								return {
									...item,
								};
							}),
						},
						params: {},
					};
					if (this.formPysclQtyTp != 'TAG' && this.formPysclQtyTp != 'CONST') {
						var sendParam2 = {
							datas: {
								eqpmGrpPysclQtyMngData: dataArr2.map(item => {
									return {
										...item,
									};
								}),
							},
							params: {},
						};
					}

					var saveReturnData = await this.postUpdateApi({
						apiKey: 'saveEmsEgrpPysclQtyDef',
						sendParam: sendParam,
					});
					saveReturnData =
						saveReturnData.data.dataset['eqpmGrpPysclQtyMngData'];

					if (this.formPysclQtyTp != 'TAG' && this.formPysclQtyTp != 'CONST') {
						if (saveReturnData.action == 'I') {
							sendParam2.datas.eqpmGrpPysclQtyMngData = sendParam2.datas.eqpmGrpPysclQtyMngData.map(
								item => {
									return {
										...item,
										pysclQtyId: saveReturnData['pysclQtyId'],
									};
								},
							);
						}
						await this.postUpdateApi({
							apiKey: 'saveEmsEgrpPysclArg',
							sendParam: sendParam2,
						});
					}
					// 물리량타입 1차계산, 최종계산이 아닐 경우 - Argument 그리드 삭제
					await this.removeCalcArgument(this.formPysclQtyTp);

					await this.search();

					break;

				default:
					break;
			}
		},
		setPysclQtyPopCheckList() {
			var gridData = this.$refs[this.gridName2].getData();

			this.EgrpPysclQtyPopItem.dataList = [];

			for (var i = 0; i < gridData.length; i++) {
				var id = gridData[i].argPysclQtyId;
				this.EgrpPysclQtyPopItem.dataList.push(id);
			}
		},
		btnAction(action) {
			switch (action) {
				case 'add':
					console.log('formEqpmGrpId : ', this.formEqpmGrpId);

					if (!this.formEqpmGrpId) {
						alert('설비그룹을 먼저 선택해주세요.');
						break;
					}

					var gridData = this.$refs[this.gridName2].getData();
					var length = gridData.length;
					var filteredGridData = gridData.filter(item => {
						return item.rowStat != 'D';
					});

					var maxArgSeq = Math.max(
						...filteredGridData.map(item => {
							return item.argSeq;
						}),
					);

					if (!isFinite(maxArgSeq)) {
						maxArgSeq = 0;
					}

					var defaultRow = {
						rowStat: 'I',
						comId: '',
						pysclQtyId: this.formPysclQtyId,
						// argSeq:'',
						argSeq: maxArgSeq + 1,
						argPysclQtyId: '',
						eqpmGrpId: '',
						pysclQtyCd: '',
						regUserNo: null,
						regDttm: null,
						procUserNo: null,
						procDttm: null,
					};

					this.$refs[this.gridName2].addRow(defaultRow, length + 1);

					this.EgrpPysclQtyPopItem.openMode = this.formPysclQtyTp;
					// this.$refs[this.gridName2].addRow();
					var targetElem = this.$refs.EgrpPysclQtyPop;
					this.setPysclQtyPopCheckList();
					targetElem.dialogOpenCloseEvent(targetElem.dialog);
					break;

				case 'edit':
					var targetElem = this.$refs.EgrpPysclQtyPop;
					targetElem.dialogOpenCloseEvent(targetElem.dialog);

					break;

				case 'remove':
					var gridData = this.$refs[this.gridName2].getData();
					var filteredGridData = gridData.filter(item => {
						return item.rowStat != 'D';
					});
					if (filteredGridData.length == 0) {
						break;
					}
					var rowKey = filteredGridData[filteredGridData.length - 1].rowKey;

					// if (filteredGridData[filteredGridData.length - 1].rowStat == 'I') {
					// 	this.$refs[this.gridName2].removeRow('immediately', rowKey);
					// } else {
					// 	this.$refs[this.gridName2].removeRow(null, rowKey);
					// }
					this.$refs[this.gridName2].removeRow('immediately', rowKey);

					break;

				default:
					break;
			}
		},
		compareData(type, newDt) {
			if (this.rowGridSelectData[type] == newDt) {
				return true;
			} else {
				return false;
			}
		},
		// true : save 진행
		async saveValidCheck1(dataArr) {
			const requiredKeyList01 = [
				'eqpmGrpId',
				'pysclQtyCd',
				'pysclQtyNm',
				'pysclQtyTp',
				'upTotMeth',
				'calcProc',
			]; // 물리량 타입이 1차계산, 최종계산일 때
			const requiredKeyList02 = [
				'eqpmGrpId',
				'pysclQtyCd',
				'pysclQtyNm',
				'pysclQtyTp',
				'upTotMeth',
			]; // 물리량 타입이 상수, 태그
			var checkList = null;

			for (var i = 0; i < dataArr.length; i++) {
				// case1 : 삭제
				if (dataArr[i].rowStat == 'D') {
					// 1. 삭제 여부 확인
					// if (confirm('삭제하시겠습니까?') == false) {
					// 	return false;
					// }
					// 2. 설비 연결 정보에서 사용하는지 확인
					var eqpmIaoData = await this.postApiReturn({
						apiKey: 'selectEqpmIao',
						resKey: 'eqpmIaoData',
						sendParam: {
							pysclQtyId: dataArr[i].pysclQtyId,
						},
					});
					// console.log('설비연결정보 : ', eqpmIaoData);

					if (eqpmIaoData.length > 0) {
						alert('설비 연결 정보에서 사용중인 물리량코드입니다.');
						return false;
					}
				}

				// case2 : 삽입, 수정
				if (dataArr[i].rowStat == 'I' || dataArr[i].rowStat == 'U') {
					// 3. 삽입, 수정시 물리량 코드 중복 체크
					var pysclQtyDefData = await this.postApiReturn({
						apiKey: 'selectEmsEgrpPysclQtyDefList',
						resKey: 'eqpmGrpPysclQtyMngData',
						sendParam: {
							eqpmGrpId: this.selectValue02,
							pysclQtyCd: dataArr[i].pysclQtyCd,
						},
					});
					// console.log('물리량코드정보 : ', pysclQtyDefData);

					for (var j = 0; j < pysclQtyDefData.length; j++) {
						if (
							pysclQtyDefData[j].pysclQtyId != dataArr[i].pysclQtyId &&
							pysclQtyDefData[j].pysclQtyCd == dataArr[i].pysclQtyCd
						) {
							alert('같은 설비그룹내에서 물리량코드가 중복되었습니다.');
							return false;
						}
					}

					// 4. 삽입, 수정시 필수값 체크

					if (this.formPysclQtyTp != 'TAG' && this.formPysclQtyTp != 'CONST') {
						checkList = requiredKeyList01;
					} else {
						checkList = requiredKeyList02;
					}

					for (var j = 0; j < checkList.length; j++) {
						if (!dataArr[i][checkList[j]]) {
							alert('필수값을 입력해주세요.');
							return false;
						}
					}
				}
			}

			return true;
		},
		async saveValidCheck2(dataArr) {
			// 1. 삽입, 수정시 arg_cnt와 행 개수가 맞는지 체크
			var gridInstance = this.$refs['rowGrid2'];
			var gridData = gridInstance.getData();
			// 두번째 그리드 유효 행 갯수
			var grid2ValidDataLength = gridData.length;

			for (var i = 0; i < gridData.length; i++) {
				if (
					gridData[i].rowStat == 'I' ||
					gridData[i].rowStat == 'U' ||
					gridData[i].rowStat == null
				) {
				} else if (gridData[i].rowStat == 'D') {
					grid2ValidDataLength--;
				}
			}

			if (typeof this.pageData.argCnt == 'number') {
				if (this.pageData.argCnt != grid2ValidDataLength) {
					alert('계산Argument의 데이터갯수가 ARG갯수와 맞지 않습니다.');
					return false;
				}
			}

			// 2. 삭제가 먼저 되도록 정렬
			dataArr.sort(function (data1, data2) {
				if (data1.rowStat > data2.rowStat) {
					return 1;
				} else if (data1.rowStat < data2.rowStat) {
					return -1;
				}
			});

			return true;
		},
		egrpPysclQtyPopOpenCloseEvent(data) {
			if (data.dialog === false) {
				if (this.grid2ArgPysclQtyId == '') {
					this.$refs[this.gridName2].removeRow('immediately');
				}
			}
		},
		async removeDisabledContent(typeVal) {
			if (typeVal == 'CALC1' || typeVal == 'CALC2') {
				await this.getRowGridData2();
			} else {
				this.setPageData({
					calcProc: '',
					calcDesc: '',
					argCnt: '',
				});
				if (this.$store.state.pageData[myPrgmId].rowGridSelectData != null) {
					this.$store.state.pageData[myPrgmId].rowGridSelectData.calcDesc = '';
				}

				this.loadGrid2 = false;
				this.$store.state.pageData[myPrgmId].rowGrid2.data = [];
				this.loadGrid2 = true;
			}
		},
		async removeCalcArgument(typeVal) {
			var _this = this;
			if (typeVal == 'CALC1' || typeVal == 'CALC2') {
			} else {
				await this.postUpdateApi({
					apiKey: 'saveEmsEgrpPysclArg',
					sendParam: {
						datas: {
							eqpmGrpPysclQtyMngData: [
								{
									rowStat: 'D',
									pysclQtyId: _this.formPysclQtyId,
								},
							],
						},
						params: {},
					},
				});
			}
		},
	},
};

function editingValidCheck(refs, rowGridName) {
	var preventFlag = false;
	try {
		var gridInstance = refs[rowGridName].gridInstance;
		var focusedCell = gridInstance.invoke('getFocusedCell');
		var focusedRowData = gridInstance.invoke('getRow', focusedCell.rowKey);
		var rowStat = focusedRowData.rowStat;

		if (rowStat == 'D') {
			preventFlag = true;
		}
	} catch (e) {
		// console.log('e :', e);
		preventFlag = true;
	} finally {
		// console.log('preventFlag : ', preventFlag);
		return preventFlag;
	}
}

const defaultData = {
	rowGridSelectKey: null,
	rowGridSelectData: null,

	pysclQtyId: null,
	eqpmGrpId: null,
	pysclQtyCd: null,
	pysclQtyNm: null,
	pysclQtyTp: null,
	upTotMeth: null,
	unit: null,
	calcProc: null,
	calcDesc: null,
	argCnt: null,

	grid2ArgSeq: null,
	grid2PysclQtyId: null,
	grid2ArgPysclQtyId: null,
	grid2PysclQtyCd: null,

	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			comId: '',
			argCnt: '',
			rowStat: 'I',
			pysclQtyId: '',
			eqpmGrpId: '',
			pysclQtyCd: '',
			pysclQtyNm: '',
			pysclQtyTp: '',
			upTotMeth: '',
			unit: '',
			calcProc: '',
			calcDesc: '',
			calcMeth: '',
			regUserNo: '',
			regDttm: '',
			procUserNo: '',
			procDttm: '',
		},
		buttonAuth: {
			add: true,
			remove: true,
			save: true,
			excel: false,
		},
	},
	rowGrid2: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			rowStat: null,
			comId: '',
			pysclQtyId: '',
			argSeq: '',
			argPysclQtyId: '',
			eqpmGrpId: '',
			pysclQtyCd: '',
			regUserNo: null,
			regDttm: null,
			procUserNo: null,
			procDttm: null,
		},
		buttonAuth: {
			add: true,
			remove: true,
		},
	},
};

const myDetail = [];
</script>
