<template>
	<v-row class="search-box" align="center" no-gutters>
		<!-- <v-col v-if="label" cols="2"> -->
		<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-col :cols="label ? 9 : ''"> -->
			<!-- :value="textfield" -->
			<v-text-field
				readonly
				v-model="selectValue"
				append-icon="mdi-magnify"
				class="v-input__custom"
				@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
		>
			<!-- <template v-slot:activator="{ on, attrs }">
        <v-btn color="primary" dark v-bind="attrs" v-on="on">공정/설비</v-btn>
      </template> -->
			<v-card :height="height">
				<v-card-title class="d-flex align-center justify-space-between">
					<span class="custom-title-4">검침개소</span>
					<v-btn icon tile :ripple="false" @click="dialog = !dialog">
						<v-icon>mdi-close</v-icon>
					</v-btn>
				</v-card-title>
				<div class="pa-5">
					<!-- <v-text-field label="위치정보 선택"></v-text-field> -->
					<v-row align="center" no-gutters>
						<v-col v-if="label" cols="3">
							<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="label ? 6 : ''">
							<!-- :value="textfield" -->
							<v-text-field
								append-icon="mdi-magnify"
								class="v-input__custom"
								outlined
								:hide-details="true"
								v-model="searchWord"
								@keyup.enter="typeEnterKey"
							></v-text-field>
						</v-col>
						<v-spacer></v-spacer>
						<v-col cols="3" class="text-right">
							<v-btn :ripple="false" icon tile @click="btnTreeExpand()">
								<!-- {{ treeExpand }} -->
								<v-icon
									size="30"
									v-text="treeExpandAll ? 'mdi-chevron-up' : 'mdi-chevron-down'"
								></v-icon>
							</v-btn>
							<!-- <v-btn color="primary" dark>펼치기</v-btn> -->
							<!-- <v-btn color="primary" dark>접기</v-btn> -->
							<!-- <v-btn :ripple="false">초기화</v-btn> -->
							<v-btn
								v-if="!searchParam.isMulti"
								:ripple="false"
								@click="search()"
								>검색</v-btn
							>
							<!-- as-is 롤 봐도 초기화가 하는 기능을 모르겠음.. -->
						</v-col>
					</v-row>
				</div>
				<v-divider></v-divider>
				<div :style="{ height: 'calc(100% - 213px)' }">
					<div ref="treeGridParent" class="h100 py-3">
						<component
							:ref="'treeGrid' + parentPrgmId"
							:is="loadGrid && dialog ? 'Grid' : null"
							:gridName="gridNameTree"
							:dataPath="searchParam.modalData.selectReadObjListTree"
							:parentPrgmId="parentPrgmId"
							@getRowsData="getRowData"
							@dblClick="setUpdate()"
						/>
					</div>
					<!-- <component
            :is="ftnPlcListTreeData.length > 0 ? 'Tree' : null"
            :tree-data="ftnPlcListTreeData"
          /> -->
				</div>
				<v-card-actions class="pa-5 d-flex align-center justify-center">
					<v-btn :ripple="false" @click="setClean()">초기화</v-btn>
					<v-btn :ripple="false" @click="setUpdate()">확인</v-btn>
					<v-btn :ripple="false" @click="dialogOpenCloseEvent(dialog)"
						>닫기</v-btn
					>
					<!-- <v-btn
            color="green darken-1"
            text
            @click="dialog = false"
          >
            Disagree
          </v-btn>
          <v-btn
            color="green darken-1"
            text
            @click="dialog = false"
          >
            Agree
          </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';

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,
		},
	},
	components: {
		Grid,
		// Tree
	},
	data() {
		return {
			labelPrepend: true,

			myModalKey: 'selectReadObjListTree',
			gridNameTree: 'treeGrid',
			loadGrid: false,

			dialog: false,
			treeData: [], // 리턴받은 원본 트리 데이터
			modalDataKey: 'modalData',
			treeExpandAll: true,
			activeRowData: {},
			checkedRowDataList: [],

			searchWord: '',

			// isUpdate: false
			// ftnPlcListTreeData: []
		};
	},
	computed: {
		...mapState({
			// searchParam: state => state.pageData,
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: 'isDarkMode',
		}),
		chkDialog() {
			// 모달 열기/닫기 값
			return this.dialog;
		},
		selectValue() {
			const readPlcData = this.searchParam.readPlcId;
			return readPlcData.path === undefined
				? readPlcData.readPlcNm
				: readPlcData.path;
			// 선택된 공장/설비 값
			// const temp = []
			// const facData = this.searchParam.facInfo;
			// if(Array.isArray(facData)){
			//   if(facData.length > 0){
			//     for(const item of facData) {
			//       temp.push(item.eccNm);
			//     }
			//   }
			// } else {
			//   return facData.path === undefined ? facData.eccNm : facData.path;
			// }
			// return temp.join();
		},
		treeExpand() {
			return this.treeExpandAll ? '접기' : '펼치기';
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				await this.getTreeData();
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData: { selectReadObjListTree },
		});
	},
	created() {
		this.init();
		this.setPageData({
			readPlcId:
				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',
			setTree: 'modules/list/setTree',
		}),
		init() {
			this.activeRowData = {};
			this.gridInit();
		},
		// 공정/설비 트리 그리드 세팅
		gridInit() {
			const treeColumnWidth = this.$refs['treeGridParent'] - 10;
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: [
					{
						header: '검침개소명',
						name: 'readPlcNm',
						width: treeColumnWidth,
						align: 'left',
					},
				],
			});
		},
		// 공정/설비 조회
		async getTreeData() {
			this.loadGrid = false;
			const res = await this.postApiReturn({
				apiKey: 'selectReadPlcBaseInfo',
				resKey: 'readPlcBaseInfoData',
				sendParam: {
					blocId:
						this.searchParam.blocMstrList.length > 0
							? this.searchParam.blocMstrList[this.searchParam.blocId].blocId
							: this.searchParam.blocId, //"BL0001",
					// roiId: this.searchParam.energyList[this.searchParam.energyCd].cd, // "MTT00001" // 전력 코드 고정
					// eqpmYn: this.eqpmYn,
					readObjId: this.searchParam.searchReadObj, // "MTT00001" // 전력 코드 고정,
					useFg: '1',
					search: this.searchWord,
				},
			});

			let myOptionsTree = {
				treeColumnOptions: {
					name: 'readPlcNm',
				},
			};

			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				// value: myOptionsTree
				value: Object.assign(
					Utility.defaultGridOption(
						this.$refs.treeGridParent.offsetHeight - 60,
					),
					myOptionsTree,
				),
			});

			// this.treeData = res;
			// const ROOT = res[0].plcCd;
			const setTreeData = await this.setTree({
				gridKey: this.gridNameTree,
				treeKey: 'READ_PLC_ID',
				value: res.map(item => ({
					...item,
					rowStat: null,
					readPlcId: item.readPlcId,
					readPlcIdNm: item.readPlcId,
					upReadPlcId:
						item.upReadPlcId == null || item.upReadPlcId == ''
							? ''
							: item.upReadPlcId,
					upReadPlcNm:
						item.upReadPlcNm == null || item.upReadPlcNm == ''
							? ''
							: item.upReadPlcNm,
					blocId: item.blocId,
					useFg: item.useFg === '1' ? true : false,
				})),
			});
			// this.treeData = setTreeData;
			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: setTreeData.ROOT,
			});
			// console.log('this.$refs["treeGrid" + this.parentPrgmId]', this.$refs)
			this.loadGrid = true;
			// this.$nextTick(() => {
			//   if (setTreeData.ROOT.length > 0) {
			//     try {
			//       this.$refs["treeGrid" + this.parentPrgmId].focus({
			//         rowKey: 0,
			//         columnName: "readPlcNm",
			//         setScroll: true
			//       });
			//     } catch (error) {

			//     }
			//   }

			// });
		},
		// 공정/설비 트리 row 클릭이벤트
		getRowData(data) {
			//this.activeRowData = data;
			this.activeRowData = data;
		},
		setUpdate() {
			this.dialog = false;
			this.setPageData({ readPlcId: this.activeRowData });
			localStorage.setItem(
				this.parentPrgmId + 'CheckedRow',
				JSON.stringify(this.searchParam.readPlcId),
			);
			this.searchWord = '';
		},
		setClean() {
			// this.$refs["treeGrid" + this.parentPrgmId].focus({
			//   rowKey: 0,
			//   columnName: "readPlcNm",
			//   setScroll: true
			// });

			// this.dialog = false;
			// this.setPageData({readPlcId : {'readPlcId' : ''}});
			this.activeRowData = {};
			localStorage.removeItem(this.parentPrgmId + 'CheckedRow');
			this.searchWord = '';
		},
		dialogOpenCloseEvent(val) {
			this.searchWord = '';
			this.dialog = !val;
		},
		// 공정/설비 트리 접기/펼치기
		btnTreeExpand() {
			this.treeExpandAll = !this.treeExpandAll;
			if (this.treeExpandAll)
				this.$refs['treeGrid' + this.parentPrgmId].expandAll();
			else this.$refs['treeGrid' + this.parentPrgmId].collapseAll();
		},
		search() {
			this.getTreeData();
		},
		typeEnterKey() {
			this.getTreeData();
		},
	},
};

const selectReadObjListTree = {
	treeGrid: {
		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>
