<template>
	<v-row class="search-box" align="center" no-gutters>
		<v-col v-if="label" :cols="labelCols">
			<label for="" class="search-box-label">
				<!-- <v-icon x-small color="primary" class="mr-1">mdi-record-circle</v-icon> -->
				<!-- {{ label }} -->
			</label>
		</v-col>
		<v-col :cols="label ? textCols : ''">
			<v-btn
				readonly
				append-icon="mdi-magnify"
				class="v-input__custom"
				@click="dialog2 = !dialog2"
				outlined
				:hide-details="true"
				>{{ label }}</v-btn
			>
		</v-col>

		<v-dialog v-model="dialog2" scrollable width="540px">
			<v-card style="height: 100%">
				<v-card-title>
					<span class="custom-title-4">사용자 조회</span>
				</v-card-title>
				<v-card-actions>
					<v-row>
						<v-col :cols="7">
							<v-text-field
								append-icon="mdi-magnify"
								class="v-input__custom"
								v-model="searchWord"
								@keyup.enter="typeEnterKey"
							></v-text-field>
						</v-col>
						<v-col :cols="5" class="text-right">
							<v-btn :ripple="false" @click="getData()">조회</v-btn>
							<BtnExcelDownload
								:ref="'excelButton01'"
								:parentPrgmId="parentPrgmId"
								:gridName="gridName"
								:parentModalDataName="'modalData2'"
								:myModalKey="myModalKey"
							/>
							<v-btn :ripple="false" @click="saveGridData()">저장</v-btn>
						</v-col>
					</v-row>
				</v-card-actions>
				<v-divider></v-divider>
				<v-card-text>
					<div ref="rowGridParent" style="height: 300px">
						<component
							:ref="gridName + parentPrgmId"
							:is="loadGrid && dialog2 ? 'Grid' : null"
							:gridName="gridName"
							:dataPath="searchParam.modalData2.selectFixedValueModiPop"
							:parentPrgmId="parentPrgmId"
							@getRowsData="getRowData"
						/>
					</div>
				</v-card-text>
				<v-divider></v-divider>
				<v-card-actions>
					<v-spacer></v-spacer>
					<!-- <v-btn color="primary" dark @click="setUpdate()">확인</v-btn> -->
					<v-btn color="primary" dark @click="dialog2 = false">닫기</v-btn>
				</v-card-actions>
			</v-card>
		</v-dialog>
	</v-row>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Buttons from '~/components/common/button/Buttons';

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		labelCols: {
			type: Number,
			require: false,
			default: 4,
		},
		textCols: {
			type: Number,
			require: false,
			default: 7,
		},
	},
	components: {
		Grid,
		BtnExcelDownload,
		Buttons,
	},
	data() {
		return {
			label: '고정값 수정',
			modalDataKey: 'modalData2',
			myModalKey: 'selectFixedValueModiPop',
			gridName: 'rowGrid',
			loadGrid: false,
			searchWord: '',
			dialog2: false,
		};
	},
	computed: {
		...mapState({
			// searchParam: state => state.pageData,
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
		}),
		chkDialog() {
			// 모달 열기/닫기 값
			return this.dialog2;
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				// 열릴 때
				console.log('dsfafds');
				await this.getData();
				// console.log("chkDialog: ", val);
				// if(this.searchParam.selecUserList.length > 0){
				//   for(var i=0; i<this.searchParam.selecUserList.length; i++) {
				//     this.$refs[this.gridName + this.parentPrgmId].checkEvt(this.searchParam.selecUserList[i], this.$refs[this.gridName + this.parentPrgmId]);
				//   }
				// }
				// this.$refs[this.gridName + this.parentPrgmId].setCheck(
				//   this.searchParam.selecUserListRowKeys
				// );
			} else {
				// 닫힐 때
				this.setPageData({
					myUserList: null,
				});
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData2: { selectFixedValueModiPop },
		});
		// console.log("2.vue::beforeCreate");
	},
	created() {
		this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setModalGridData: 'setModalGridData',
			setModalGridColumn: 'setModalGridColumn',
			setModalGridOption: 'setModalGridOption',
		}),
		...mapActions({
			postApiReturn: 'modules/list/postApiReturn',
			postUpdateApi: 'modules/list/postUpdateApi',
			// setTree: "modules/list/setTree"
		}),
		init() {
			this.gridInit();
		},
		async saveGridData() {
			this.loadGrid = false;
			let dataArr = this.$refs[this.gridName + this.parentPrgmId].save();
			// this.setPageData({ isFind: true });

			for (var i = 0; i < dataArr.length; i++) {
				if (
					dataArr[i].addInfoDataKind == 'NUM' &&
					dataArr[i].addInfoVal == ''
				) {
					dataArr[i].addInfoVal = null;
				}
			}
			console.log('dataArr', dataArr);
			if (dataArr.length > 0) {
				const sendParam = {
					datas: {
						fixedValModiPopDatas: dataArr.map(item => ({
							...item,
						})),
					},
					params: {},
				};
				await this.postUpdateApi({
					apiKey: 'savefixedValModiPopDatas',
					sendParam: sendParam,
				});
				await this.getData();
				this.loadGrid = true;
				this.setPageData({ isFind: true });
			} else {
				this.loadGrid = true;
				alert('저장할 내용이 없습니다.');
			}
		},
		gridInit() {
			const gridHeight = 490; // this.$refs.rowGridParent.offsetHeight - 30;

			const myOptions = {
				// rowHeaders: ["checkbox"]
			};
			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: myColumns,
			});
		},
		async getData() {
			this.loadGrid = false;
			let sendParams = {
				search: this.searchWord,
				// userNo: '',
				// userLoginId: '',
				// deptId: ''
			};

			const res = await this.postApiReturn({
				apiKey: 'selectFixedValueModiPop',
				resKey: 'tagFixedValData',
				sendParam: sendParams,
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
					useFg: item.useFg === '1' ? true : false, // 화면 개발 편의를 위해 boolean 타입으로 교체, 저장시 "1", "0" 으로 바꿔 보내야 함
				};
				return newObj;
			});

			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: newRes,
			});
			this.loadGrid = true;
		},
		// 공정/설비 트리 row 클릭이벤트
		getRowData(data) {
			//this.activeRowData = data;
			if (data._attributes.checked) {
				this.$refs[this.gridName + this.parentPrgmId].uncheckEvt(
					data,
					this.$refs[this.gridName + this.parentPrgmId],
				);
			} else {
				this.$refs[this.gridName + this.parentPrgmId].checkEvt(
					data,
					this.$refs[this.gridName + this.parentPrgmId],
				);
			}
		},
		// setUpdate() {
		//   // console.log("이게뭐야", this.$refs[this.gridName + this.parentPrgmId])
		//   console.log("adsfasdfasdfasf", this.$refs[ this.gridName + this.parentPrgmId].getData());

		//   // let gridInstance = this.$refs[ this.gridName + this.parentPrgmId];
		//   // const saveTargetRows = gridInstance.invoke("getModifiedRows");
		//   // console.log('saveTargetRows', saveTargetRows);

		//   let dataArr = this.$refs[ this.gridName + this.parentPrgmId].save();

		//   this.dialog2 = false;
		//   this.setPageData({
		//     selecUserList: this.$refs[
		//       this.gridName + this.parentPrgmId
		//     ].getCheckedRowsEvt()
		//   });
		//   // this.setPageData({
		//   //   selecUserListRowKeys: this.$refs[
		//   //     this.gridName + this.parentPrgmId
		//   //   ].getCheckedRowKeys()
		//   // });
		// },
		// 검색
		typeEnterKey() {
			this.getData();
		},
	},
};

const selectFixedValueModiPop = {
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			eccId: '',
			readObjId: '',
			ucId: '',
			tagId: '',
			tagNm: '',
			dfltVal: '',
			userVal: '',
			rowStat: null,
		},
		buttonAuth: {
			add: false,
			remove: false,
			save: true,
			excel: true,
		},
	},
	eqpmYn: 1,
	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};

const myColumns = [
	{ header: '공정ID', name: 'eccId', align: 'left', hidden: true },
	{ header: '에너지ID', name: 'readObjId', align: 'left', hidden: true },
	{ header: '케이스명', name: 'ucId', align: 'left', hidden: true },
	{ header: '태그ID', name: 'tagId', align: 'left', hidden: true },
	{ header: '태그명(R)', name: 'tagNm', align: 'left' },
	{ header: '디폴트값(R)', name: 'dfltVal', align: 'right' },
	{
		header: '사용자 세팅값(E)',
		name: 'userVal',
		align: 'right',
		editor: 'text',
	},
];
</script>

<style scoped>
.v-input {
	font-size: 12px;
}
.v-label {
	font-size: 10px;
}
</style>
