<template>
	<v-row class="search-box" align="center" no-gutters>
		<!-- <v-col v-if="label" cols="2"> -->
		<v-col v-if="label" :cols="item.labelCols">
			<!-- <label for="" class="search-box-label">
				<v-icon
					x-small
					:color="item.required ? '#fb8200' : 'primary'"
					class="mr-1"
					>mdi-record-circle</v-icon
				>
				{{ item.label }}
			</label> -->
			<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="label ? item.textCols : ''" class="py-0">
			<!-- <v-col :cols="label ? 9 : ''"> -->
			<!-- :value="textfield" -->
			<v-text-field
				readonly
				v-model="selectValue"
				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
			ref="popModal"
			v-model="dialog"
			width="900"
			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 style="height: 100%">
				<v-card-title
					class="v-card__title d-flex align-center justify-space-between"
				>
					<span class="custom-title-4">{{ item.label }}</span>
					<v-btn icon tile :ripple="false" @click="dialog = !dialog">
						<v-icon>mdi-close</v-icon>
					</v-btn>
				</v-card-title>
				<!-- <v-card-actions> -->
				<div class="pa-5">
					<!-- <v-text-field label="위치정보 선택"></v-text-field> -->
					<v-row align="center" no-gutters>
						<v-col :cols="label ? 3 : ''" class="pr-3" >
							<component
								:is="'selectCodeList'"
								:parentPrgmId="parentPrgmId"
								:label="'계약구분'"
								dataKey="searchElecContKind"
								:sendParam="{ commGrpCd: 'EM_CONT', useFg: '1' }"
								:addAll="true"
								:customClass="'select-large'"
							/>
						</v-col>
						<v-col :cols="label ? 3 : ''" class="pr-3" >
							<component
								:is="'selectCodeList'"
								:parentPrgmId="parentPrgmId"
								:label="'전압구분'"
								dataKey="searchVoltKind"
								:sendParam="{ commGrpCd: 'EM_VOLT_KIND', useFg: '1' }"
								:customClass="'select-large'"
								:addAll="true"
							/>
						</v-col>
						<v-col :cols="label ? 3 : ''" class="pr-3" >
							<component
								:is="'selectCodeList'"
								:parentPrgmId="parentPrgmId"
								:label="'전압구분'"
								dataKey="searchOptKind"
								:sendParam="{ commGrpCd: 'EM_VOLT_OPT', useFg: '1' }"
								:customClass="'select-large'"
								:addAll="true"
							/>
						</v-col>
						<v-col cols="3" class="text-right">
							<div style="height: 25px"></div>
							<!-- <v-btn
								v-if="!searchParam.isMulti"
								:ripple="false"
								@click="search()"
								>검색</v-btn
							> -->
							<a-button
								v-if="!searchParam.isMulti"
								type="primary"
								class="mr-1"
								icon="search"
								:ripple="false"
								@click="search"
								style="height: 40px"
							>
								검색
							</a-button>
							<!-- <v-btn
								v-if="!searchParam.isMulti"
								:ripple="false"
								@click="initVal()"
								>초기화</v-btn
							> -->
							<a-button
								v-if="!searchParam.isMulti"
								type="primary"
								class="mr-1"
								:ripple="false"
								@click="initVal"
								style="height: 40px"
							>
								초기화
							</a-button>
						</v-col>
					</v-row>
				</div>
				<v-divider></v-divider>
				<v-card-text>
					<div id="gridParent" ref="gridParent" style="height: 500px">
						<component
							:ref="'gridName' + parentPrgmId"
							:is="loadGrid && dialog ? 'Grid' : null"
							:gridName="gridName"
							:dataPath="searchParam.modalData2.selectElecPowChrgPopList"
							:parentPrgmId="parentPrgmId"
							:bindingData="bindingData"
							@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';
import selectCodeList from '@/components/common/select/selectCodeList';

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

			myModalKey: 'selectElecPowChrgPopList',
			gridName: 'rowElecContGrid',
			loadGrid: false,

			dialog: false,
			modalDataKey: 'modalData2',
			activeRowData: {},
			checkedRowDataList: [],
		};
	},
	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;
		},
		chkElecContKind() {
			return this.searchParam.searchElecContKind;
		},
		chkVoltKind() {
			return this.searchParam.searchVoltKind;
		},
		chkOptKind() {
			return this.searchParam.searchOptKind;
		},
		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 });
			},
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				await this.getData();
			} else {
				this.searchParam.searchElecContKind = '';
				this.searchParam.searchVoltKind = '';
				this.searchParam.searchOptKind = '';
			}
		},
		chkElecContKind() {
			if (this.dialog) {
				this.getData();
			}
		},
		chkVoltKind() {
			if (this.dialog) {
				this.getData();
			}
		},
		chkOptKind() {
			if (this.dialog) {
				this.getData();
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData2: { selectElecPowChrgPopList },
		});
	},
	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',
		}),
		init() {
			this.activeRowData = {};
			this.gridInit();
		},
		// 공정/설비 트리 그리드 세팅
		gridInit() {
			const myOptions = {
				header: {
					height: 38,
				},
			};
			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				// value: myOptionsTree
				value: Object.assign(Utility.defaultGridOption(490), myOptions),
			});
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: myColumns,
			});
		},
		// 계약 정보 조회
		async getData() {
			this.loadGrid = false;
			let res = [];
			res = await this.postApiReturn({
				apiKey: 'selectElecPowChrgInfo',
				resKey: 'elecPowChrgInfoData',
				sendParam: {
					elecContKind: this.searchParam.searchElecContKind,
					voltKind: this.searchParam.searchVoltKind,
					optKind: this.searchParam.searchOptKind,
				},
			});
			// function setRowSpanAttribute(
			// 	res,
			// 	targetAttributeName,
			// 	targetAttributeList,
			// ) {
			// 	if (!(res.length && res.length >= 1)) {
			// 		return;
			// 	}

			// 	if (targetAttributeList == undefined) {
			// 		var currentCnt = 1;
			// 		var currentIdx = 0;
			// 		var currentValue = res[0][targetAttributeName];
			// 		for (var i = 1; i < res.length; i++) {
			// 			if (res[i][targetAttributeName] != currentValue) {
			// 				if (res[currentIdx]['_attributes'] == undefined) {
			// 					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
			// 					//추가용
			// 					res[currentIdx]['_attributes']['className'] = {column:new Object()};
			// 					//추가용
								
			// 				}
			// 				res[currentIdx]['_attributes']['rowSpan'][
			// 					targetAttributeName
			// 				] = currentCnt;
			// 				//추가용							
			// 				res[currentIdx]['_attributes']['className']['column'][targetAttributeName] = ['rowSpan-done'];
			// 				//추가용
							

			// 				currentValue = res[i][targetAttributeName];
			// 				currentCnt = 1;
			// 				currentIdx = i;
			// 			} else if (
			// 				res[i][targetAttributeName] == currentValue &&
			// 				i == res.length - 1
			// 			) {
			// 				currentCnt = currentCnt + 1;
			// 				if (res[currentIdx]['_attributes'] == undefined) {
			// 					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
			// 					//추가용
			// 					res[currentIdx]['_attributes']['className'] = {column:new Object()};
			// 					//추가용
			// 				}
			// 				res[currentIdx]['_attributes']['rowSpan'][
			// 					targetAttributeName
			// 				] = currentCnt;
			// 				//추가용
			// 				res[currentIdx]['_attributes']['className']['column'][targetAttributeName] = ['rowSpan-done'];
			// 				//추가용
			// 			} else {
			// 				currentCnt = currentCnt + 1;
			// 			}
			// 		}
			// 	} else {
			// 		var currentCnt = 1;
			// 		var currentIdx = 0;
			// 		for (var i = 1; i < res.length; i++) {
			// 			if (!compareValue(res, targetAttributeList, currentIdx, i)) {
			// 				if (res[currentIdx]['_attributes'] == undefined) {
			// 					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
			// 					//추가용
			// 					res[currentIdx]['_attributes']['className'] = {column:new Object()};
			// 					//추가용
			// 				}
			// 				if (currentCnt != 1) {
			// 					res[currentIdx]['_attributes']['rowSpan'][
			// 						targetAttributeName
			// 					] = currentCnt;
			// 					//추가용
			// 					res[currentIdx]['_attributes']['className']['column'][targetAttributeName] = ['rowSpan-done'];
			// 					//추가용
			// 				}
			// 				currentCnt = 1;
			// 				currentIdx = i;
			// 			} else if (
			// 				compareValue(res, targetAttributeList, currentIdx, i) &&
			// 				i == res.length - 1
			// 			) {
			// 				currentCnt = currentCnt + 1;
			// 				if (res[currentIdx]['_attributes'] == undefined) {
			// 					res[currentIdx]['_attributes'] = { rowSpan: new Object() };
			// 					//추가용
			// 					res[currentIdx]['_attributes']['className'] = {column:new Object()};
			// 					//추가용
			// 				}
			// 				if (currentCnt != 1) {
			// 					res[currentIdx]['_attributes']['rowSpan'][
			// 						targetAttributeName
			// 					] = currentCnt;
			// 					//추가용
			// 					res[currentIdx]['_attributes']['className']['column'][targetAttributeName] = ['rowSpan-done'];
			// 					//추가용
			// 				}
			// 			} else {
			// 				currentCnt = currentCnt + 1;
			// 			}
			// 		}
			// 	}
			// 	function compareValue(res, targetAttributeList, currentIdx, targetIdx) {
			// 		for (var i = 0; i < targetAttributeList.length; i++) {
			// 			if (
			// 				res[currentIdx][targetAttributeList[i]] !=
			// 				res[targetIdx][targetAttributeList[i]]
			// 			) {
			// 				return false;
			// 			}
			// 		}
			// 		return true;
			// 	}
			// }
			// setRowSpanAttribute(res, 'elecContKindNm');
			// setRowSpanAttribute(res, 'voltKindNm');
			// setRowSpanAttribute(res, 'optKindNm');
			// setRowSpanAttribute(res, 'baseChrg');

			function setRowSpanAttribute(
				separateColStandardList,
				res,
				targetAttributeName,
				rowSpanList
			) {
				if (!(res.length && res.length >= 2)) {
					return;
				}
				var valueList = [];
				var rowSpanValueList = [];
				var currentIdx = 0;
				for (var i = 0; i < res.length; i++) {
					valueList.push(res[i][targetAttributeName]);
				}

				function makeCurrentSeparateVal(idx, separateColStandardList) {
					let returnVal = '';
					for (var i = 0; i < separateColStandardList.length; i++) {
						returnVal += res[idx][separateColStandardList[i]];
					}
					return returnVal;
				}

				let beforeSeparateVal = makeCurrentSeparateVal(
					0,
					separateColStandardList,
				);
				rowSpanValueList[0] = [valueList[0], 1, currentIdx];
				for (var i = 1; i < valueList.length; i++) {
					currentIdx += 1;
					let currentSeparateVal = makeCurrentSeparateVal(
						i,
						separateColStandardList,
					);
					if (
						currentSeparateVal == beforeSeparateVal &&
						valueList[i] == rowSpanValueList[rowSpanValueList.length - 1][0]
					) {
						rowSpanValueList[rowSpanValueList.length - 1][1] += 1;
					} else {
						rowSpanValueList[rowSpanValueList.length] = [
							valueList[i],
							1,
							currentIdx,
						];
						beforeSeparateVal = currentSeparateVal;
					}
				}

				for (var i = 0; i < rowSpanValueList.length; i++) {
					if (rowSpanValueList[i][1] === 1) {
						continue;
					}
					if (res[rowSpanValueList[i][2]]['_attributes'] == undefined) {
						res[rowSpanValueList[i][2]]['_attributes'] = {
							rowSpan: new Object(),
						};
						//추가용
						res[rowSpanValueList[i][2]]['_attributes']['className'] = {column:new Object()};
						for(var j=0; j<rowSpanList.length; j++){
							res[rowSpanValueList[i][2]]['_attributes']['className']['column'][rowSpanList[j]] = ['colrowspan'];
						}
						//추가용
					}
					res[rowSpanValueList[i][2]]['_attributes']['rowSpan'][
						targetAttributeName
					] = rowSpanValueList[i][1];
					res[rowSpanValueList[i][2]]['_attributes']['className']['column'][targetAttributeName].push(['rowrowspan']);
					
				}
			}
			// rowSpanList 합쳐지는 row colNm을 넣어야 함
			let rowSpanList = ['elecContKindNm', 'voltKindNm', 'optKindNm', 'baseChrg'];
			setRowSpanAttribute(['elecContKindNm'], res, 'elecContKindNm', rowSpanList);
			setRowSpanAttribute(['elecContKindNm'], res, 'voltKindNm', rowSpanList);
			setRowSpanAttribute(['elecContKindNm'], res, 'optKindNm', rowSpanList);
			setRowSpanAttribute(['elecContKindNm'], res, 'baseChrg', rowSpanList);

			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: res,
			});
			this.loadGrid = true;
		},
		async getRowData(data) {
			this.activeRowData = data;
		},
		setUpdate() {
			if (this.searchParam.isMulti) {
				// 멀티 처리 필요사 시용...
				// this.checkedRowDataList = this
			} else {
				this.dialog = false;
				var nm = this.item.valueNm;
				if (nm == 'elecContId') {
					this.myBindingData.elecContId = this.activeRowData.eleclContId;
					this.myBindingData.elecContNm = this.activeRowData.eleclContNm;
					const dt1 = {
						columnName: 'elecContId',
						value: this.activeRowData.eleclContId,
					};
					const dt2 = {
						columnName: 'elecContNm',
						value: this.activeRowData.eleclContNm,
					};
					this.$emit('gridEditingFinish', dt1);
					this.$emit('gridEditingFinish', dt2);
				}
			}
		},
		initVal() {
			this.dialog = false;
			var nm = this.item.valueNm;
			if (nm == 'elecContId') {
				this.myBindingData.elecContId = '';
				this.myBindingData.elecContNm = '';
				const dt1 = {
					columnName: 'elecContId',
					value: '',
				};
				const dt2 = {
					columnName: 'elecContNm',
					value: '',
				};
				this.$emit('gridEditingFinish', dt1);
				this.$emit('gridEditingFinish', dt2);
			}
		},
		search() {
			this.getData();
		},
	},
};

document.querySelector("#gridParent > div > div > div.tui-grid-content-area > div.tui-grid-rside-area > div.tui-grid-body-area > div > div.tui-grid-table-container > table > tbody > tr.tui-grid-row-odd.tui-grid-cell-current-row")


const selectElecPowChrgPopList = {
	rowElecContGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
	},
};

const myColumns = [
	{ header: '전력계약 ID', name: 'eleclContId', hidden: true},
	{ header: '전력계약 명', name: 'eleclContNm', hidden: true},
	{ header: '전력계약구분CD', name: 'elecContKind', hidden: true},
	{ header: '전력계약구분', name: 'elecContKindNm', align: 'left'},
	{ header: '전압구분CD', name: 'voltKind', hidden: true },
	{ header: '전압구분', name: 'voltKindNm', align: 'left' },
	{ header: '옵션CD', name: 'optKind', hidden: true },
	{ header: '옵션', name: 'optKindNm', align: 'left' },
	{
		header: '기본요금(원/kW)',
		name: 'baseChrg',
		align: 'right',
		formatter({ value }) {
			return Utility.setFormatInt(value);
		},
	},
	{ header: '시간대CD', name: 'peakKind', hidden: true },
	{ header: '시간대', name: 'peakKindNm', align: 'left' },
	{
		header: '여름철(6~8월)',
		name: 'unitPrcSum',
		align: 'right',
		formatter({ value }) {
			return Utility.setFormatIntDecimal(value, 1);
		},
	},
	{
		header: '봄·가을철(3~5,9~10월)',
		name: 'unitPrcSprfal',
		align: 'right',
		formatter({ value }) {
			return Utility.setFormatIntDecimal(value, 1);
		},
	},
	{
		header: '겨울철(11~2월)',
		name: 'unitPrcWin',
		align: 'right',
		formatter({ value }) {
			return Utility.setFormatIntDecimal(value, 1);
		},
	},
];
// 전력량 요금(원/kWh)
</script>

<style lang="scss" scoped>
@each $theme in dark, light {
	.v-application.#{$theme}-mode {
		.tui-grid {
			&-row-odd,
			&-row-even {					
				&:hover > .colrowspan{
						background-color: map-deep-get(
							$config,
							#{$theme},
							"tui-grid-cell-backgroundColor"
						)!important;

						.tui-grid-cell-content {
							color: map-deep-get($config, #{$theme}, "activate")!important;
						}
						
					}
			}
			&-cell{
				&.row-selected.colrowspan{
					background-color: map-deep-get(
						$config,
						#{$theme},
						"tui-grid-cell-backgroundColor"
					)!important;

					.tui-grid-cell-content {
						color: map-deep-get($config, #{$theme}, "activate")!important;
					}
				}	
			}
		}
	}
}
</style>