<template>
	<v-row class="search-box">
		<v-col v-if="label" cols="2">
			<label for="" class="search-box-label">
				{{ label }}
			</label>
		</v-col>
		<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"
			></v-text-field>
		</v-col>

		<!-- <v-row justify="center"> -->
		<v-dialog ref="popModal" v-model="dialog" scrollable width="540px">
			<!-- <template v-slot:activator="{ on, attrs }">
        <v-btn color="primary" dark v-bind="attrs" v-on="on">공정/설비</v-btn>
      </template> -->
			<v-card style="height: 100%">
				<v-card-title>
					<span class="search-box-label">공정/설비</span>
				</v-card-title>
				<v-card-actions>
					<!-- <v-text-field label="위치정보 선택"></v-text-field> -->
					<v-col v-if="label" cols="3">
						<label for="" class="search-box-label">
							위치정보 선택
						</label>
					</v-col>
					<v-col :cols="label ? 6 : ''">
						<!-- :value="textfield" -->
						<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-btn color="primary" dark>접기</v-btn> -->
					<v-btn color="primary" dark>초기화</v-btn>
					<!-- as-is 롤 봐도 초기화가 하는 기능을 모르겠음.. -->
				</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.selectReadPlcTree"
							:parentPrgmId="parentPrgmId"
							@getRowsData="getRowData"
						/>
					</div>
					<!-- <component
            :is="ftnPlcListTreeData.length > 0 ? 'Tree' : null"
            :tree-data="ftnPlcListTreeData"
          /> -->
				</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-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,
		},
	},
	components: {
		Grid,
		// Tree
	},
	data() {
		return {
			label: '비교대상 최대(20개)',
			labelPrepend: true,

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

			dialog: false,
			treeData: [], // 리턴받은 원본 트리 데이터

			treeExpandAll: true,
			activeRowData: {},
			checkedRowDataList: [],
			// isUpdate: false
			// ftnPlcListTreeData: []
		};
	},
	computed: {
		...mapState({
			// searchParam: state => state.pageData,
			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.path;
			}
			return temp.join();
		},
		treeExpand() {
			return this.treeExpandAll ? '접기' : '펼치기';
		},
	},
	watch: {
		chkDialog(val) {
			if (val) {
				this.getTreeData();
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData: { selectReadPlcTree },
		});
		// console.log("2.vue::beforeCreate");
	},
	created() {
		this.init();
	},
	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 treeGridHeight = 490; // this.$refs.treeGridParent.offsetHeight - 30;
			const myOptionsTree = {
				treeColumnOptions: {
					name: 'name',
				},
			};
			if (this.searchParam.isMulti) {
				myOptionsTree['rowHeaders'] = [{ type: 'checkbox' }];
				myOptionsTree['rowHeight'] = 'auto'; // checkbox와 그리드 높이 같게
				myOptionsTree['treeColumnOptions']['useCascadingCheckbox'] = false;
			}
			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				// value: myOptionsTree
				value: Object.assign(
					Utility.defaultGridOption(treeGridHeight),
					myOptionsTree,
				),
			});
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				value: [{ header: '위치정보', name: 'name' }],
			});
		},
		// 공정/설비 조회
		async getTreeData() {
			const res = await this.postApiReturn({
				apiKey: 'selectFtnPlcListTree',
				resKey: 'ftnPlcTreeDatas',
				sendParam: {
					blocCd: this.searchParam.blocCd, //"BL0001",
					mttCd: this.searchParam.energyList[this.searchParam.energyCd].cd, // "MTT00001" // 전력 코드 고정
				},
			});

			// this.treeData = res;
			// const ROOT = res[0].plcCd;
			const setTreeData = await this.setTree({
				gridKey: this.gridNameTree,
				treeKey: 'PLC_CD',
				value: res.map(item => ({
					...item,
					plcCdNm: item.plcNm,
				})),
			});
			// this.treeData = setTreeData;

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

			this.$nextTick(() => {
				this.setGridCheckedRows();
			});
		},
		async setGridCheckedRows() {
			this.checkedRowDataList =
				this.searchParam.facInfoList.length > 0
					? this.searchParam.facInfoList
					: [];

			if (this.checkedRowDataList.length > 0) {
				for (var i = 0; i < this.checkedRowDataList.length; i++) {
					this.$refs['treeGrid' + this.parentPrgmId].checkEvt(
						this.checkedRowDataList[i],
						this.$refs['treeGrid' + this.parentPrgmId],
					);
				}
			}
		},
		// 공정/설비 트리 row 클릭이벤트
		async getRowData(data) {
			//this.activeRowData = data;
			if (this.searchParam.isMulti) {
				if (data._attributes.checked) {
					this.$refs['treeGrid' + this.parentPrgmId].uncheckEvt(
						data,
						this.$refs['treeGrid' + this.parentPrgmId],
					);
				} else {
					this.$refs['treeGrid' + this.parentPrgmId].checkEvt(
						data,
						this.$refs['treeGrid' + this.parentPrgmId],
					);
				}
			} else {
				this.activeRowData = data;
			}
		},
		setUpdate() {
			if (this.searchParam.isMulti) {
				this.checkedRowDataList = this.$refs[
					'treeGrid' + this.parentPrgmId
				].getCheckedRowsEvt();
				if (this.checkedRowDataList.length < 20) {
					this.dialog = false;

					this.setPageData({ facInfoList: this.checkedRowDataList });
				} else {
					alert('비교대상이 20개를 초과하였습니다.');
				}
			} else {
				// console.log(this.activeRowData);
				this.dialog = false;
				this.setPageData({ facInfo: this.activeRowData });
			}
		},
		// 공정/설비 트리 접기/펼치기
		btnTreeExpand() {
			this.treeExpandAll = !this.treeExpandAll;
			if (this.treeExpandAll)
				this.$refs['treeGrid' + this.parentPrgmId].expandAll();
			else this.$refs['treeGrid' + this.parentPrgmId].collapseAll();
		},
	},
};

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

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