<template>
	<span>
		<v-tooltip bottom>
			<template v-slot:activator="{ on, attrs }">
				<v-icon class="mr-1" v-bind="attrs" v-on="on" @click="dialog = true"
					>mdi-tooltip-plus
				</v-icon>
			</template>
			<span>검침개소</span>
		</v-tooltip>
		<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="v-card__title 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-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="7">
							<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 v-if="searchParam.isMulti" :ripple="false" @click="reset()"
								>초기화</v-btn
							>
							<v-btn :ripple="false" icon tile @click="btnTreeExpand()">
								<v-icon
									size="30"
									v-text="treeExpandAll ? 'mdi-chevron-up' : 'mdi-chevron-down'"
								></v-icon>
							</v-btn>
							<v-btn :ripple="false" @click="reset()">초기화</v-btn>
						</v-col>
					</v-row>
				</div>
				<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.selectReadPlcListTree"
							: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>
	</span>
</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,
		},
		widGetKey: {
			type: String,
			require: true,
		},
		widgetDataKey: {
			type: String,
			require: true,
		},
		isMulti: {
			type: Boolean,
			require: false,
			default: null,
		},
		mntrFg: {
			type: String,
			require: false,
			default: null,
		},
	},
	components: {
		Grid,
		// Tree
	},
	data() {
		return {
			myModalKey: 'selectReadPlcListTree',
			gridNameTree: 'treeGrid',
			loadGrid: false,

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

			searchWord: '', // 팝업내 검색
		};
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId][this.widGetKey][
					this.widgetDataKey
				];
			},
		}),
		chkDialog() {
			return this.dialog;
		},
		treeExpand() {
			return this.treeExpandAll ? '접기' : '펼치기';
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				await this.getTreeData();
			}
		},
	},

	beforeCreate() {},
	created() {
		this.$store.state.pageData[this.parentPrgmId][this.widGetKey][
			this.widgetDataKey
		].modalData = { selectReadPlcListTree };
		this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setModalGridData: 'setModalGridData',
			setModalGridColumn: 'setModalGridColumn',
			setModalGridOption: 'setModalGridOption',
			setWidgetModalGridData: 'setWidgetModalGridData',
			setWidgetModalGridColumn: 'setWidgetModalGridColumn',
			setWidgetModalGridOption: 'setWidgetModalGridOption',
		}),
		...mapActions({
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
		}),
		init() {
			this.activeRowData = {};
			this.gridInit();
		},
		// 공정/설비 트리 그리드 세팅
		gridInit() {
			const treeGridHeight = 490;
			if (this.$store.state.activeMenuInfo.prgmId == '0') {
				this.$store.state.activeMenuInfo.prgmId = this.$route.query.prgmId;
			}
			this.setWidgetModalGridColumn({
				widgetId: this.widGetKey,
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: [
					{
						header: '검침개소명',
						name: 'readPlcNm',
						width: 370,
						align: 'left',
					},
					{ header: '검침개소', name: 'name', align: 'center' },
				],
			});
		},
		// 공정/설비 조회
		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",
					readObjId: this.searchParam.searchReadObj, // "MTT00001" // 전력 코드 고정
					mntrFg: this.mntrFg,
					useFg: '1',
					readPlcNmLike: this.searchWord,
				},
			});

			let myOptionsTree = {
				treeColumnOptions: {
					name: 'readPlcNm',
				},
			};
			if (this.isMulti) {
				myOptionsTree['rowHeaders'] = [{ type: 'checkbox' }];
				myOptionsTree['rowHeight'] = 'auto'; // checkbox와 그리드 높이 같게
				myOptionsTree['treeColumnOptions']['useCascadingCheckbox'] = false;
			}

			this.setWidgetModalGridOption({
				widgetId: this.widGetKey,
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: Object.assign(Utility.defaultGridOption(490), myOptionsTree),
			});

			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.setWidgetModalGridData({
				widgetId: this.widGetKey,
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: setTreeData.ROOT || [],
			});

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

			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],
					);
				}
			}
		},
		getRowData(data) {
			if (this.isMulti) {
				if (data._attributes.checked) {
					this.$refs['treeGrid' + this.parentPrgmId].uncheckEvt(
						data,
						this.$refs['treeGrid' + this.parentPrgmId],
					);
				} else {
					var checkedRowNumber = this.$refs[
						'treeGrid' + this.parentPrgmId
					].getCheckedRowsEvt().length;
					if (checkedRowNumber >= this.maxSelectableNum) {
						alert(
							'최대 ' + this.maxSelectableNum + '개까지 선택할 수 있습니다.',
						);
						return;
					}
					this.$refs['treeGrid' + this.parentPrgmId].checkEvt(
						data,
						this.$refs['treeGrid' + this.parentPrgmId],
					);
				}
			} else {
				this.activeRowData = data;
			}
		},
		setUpdate() {
			if (this.isMulti) {
				this.checkedRowDataList = this.$refs[
					'treeGrid' + this.parentPrgmId
				].getCheckedRowsEvt();
				// this.$store.state.pageData[this.parentPrgmId][this.widGetKey][this.widgetDataKey].selectedReadPlcList = this.checkedRowDataList;
				this.$store.state.pageData[this.parentPrgmId][this.widGetKey][
					this.widgetDataKey
				].plcKindList = this.checkedRowDataList;
			} else {
				this.$store.state.pageData[this.parentPrgmId][this.widGetKey][
					this.widgetDataKey
				].plcKindList = this.activeRowData;
			}
			this.$emit('chDialogView' + this.widGetKey);
			this.dialog = false;
		},
		// 공정/설비 트리 접기/펼치기
		btnTreeExpand() {
			this.treeExpandAll = !this.treeExpandAll;
			if (this.treeExpandAll) {
				this.$refs['treeGrid' + this.parentPrgmId].expandAll();
			} else {
				this.$refs['treeGrid' + this.parentPrgmId].collapseAll();
			}
		},
		typeEnterKey() {
			this.getTreeData();
		},
		reset() {
			for (
				var i = 0;
				i < this.$refs['treeGrid' + this.parentPrgmId].getData().length;
				i++
			) {
				this.$refs['treeGrid' + this.parentPrgmId].uncheckEvt(
					this.$refs['treeGrid' + this.parentPrgmId].getData()[i],
					this.$refs['treeGrid' + this.parentPrgmId],
				);
			}
			this.searchWord = '';
		},
	},
};

const selectReadPlcListTree = {
	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;
	}
}

@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>
