<template>
	<v-row class="search-box" align="center" no-gutters>
		<!-- <v-col v-if="label" cols="2"> -->
		<v-col v-if="item.label" :cols="item.labelCols" class="py-0">
			<label for="" class="search-box-label">
				<v-icon v-if="item.iconShow" small
					:class="['mr-1', item.required ? 'icon-orange' : 'icon-blue']">$icoBulletPoint</v-icon>
				{{ item.label }}
			</label>
		</v-col>
		<v-col :cols="item.label ? item.textCols : ''" class="py-0">
			<!-- <v-col :cols="label ? 9 : ''"> -->
			<!-- :value="textfield" -->
			<v-text-field readonly v-model="selectValue" append-icon="" class="v-input__custom"
				@click="dialog = !dialog" outlined :hide-details="true" :disabled="item.disabled || false"
				:required="item.required || false"><template v-slot:append>
					<!-- Custom SVG icon -->
					<v-icon>$icoSearch</v-icon>


				</template></v-text-field>
		</v-col>

		<!-- <v-row justify="center"> -->
		<v-dialog v-model="dialog" width="800px" scrollable>
			<!-- <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 class="px-6 py-4 d-flex align-center justify-space-between">
					<span class="custom-title-4">{{ item.label }}</span>
					<a-button icon="close" type="text" @click="dialog = false"></a-button>
				</v-card-title>
				<!-- <v-card-actions> -->
				<div class="pa-6 pt-0">
					<!-- <v-text-field label="위치정보 선택"></v-text-field> -->
					<v-row align="center">
						<v-col v-if="label" cols="12" class="py-0">
							<label for="" class="search-box-label">
								<v-icon small :class="['mr-1', 'icon-blue']">$icoBulletPoint</v-icon>
								{{ item.label }}
							</label>
						</v-col>
						<v-col :cols="label ? 8 : ''" class="py-0">
							<!-- :value="textfield" -->
							<v-text-field append-icon="" class="v-input__custom" outlined :hide-details="true"
								v-model="searchWord" @keyup.enter="typeEnterKey"><template v-slot:append>
									<!-- Custom SVG icon -->
									<v-icon>$icoSearch</v-icon>


								</template></v-text-field>
						</v-col>
						<!-- <v-spacer></v-spacer> -->
						<v-col cols="2" class="text-right">
							<a-button icon="search" type="primary" @click="search()" class="search-button">조회</a-button>

							<!-- <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="reset()">초기화</v-btn>
              <v-btn v-if="!searchParam.isMulti" :ripple="false" @click="search()">검색</v-btn> -->
							<!-- as-is 롤 봐도 초기화가 하는 기능을 모르겠음.. -->
						</v-col>
						<v-col cols="2" class="text-right"><a-button class="expand-btn" :ripple="false" @click="btnTreeExpand()">
								<v-icon small>$icoExpandAlt</v-icon>
								Expand All
							</a-button></v-col>
					</v-row>
					
					<!-- <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 롤 봐도 초기화가 하는 기능을 모르겠음.. -->
				</div>

				<v-card-text>
					<div ref="treeGridParent" style="height: 450px">
						<component :ref="'treeGrid' + parentPrgmId" :is="loadGrid && dialog ? 'Grid' : null"
							:gridName="gridNameTree" :dataPath="searchParam.modalData.selectReadObjListTree"
							:parentPrgmId="parentPrgmId" :bindingData="bindingData" @getRowsData="getRowData"
							@dblClick="setUpdate()" />
					</div>
					<!-- <component
            :is="ftnPlcListTreeData.length > 0 ? 'Tree' : null"
            :tree-data="ftnPlcListTreeData"
          /> -->
				</v-card-text>

				<v-card-actions class="px-6 py-4 d-flex align-center justify-end">
					<a-button :ripple="false" @click="dialog = false" class="mr-2">닫기</a-button>
					<a-button :ripple="false" type="primary" @click="setUpdate($event)">확인</a-button>
				</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: false,
			default: '검침개소',
		},
		valueNm: {
			type: String,
			require: false,
			default: '',
		},
		title: {
			type: String,
			require: false,
			default: '검침대상 목록',
		},
		labelCols: {
			type: Number,
			require: false,
			default: 4,
		},
		textCols: {
			type: Number,
			require: false,
			default: 7,
		},
		item: {
			type: Object,
			require: true,
		},
		bindingData: {
			type: String,
			require: false,
		},
	},
	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];
			},
			myBindingData(state) {
				//return state.pageData[this.parentPrgmId]["rowGridSelectData"];
				if (!this.bindingData) {
					return state.pageData[this.parentPrgmId]['rowGridSelectData'];
				} else {
					return state.pageData[this.parentPrgmId][this.bindingData][
						'rowGridSelectData'
					];
				}
			},
			rowGridSelectData(state) {
				if (!this.bindingData) {
					return state.pageData[this.parentPrgmId].rowGridSelectData;
				} else {
					return state.pageData[this.parentPrgmId][this.bindingData]
						.rowGridSelectData;
				}
			},
		}),
		chkDialog() {
			// 모달 열기/닫기 값
			return this.dialog;
		},
		selectValue: {
			get() {
				// if(this.searchParam.rowGridSelectData){
				//     return this.searchParam.rowGridSelectData[this.item.valueNm];
				// }
				return this.myBindingData ? this.myBindingData[this.item.valueNm] : '';
			},
			set(value) {
				// return value;
				// return this.myBindingData({ [this.item.valueNm]: value });
				//return this.setPageData({ [this.item.valueNm]: value });
				return this.myBindingData({ [this.item.valueNm]: value });
			},
		},
		treeExpand() {
			return this.treeExpandAll ? '접기' : '펼치기';
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				await this.getTreeData();
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData: { selectReadObjListTree },
		});
	},
	created() {
		this.init();
		// if(this.searchParam.isMulti == true){
		//   this.setPageData({
		//     facInfoList : localStorage.getItem(this.parentPrgmId + "CheckedRow") !=null ? JSON.parse(localStorage.getItem(this.parentPrgmId + "CheckedRow")) : {}
		//   });
		// }else{
		//   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() {
			this.activeRowData = {};
			this.gridInit();
		},
		// 공정/설비 트리 그리드 세팅
		gridInit() {
			const treeGridHeight = 490;
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				value: [
					{
						header: '',
						name: '',
						align: 'center',
						width: 20,
						formatter: (props) => {
							return `<label class="custom-radio">
										<span class="radio-mark"></span>
									</label>`;
						}
					},
					{
						header: '검침개소명',
						name: 'readPlcNm',
						width: 500,
						align: 'left',
					},
					{ header: '검침개소', name: 'name', align: 'left', width: 200 },
				],
			});
		},
		// 공정/설비 조회
		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.readObj, // "MTT00001" // 전력 코드 고정
					readObjId: this.searchParam.searchReadObj, // "MTT00001" // 전력 코드 고정

					useFg: '1',
					readPlcNmLike: this.searchWord,
				},
			});

			// console.log("treeData", res)
			let myOptionsTree = {
				columnOptions: {
					resizable: true,
				},
				treeColumnOptions: {
					name: 'readPlcNm',
				},
				header: {
					height: 37,
				},
				rowHeight: 'auto',
			};
			if (this.searchParam.isMulti) {
				myOptionsTree['rowHeaders'] = [{ type: 'checkbox' }];
				myOptionsTree['rowHeight'] = 'auto'; // checkbox와 그리드 높이 같게
				myOptionsTree['treeColumnOptions']['useCascadingCheckbox'] = false;
			}

			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridNameTree,
				modalDataKey: this.modalDataKey,
				// value: myOptionsTree
				value: Object.assign(Utility.defaultGridOption(490), 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 || [],
			});
			this.loadGrid = true;

			this.$nextTick(() => {
				if (this.searchParam.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],
					);
				}
			}
		},
		// 공정/설비 트리 row 클릭이벤트
		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 {
				this.dialog = false;
				const dt = {
					columnName: this.item.valueNm,
					value: this.activeRowData.name,
				};
				var nm = this.item.valueNm;

				if (this.item.valueNm2 !== undefined) {
					const dt = {
						columnName: this.item.valueNm2,
						value: this.activeRowData[this.item.valueNm2],
					};
					this.$emit('gridEditingFinish', dt);
				}

				if (nm == 'objReadPlcId') {
					this.myBindingData.objReadPlcId = this.activeRowData.name;
					this.myBindingData.objReadPlcNm = this.activeRowData.readPlcNm;
					const dt2 = {
						columnName: 'objReadPlcNm',
						value: this.activeRowData.readPlcNm,
					};
					this.$emit('gridEditingFinish', dt2);
				} else if (nm == 'readPlcId') {
					this.myBindingData.readPlcId = this.activeRowData.name;
					this.myBindingData.readPlcNm = this.activeRowData.readPlcNm;
				} else if (nm == 'upReadPlcId') {
					this.myBindingData.upReadPlcId = this.activeRowData.name;
					this.myBindingData.upReadPlcNm = this.activeRowData.readPlcNm;
				} else {
					this.myBindingData.upReadPlcId = this.activeRowData.name;
					if (this.item.bindNm) {
						this.myBindingData[this.item.bindNm] = this.activeRowData.readPlcNm;
						var bindDt = {
							columnName: this.item.bindNm,
							value: this.activeRowData.readPlcNm,
						};
						this.$emit('gridEditingFinish', bindDt);
					}
				}
				this.$emit('gridEditingFinish', dt);
			}
		},
		// 공정/설비 트리 접기/펼치기
		btnTreeExpand() {
			this.treeExpandAll = !this.treeExpandAll;
			if (this.treeExpandAll) {
				this.$refs['treeGrid' + this.parentPrgmId].expandAll();
			} else {
				this.$refs['treeGrid' + this.parentPrgmId].collapseAll();
			}
		},
		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;
	}
}

</style>
