<template>
	<v-row class="search-box" align="center" no-gutters>
		<!-- <v-col v-if="label" cols="2"> -->

		<v-col :cols="label ? textCols : ''">
			<!-- <v-col :cols="label ? 9 : ''"> -->
			<!-- :value="textfield" -->
			<v-text-field
				readonly
				v-model="selectValue"
				append-icon="mdi-magnify"
				class="v-input__custom"
				placeholder="조회항목선택"
				@click="dialog = !dialog"
				:hide-details="true"
				outlined
			></v-text-field>
		</v-col>

		<!-- <v-row justify="center"> -->
		<v-dialog
			ref="popModal"
			v-model="dialog"
			width="600"
			overlay-color="#000"
			overlay-opacity="0.8"
			scrollable
		>
			<v-card style="height: 100%">
				<v-card-title class="pa-5 d-flex align-center justify-space-between">
					<span class="custom-title-4">{{ popTitle }}</span>
					<v-btn
						icon
						tile
						:ripple="false"
						@click="dialogOpenCloseEvent(dialog)"
					>
						<v-icon>mdi-close</v-icon>
					</v-btn>
				</v-card-title>
				<div class="pa-5">
					<v-row align="center" no-gutters>
						<v-col :cols="2">
							<label for="" class="search-box-label">
								<v-icon x-small color="primary" class="mr-1"
									>mdi-record-circle</v-icon
								>
								검색
							</label>
						</v-col>
						<v-col :cols="6">
							<v-text-field
								append-icon="mdi-magnify"
								class="v-input__custom"
								outlined
								:hide-details="true"
								v-model="searchWord"
								@keyup.enter="search"
							></v-text-field>
						</v-col>
						<v-spacer></v-spacer>
						<v-col cols="4" class="text-right">
							<v-btn :ripple="false" @click="search()">
								조회
							</v-btn>
							<v-btn v-if="searchParam.isMulti" :ripple="false" @click="reset()"
								>초기화</v-btn
							>
						</v-col>
					</v-row>
				</div>
				<v-divider></v-divider>
				<div :style="'height: calc(50vh)'">
					<!-- <div :style="{ height: 'calc(100% - 213px)' }"> -->
					<div ref="gridParent" class="h100 py-3">
						<component
							:ref="gridName + parentPrgmId"
							:is="loadGrid && dialog ? 'Grid' : null"
							:gridName="gridName"
							:dataPath="searchParam.modalData.OnInDataReadPop"
							:parentPrgmId="parentPrgmId"
							@getRowsData="getRowData"
							@dblClick="setUpdate($event)"
						/>
					</div>
				</div>
				<v-card-actions class="pa-5 d-flex align-center justify-center">
					<v-btn :ripple="false" @click="setUpdate($event)">확인</v-btn>
					<v-btn :ripple="false" @click="dialogOpenCloseEvent(dialog)"
						>닫기</v-btn
					>
				</v-card-actions>
			</v-card>
			<!-- <template v-slot:activator="{ on, attrs }">
        <v-btn color="primary" dark v-bind="attrs" v-on="on">공정/설비</v-btn>
      </template> -->
		</v-dialog>
	</v-row>
</template>

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

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
			default: '비교대상 최대(20개)',
		},
		label: {
			type: String,
			require: true,
			// default: "공정/설비"
		},
		labelCols: {
			type: Number,
			require: false,
			default: 4,
		},
		textCols: {
			type: Number,
			require: false,
			default: 8,
		},
		height: {
			type: Number,
			default: 713,
		},
		eqpmYn: {
			type: Number,
			require: false,
			default: 1,
		},
		popTitle: {
			type: String,
			require: false,
			default: '',
		},
	},
	components: {
		Grid,
		Utility,
		// Tree
	},
	data() {
		return {
			labelPrepend: true,

			myModalKey: 'OnInDataReadPop',
			gridName: 'modalGrid',
			loadGrid: false,

			dialog: false,
			modalDataKey: 'modalData',
			activeRowData: {},
			checkedRowDataList: [],
			searchWord: '',
			gridSet: true,
		};
	},
	computed: {
		...mapState({
			// searchParam: state => state.pageData,
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: 'isDarkMode',
		}),
		chkDialog() {
			return this.dialog;
		},
		selectValue() {
			const temp = [];
			const readObjData = this.searchParam.isMulti
				? this.searchParam.readObjList
				: this.searchParam.readObj;
			if (Array.isArray(readObjData)) {
				if (readObjData.length > 0) {
					for (const item of readObjData) {
						temp.push(item.readObjNm);
					}
				}
			} else {
				// return readObjData.path === undefined ? readObjData.eccNm : readObjData.path;
			}
			return temp.join();
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				await this.getGridData();
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData: { OnInDataReadPop },
		});
	},
	created() {
		this.init();
		if (this.searchParam.isMulti == true) {
			this.setPageData({
				readObjList:
					localStorage.getItem(this.parentPrgmId + 'CheckedRow') != null
						? JSON.parse(localStorage.getItem(this.parentPrgmId + 'CheckedRow'))
						: {},
			});
		} else {
			this.setPageData({
				readObj:
					localStorage.getItem(this.parentPrgmId + 'CheckedRow') != null
						? JSON.parse(localStorage.getItem(this.parentPrgmId + 'CheckedRow'))
						: {},
			});
		}
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setModalGridData: 'setModalGridData',
			setModalGridColumn: 'setModalGridColumn',
			setModalGridOption: 'setModalGridOption',
		}),
		...mapActions({
			postApiReturn: 'modules/list/postApiReturn',
		}),
		init() {
			this.activeRowData = {};
			this.gridInit();
		},
		// 그리드 세팅
		gridInit() {
			// const gridHeight = this.$refs.gridParent.offsetHeight - 36;
			const myOptions = {
				columOptions: {
					resizeable: true,
				},
			};

			if (this.searchParam.isMulti) {
				myOptions['rowHeaders'] = [{ type: 'checkbox' }];
				myOptions['rowHeight'] = 'auto'; // checkbox와 그리드 높이 같게
			}

			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: Object.assign(
					Utility.defaultGridOption(400, myOptions),
					myOptions,
				),
			});
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: [{ header: '검침 대상 명', name: 'readObjNm' }],
			});
		},
		// 그리드 데이터 설정
		async getGridData() {
			this.loadGrid = false;
			const res = await this.postApiReturn({
				apiKey: 'selectOnInDataReadPop',
				resKey: 'OnInDataReadPopData',
				sendParam: {
					enrgDiv: this.searchParam.enrgDiv,
					search: this.searchWord,
				},
			});

			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: res,
			});

			//화면 처음 열때 Default 체크 처리
			if (localStorage.getItem(this.parentPrgmId + 'CheckedRow') == null) {
				let temp = [];
				res.filter(item => {
					if (item.mntrFg == 1) {
						temp.push(item);
					}
				});
				this.searchParam.readObjList = temp;
			}

			this.loadGrid = true;
			this.$nextTick(() => {
				if (this.searchParam.isMulti) {
					this.setGridCheckedRows(res);
				}
			});
		},
		setGridCheckedRows(res) {
			this.checkedRowDataList =
				this.searchParam.readObjList.length > 0
					? this.searchParam.readObjList
					: [];

			if (this.checkedRowDataList.length > 0) {
				if (res.length > 0) {
					for (var i = 0; i < this.checkedRowDataList.length; i++) {
						if (res[i].readObjNm == this.checkedRowDataList[i].readObjNm) {
							this.$refs[this.gridName + this.parentPrgmId].checkEvt(
								this.checkedRowDataList[i],
								this.$refs[this.gridName + this.parentPrgmId],
							);
						}
					}
				}
			}
		},
		// row 클릭이벤트
		getRowData(data) {
			//this.activeRowData = data;
			if (this.searchParam.isMulti) {
				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],
					);
				}
			} else {
				this.activeRowData = data;
			}
		},
		setUpdate() {
			if (this.searchParam.isMulti) {
				this.checkedRowDataList = this.$refs[
					this.gridName + this.parentPrgmId
				].getCheckedRowsEvt();
				this.dialog = false;
				this.setPageData({ readObjList: this.checkedRowDataList });
				localStorage.setItem(
					this.parentPrgmId + 'CheckedRow',
					JSON.stringify(this.searchParam.readObjList),
				);
			} else {
				this.dialog = false;
				this.setPageData({ readObj: this.activeRowData });
				localStorage.setItem(
					this.parentPrgmId + 'CheckedRow',
					JSON.stringify(this.searchParam.readObj),
				);
			}
		},
		reset() {
			for (
				var i = 0;
				i < this.$refs[this.gridName + this.parentPrgmId].getData().length;
				i++
			) {
				this.$refs[this.gridName + this.parentPrgmId].uncheckEvt(
					this.$refs[this.gridName + this.parentPrgmId].getData()[i],
					this.$refs[this.gridName + this.parentPrgmId],
				);
			}
		},
		search() {
			this.getGridData();
		},
		typeEnterKey() {
			this.getGridData();
		},
		dialogOpenCloseEvent(val) {
			this.dialog = !val;
		},
	},
};

const OnInDataReadPop = {
	modalGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
	},
};
</script>
<style lang="scss" scoped>
::v-deep {
	.v-dialog {
		overflow-y: hidden !important;
	}

	.tui-grid-table-container {
		.tui-grid-table {
			border-right-style: solid !important;
			border-right-color: rgba(255, 255, 255, 0.1) !important;
		}
	}

	.tui-grid-cell.tui-grid-cell-has-tree
		.tui-grid-tree-extra-content
		+ .tui-grid-cell-content:before {
		content: none !important;
	}

	.tui-grid-tree-icon {
		margin-left: -21px !important;
	}
}

@each $theme in dark, light {
	.v-application.#{$theme}-mode {
		.v-dialog {
			.v-card {
				&__title {
					color: map-deep-get($color, 'white', '0');
					@if $theme == dark {
						background-color: #2d3355;
						.v-btn {
							background-color: #2d3355;
						}
					} @else {
						background-color: #3f4d7d;
						.v-btn {
							background-color: #3f4d7d;
						}
					}
				}
			}
		}
	}
}
</style>
