<template>
	<v-row class="search-box">
		<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-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-dialog v-model="dialog" scrollable width="540px">
			<v-card style="height: 100%">
				<v-card-title>
					<span v-if="label" class="custom-title-4">
						검침개소
					</span>
				</v-card-title>
				<v-card-actions>
					<v-col v-if="label" cols="3">
						<label for="" class="search-box-label">
							위치정보 선택
						</label>
					</v-col>
					<v-col :cols="label ? 6 : ''">
						<v-text-field
							append-icon="mdi-magnify"
							class="v-input__custom"
						></v-text-field>
					</v-col>

					<v-spacer></v-spacer>
					<v-btn color="primary" dark @click="btnTreeExpand()">{{
						treeExpand
					}}</v-btn>
					<v-btn color="primary" dark>초기화</v-btn>
				</v-card-actions>
				<v-divider></v-divider>
				<v-card-text>
					<div ref="treeGridParent" style="height: 500px">
						<component
							:ref="'treeGrid' + parentPrgmId"
							:is="loadGrid && dialog ? 'Grid' : null"
							:gridName="gridNameTree"
							:dataPath="searchParam.modalData.readPlcListTree"
							:parentPrgmId="parentPrgmId"
							@getRowsData="getRowData"
							@dblClick="setUpdate()"
						/>
					</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="dialog = 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';

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		label: {
			type: String,
			require: false,
			default: '공장/설비',
		},
		textCols: {
			type: Number,
			require: false,
			default: 7,
		},
		labelCols: {
			type: Number,
			require: false,
			default: 4,
		},
	},
	components: {
		Grid,
		// Tree
	},
	data() {
		return {
			// label: "공정/설비",
			labelPrepend: true,

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

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

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

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData: { readPlcListTree },
		});
	},
	created() {
		this.init();
		this.setPageData({
			facInfo:
				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() {
			// console.log("init 시작...");
			this.activeRowData = {};
			this.gridInit();
			// this.getTreeData();
			// this.lineCOption = chartOption;
		},
		// 공정/설비 트리 그리드 세팅
		gridInit() {
			// console.log("gridInit 시작...");
			const treeGridHeight = 490; // this.$refs.treeGridParent.offsetHeight - 30;
			const myOptionsTree = {
				treeColumnOptions: {
					name: 'readPlcNm',
					//useCascadingCheckbox: false
				},
			};
			if (this.searchParam.isMulti) {
				myOptionsTree['rowHeaders'] = [{ type: 'checkbox' }];
				myOptionsTree['rowHeight'] = 'auto'; // checkbox와 그리드 높이 같게
				myOptionsTree['treeColumnOptions']['useCascadingCheckbox'] = false;
			} else {
				delete this.$store.state.pageData[this.parentPrgmId]['modalData'][
					this.myModalKey
				].treeGrid.option.rowHeaders;
			}
			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				// value: myOptionsTree
				value: Object.assign(
					Utility.defaultGridOption(treeGridHeight),
					myOptionsTree,
				),
			});

			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: [
					{
						header: '측정 개소명',
						name: 'readPlcNm',
						width: 480,
						align: 'left',
					},
					{
						header: 'enableFg',
						name: 'enableFg',
						width: 480,
						align: 'left',
						hidden: true,
					},
					// , { header: "측정 개소", name: "name", align: "center"}
				],
			});
		},
		// 공정/설비 조회
		async getTreeData() {
			this.loadGrid = false;
			const res = await this.postApiReturn({
				apiKey: 'selectReadPlcDataForEnrgLossAnalysis',
				resKey: 'enrgLossAnalysisData',
				sendParam: {
					blocId: this.searchParam.blocId, //"BL0001",
					readObjid: this.searchParam.energyCd,
				},
			});
			// console.log('getTreeData : ', res);
			// 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.readPlcNm,
					upReadPlcId:
						item.upReadPlcId == null || item.upReadPlcId == ''
							? ''
							: item.upReadPlcId,
				})),
			});

			this.treeData = setTreeData;

			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: setTreeData.ROOT,
			});
			this.loadGrid = true;

			const setTreeDataKeys = Object.keys(setTreeData);

			// let nowTreeData = [];
			this.$nextTick(() => {
				if (this.searchParam.isMulti) {
					this.setGridCheckedRows();
				}
				for (var i = 0; i < setTreeDataKeys.length; i++) {
					for (var j = 0; j < setTreeData[setTreeDataKeys[i]].length; j++) {
						if (setTreeData[setTreeDataKeys[i]][j]['enableFg'] == 0) {
							this.disabledRowKeyList.push(
								setTreeData[setTreeDataKeys[i]][j]['rowKey'],
							);
						}
					}
				}
				for (var i = 0; i < this.disabledRowKeyList.length; i++) {
					this.$refs['treeGrid' + this.parentPrgmId].disabledRow(
						this.disabledRowKeyList[i],
					);
				}
				// console.log('treeGrid' + this.parentPrgmId);
				// console.log("확인", this.$refs['treeGrid' + this.parentPrgmId].getData());
				// this.treeGridInstance = this.$refs['treeGrid' + this.parentPrgmId];
				// nowTreeData = this.treeGridInstance.getData();

				// rowDatas.forEach(item => {
				//   if (item.rowKey == rowKey) {
				//     this.gridInstance.invoke(
				//       "addRowClassName",
				//       item.rowKey,
				//       "row-selected"
				//     );
				//   } else {
				//     this.gridInstance.invoke(
				//       "removeRowClassName",
				//       item.rowKey,
				//       "row-selected"
				//     );
				//   }
				// });
			});
		},
		// 공정/설비 트리 row 클릭이벤트
		async getRowData(data) {
			// console.log("getRowData 시작...");
			// console.log('data', data);
			this.activeRowData = data;
			// if(data.enableFg == 1){
			// this.activeRowData = data;
			// }
		},
		setUpdate() {
			// console.log("setUpdate 시작...");
			if (this.disabledRowKeyList.includes(this.activeRowData['rowKey'])) {
				alert('활성화된 항목을 선택해주세요');
				return;
			}
			if (this.activeRowData) {
				this.dialog = false;
				this.setPageData({ facInfo: this.activeRowData });
				localStorage.setItem(
					this.parentPrgmId + 'CheckedRow',
					JSON.stringify(this.searchParam.facInfo),
				);
			}
		},
		// 공정/설비 트리 접기/펼치기
		btnTreeExpand() {
			// console.log("btnTreeExpand 시작...");
			this.treeExpandAll = !this.treeExpandAll;
			if (this.treeExpandAll)
				this.$refs['treeGrid' + this.parentPrgmId].expandAll();
			else this.$refs['treeGrid' + this.parentPrgmId].collapseAll();
		},
	},
};

const readPlcListTree = {
	treeGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
	},
	eqpmYn: 1,
};
</script>

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