<template>
	<v-row class="search-box" align="center" no-gutters>
		<v-col :cols="4">
			<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-dialog
			ref="popModal"
			v-model="dialog"
			width="700"
			overlay-color="#000"
			overlay-opacity="0.8"
			scrollable
		>
			<v-card style="height: 100%">
				<v-card-title class="pa-5 d-flex align-center justify-space-between">
					<span class="custom-title-4">{{ label }}</span>
					<v-btn icon tile :ripple="false" @click="dialog = false">
						<v-icon>mdi-close</v-icon>
					</v-btn>
				</v-card-title>
				<div class="searchFilter v-card">
					<v-row align="center" no-gutters>
						<v-col :cols="6">
							<component
								:is="'selectSnarEnergy'"
								:parentPrgmId="parentPrgmId"
								:label="'에너지원'"
								:dataKey="'snarEnergyCd'"
								:addAll="true"
								:labelCols="4"
							/>
						</v-col>
						<v-col :cols="5">
							<v-row align="center" no-gutters>
								<v-col cols="4">
									<label 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-row>
							<!-- <InputText
              :parentPrgmId="parentPrgmId"
              label="시나리오명"
              valueNm="snarNm"
              :searchOption="true"
              :labelCols="4"
              :textCols="7"
              /> -->
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="8">
							<DatePicker
								:parentPrgmId="parentPrgmId"
								:label="'실행일자'"
								:labelCols="3"
							/>
						</v-col>
						<v-col :cols="4" class="text-right">
							<v-btn :ripple="false" @click="reset()">초기화</v-btn>
							<v-btn :ripple="false" @click="search()">검색</v-btn>
						</v-col>
					</v-row>
				</div>
				<v-divider></v-divider>
				<div ref="snargridParent" class="py-3" style="height:400px">
					<component
						:ref="gridName + parentPrgmId"
						:is="loadGrid ? 'Grid' : null"
						:dataPath="searchParam.modalData.selectSnarPrgm"
						:parentPrgmId="parentPrgmId"
						:gridName="gridName"
						@getRowsData="getRowData"
					/>
				</div>
				<v-divider></v-divider>
				<v-card-actions>
					<v-spacer></v-spacer>
					<v-btn :ripple="false" @click="setUpdate($event)">확인</v-btn>
					<v-btn :ripple="false" @click="dialog = false">닫기</v-btn>
				</v-card-actions>
			</v-card>
		</v-dialog>
	</v-row>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import DatePicker from '~/components/common/Datepicker';
import Buttons from '~/components/common/button/Buttons';
import Utility from '~/plugins/utility';
import SelectSnarEnergy from '@/components/common/select/SelectSnarEnergy';
import InputText from '@/components/common/input/InputText';
import Grid from '~/components/common/Grid';

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		label: {
			type: String,
			require: true,
		},
	},
	components: {
		InputText,
		DatePicker,
		Buttons,
		Utility,
		SelectSnarEnergy,
		InputText,
		Grid,
	},
	data() {
		return {
			dialog: false,
			myModalKey: 'selectSnarPrgm',
			loadGrid: false,
			gridName: 'snarGrid',
			modalDataKey: 'modalData',
			activeRowData: {},
			checkedRowDataList: [],
			searchWord: '',
		};
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			selectValue() {
				// 선택된 시나리오 값
				const temp = [];
				const snarData = this.searchParam.isMulti
					? this.searchParam.snarInfoList
					: this.searchParam.snarInfo;
				console.log('this.searchParam.isMulti', this.searchParam.isMulti);
				console.log(
					'this.searchParam.snarInfoList',
					this.searchParam.snarInfoList,
				);
				console.log('this.searchParam.snarInfo', this.searchParam.snarInfo);
				if (Array.isArray(snarData)) {
					if (snarData.length > 0) {
						for (const item of snarData) {
							temp.push(item.simulId);
						}
					}
				} else {
					//return snarData.path === undefined ? snarData.simulId : snarData.path;
				}
				return temp.join();
			},
			isDarkMode: 'isDarkMode',
		}),
		chkDialog() {
			return this.dialog;
		},
		chkSnarEnergy() {
			return this.searchParam.snarEnergyCd;
		},
		chkFromDt() {
			// 조회기간 시작일 선택 감지
			return this.searchParam.fromDt;
		},
		chkToDt() {
			// 조회기간 종료일 선택 감지
			return this.searchParam.toDt;
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) this.search();
		},
		async chkSnarEnergy(val) {
			if (val) this.search();
		},
		async chkFromDt(val) {
			if (val) this.search();
		},
		async chkToDt(val) {
			if (val) this.search();
		},
	},
	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData: { selectSnarPrgm },
		});
	},
	created() {
		this.init();
		if (this.searchParam.isMulti == true) {
			this.setPageData({
				snarInfoList:
					localStorage.getItem(this.parentPrgmId + 'CheckedRow') != null
						? JSON.parse(localStorage.getItem(this.parentPrgmId + 'CheckedRow'))
						: {},
			});
		} else {
			this.setPageData({
				snarInfo:
					localStorage.getItem(this.parentPrgmId + 'CheckedRow') != null
						? JSON.parse(localStorage.getItem(this.parentPrgmId + 'CheckedRow'))
						: {},
			});
		}

		// if(this.searchParam.isMulti == true){
		//   this.setPageData({
		//     snarInfoList : 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',
		}),
		search() {
			this.getSnarData();
		},
		init() {
			this.activeRowData = {};
			this.gridInit();
		},
		gridInit() {
			const myOptions = {
				columnOptions: {
					resizable: true,
				},
			};
			const _this = this;
			// const myOptionsSnar = {
			//   snarColumnOptions: {
			//     name: "simulId",
			//     useIcon: true
			//   },
			//   scrollX: true
			// };
			if (this.searchParam.isMulti) {
				myOptions['rowHeaders'] = [{ type: 'checkbox' }];
				myOptions['rowHeight'] = 'auto'; // checkbox와 그리드 높이 같게
				// myOptionsSnar["snarColumnOptions"]["useCascadingCheckbox"] = false;
			}

			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: Object.assign(
					Utility.defaultGridOption(350, myOptions),
					myOptions,
				),
			});

			const myColumnsSnar = [
				{
					header: '실행일자',
					name: 'calcDt',
					align: 'center',
					formatter: dateFormatter,
				},
				{ header: '시나리오명', name: 'snarNm', align: 'center' },
				{ header: '완료여부', name: 'exctFg', align: 'center' },
			];
			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: myColumnsSnar,
			});
		},
		async getSnarData() {
			this.loadGrid = false;
			const res = await this.postApiReturn({
				apiKey: 'selectSimulSlctList',
				resKey: 'selectSimulSlctList',
				sendParam: {
					snarNm: this.searchWord, // 검색키워드: 시나리오명
					ercId: this.searchParam.snarEnergyCd, // 검색키워드: 에너지원
					fromDt: this.searchParam.fromDt, // 검색키워드: 시작일자
					toDt: this.searchParam.toDt, // 검색키워드: 끝일자
				},
			});
			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.gridName,
				modalDataKey: this.modalDataKey,
				value: res,
			});

			//화면 처음 열때 Default 체크 처리
			if (localStorage.getItem(this.parentPrgmId + 'CheckedRow') == null) {
				let temp = [];
				res.filter(item => {
					if (item.mntrFg == 1) {
						temp.push(item);
					}
				});
				this.searchParam.snarInfoList = temp;
			}

			this.loadGrid = true;

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

			if (this.checkedRowDataList.length > 0) {
				if (res.length > 0) {
					for (var i = 0; i < this.checkedRowDataList.length; i++) {
						//if(res[i].simulId == this.checkedRowDataList[i].simulId){
						this.$refs[this.gridName + this.parentPrgmId].checkEvt(
							this.checkedRowDataList[i],
							this.$refs[this.gridName + this.parentPrgmId],
						);
						//}
					}
				}
			}
		},
		getRowData(data) {
			if (this.searchParam.isMulti) {
				if (data._attributes.checked) {
					this.$refs[this.gridName + this.parentPrgmId].uncheckEvt(
						data,
						this.$refs[this.gridName + this.parentPrgmId],
					);
				} else {
					this.$refs[this.gridName + this.parentPrgmId].checkEvt(
						data,
						this.$refs[this.gridName + this.parentPrgmId],
					);
				}
			} else {
				this.activeRowData = data;
			}
		},
		setUpdate() {
			if (this.searchParam.isMulti) {
				this.checkedRowDataList = this.$refs[
					this.gridName + this.parentPrgmId
				].getCheckedRowsEvt();
				if (this.checkedRowDataList.length < 20) {
					this.dialog = false;
					this.setPageData({ snarInfoList: this.checkedRowDataList });
					this.setPageData({ snarInfoListSearch: this.checkedRowDataList });
				} else {
					alert('선택 목록이 20개를 초과하였습니다.');
				}
			} else {
				this.dialog = false;
				this.setPageData({ snarinfo: this.activeRowData });
				localStorage.setItem(
					this.parentPrgmId + 'CheckedRow',
					JSON.stringify(this.searchParam.simulId),
				);
			}
		},
		reset() {
			for (
				var i = 0;
				i < this.$refs[this.gridName + this.parentPrgmId].getData().length;
				i++
			) {
				this.$refs[this.gridName + this.parentPrgmId].uncheckEvt(
					this.$refs[this.gridName + this.parentPrgmId].getData()[i],
					this.$refs[this.gridName + this.parentPrgmId],
				);
			}
		},
		typeEnterKey() {
			this.search();
		},
	},
};
const selectSnarPrgm = {
	snarGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
	},
};

function dateFormatter({ value }) {
	return Utility.setFormatDate(value, 'YYYY-MM-DD');
}
</script>

<style scoped lang="scss">
@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>
