<template>
	<v-row v-if="!item.showValue" class="search-box" align="center">
		<v-col 
			:cols="option.labelCols" 
			:style="item.padding ? 'padding-left:10px' : ''" 
			class="py-0">
			<label for="" class="search-box-label">
				<v-icon
					x-small
					:color="item.required ? '#fb8200' : 'primary'"
					class="mr-1"
					>mdi-record-circle</v-icon
				>
				{{ option.labelContent }}
			</label>
		</v-col>
		<v-col :cols="option.textCols" class="d-flex flex-column" style="gap: 4px">
			<v-text-field
				readonly
				v-model="selectValue"
				append-icon="mdi-magnify"
				class="v-input__custom"
				@click="dialogOpenCloseEvent(dialog)"
				outlined
				:hide-details="true"
			></v-text-field>

			<v-text-field
				v-model="InputValue"
				class="v-input__custom"
				outlined
				:type="item.inputType || 'text'"
				:min="item.min || ''"
				:max="item.max || ''"
				:onkeyup="item.onkeyup || ''"
				:onkeydown="item.onkeydown || ''"
				:hide-details="true"
				:disabled="
					item.disabled ||
						(item.elseDisabled &&
							myBindingData &&
							item.elseDisabled !== myBindingData.rowStat) ||
						disabledCondition ||
						false
				"
				:readonly="
					item.readonly ||
						(item.elseReadonly &&
							myBindingData &&
							item.elseReadonly !== myBindingData.rowStat) ||
						readonlyCondition ||
						false
				"
				:required="item.required || false"
				:placeholder="item.placeholder"
				@input="modifyValue($event, item.valueNm)"
				@click="onClick($event, item, item.valueNm)"
			></v-text-field>
		</v-col>

		<v-dialog v-model="dialog" scrollable width="700px">
			<v-card style="height: 100%">
				<v-card-title class="pa-5 d-flex align-center justify-space-between">
					<span class="custom-title-4">{{ option.modalTitle }}</span>
					<v-btn
						icon
						tile
						:ripple="false"
						@click="dialogOpenCloseEvent(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="3">
							<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="5">
							<v-text-field
								append-icon="mdi-magnify"
								class="v-input__custom"
								outlined
								:hide-details="true"
								v-model="searchWord"
								@keyup.enter="search"
							></v-text-field>
						</v-col>
						<v-spacer></v-spacer>
						<v-col cols="4" class="text-right">
							<v-btn :ripple="false" @click="search()">
								조회
							</v-btn>
							<v-btn :ripple="false" @click="initSearch()">
								초기화
							</v-btn>
						</v-col>
					</v-row>
				</div>
				<v-divider></v-divider>
				<!-- <div :style="'height: calc(65vh)'"> -->
					<div :style="'height: 429px;'">
					<!-- <div :style="{ height: 'calc(100% - 213px)' }"> -->
					<div ref="modalGridParent" class="h100 w100 py-3">
						<!-- <component
							:is="loadGrid && dialog ? 'Grid' : null"
							:gridName="grid_01"
							:dataPath="searchParam.modalData3.FtnPlcFormPop"
							:parentPrgmId="parentPrgmId"
							@getRowsData="getRowData"
							@dblClick="setUpdate($event)"
						/> -->
						<a-table :columns="columns" :dataSource="filteredData" rowKey="id" :rowSelection="rowSelection" bordered />

					</div>
				</div>
				<v-card-actions class="pa-5 d-flex align-center justify-center">
					<v-btn :ripple="false" @click="setUpdate($event)">확인</v-btn>
					<v-btn :ripple="false" @click="dialogOpenCloseEvent(dialog)"
						>닫기</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,
		},
		labelCols: {
			type: Number,
			require: false,
			default: 4,
		},
		labelContent: {
			type: String,
			require: false,
			default: '공정',
		},
		textCols: {
			type: Number,
			require: false,
			default: 7,
		},
		modalTitle: {
			type: String,
			require: false,
			default: '공정',
		},
		modalContent: {
			type: String,
			require: false,
			default: '검색',
		},
		item: {
			type: Object,
			require: false,
		},
		bindingData: {
			type: String,
			require: false,
		},
	},
	components: {
		Grid,
		Utility,
	},
	data() {
		return {
			dialog: true,
			loadGrid: true,
			grid_01: 'grid_01',
			myModalKey: 'FtnPlcFormPop',
			modalDataKey: 'modalData3',

			searchWord: '',
			selectedData: {},
			textFieldData: '',

			option: {
				labelCols:
					this.item !== undefined
						? this.item.labelCols !== undefined
							? this.item.labelCols
							: this.labelCols
						: this.labelCols,
				labelContent:
					this.item !== undefined
						? this.item.labelContent !== undefined
							? this.item.labelContent
							: this.labelContent
						: this.labelContent,
				textCols:
					this.item !== undefined
						? this.item.textCols !== undefined
							? this.item.textCols
							: this.textCols
						: this.textCols,
				modalTitle:
					this.item !== undefined
						? this.item.modalTitle !== undefined
							? this.item.modalTitle
							: this.modalTitle
						: this.modalTitle,
			},
			columns: [
				{
					title: 'FAB',
					dataIndex: 'fab',
					key: 'fab',
				},
				{
					title: '설비명',
					dataIndex: 'equipmentName',
					key: 'equipmentName',
				},
			],
			data: [
				{
					id: 1,
					fab: 'FAB001',
					equipmentId: 'EQ001',
					equipmentName: '냉각기 A',
				},
				{
					id: 2,
					fab: 'FAB002',
					equipmentId: 'EQ002',
					equipmentName: '펌프 B',
				},
				{
					id: 3,
					fab: 'FAB003',
					equipmentId: 'EQ003',
					equipmentName: '히터 C',
				},
				{
					id: 4,
					fab: 'FAB001',
					equipmentId: 'EQ004',
					equipmentName: '냉각기 D',
				},
				{
					id: 5,
					fab: 'FAB002',
					equipmentId: 'EQ005',
					equipmentName: '펌프 E',
				},
				{
					id: 6,
					fab: 'FAB003',
					equipmentId: 'EQ006',
					equipmentName: '히터 F',
				},
			],
			filteredData: [],
			rowSelection: {
				onChange: (selectedRowKeys, selectedRows) => {
					// console.log('Selected Row Keys:', selectedRowKeys);
					// console.log('Selected Rows:', selectedRows);
				},
			}
		};
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			myBindingData(state) {
				if (!this.bindingData) {
					return state.pageData[this.parentPrgmId]['rowGridSelectData'];
				} else {
					return state.pageData[this.parentPrgmId][this.bindingData][
						'rowGridSelectData'
					];
				}
			},
		}),
		InputValue: {
			get() {
				// console.log(this.myBindingData);
				return this.myBindingData ? this.myBindingData[this.item.valueNm] : ' ';
			},
			set(value) {
				this.$emit('getValue', {
					key: this.item.valueNm,
					value: value,
				});
				return this.newValue(value);
			},
		},
		disabledCondition() {
			if (this.myBindingData && this.item.disabledCondition) {
				let isDisabled = false;
				this.item.disabledCondition.forEach(condition => {
					if (this.myBindingData[condition.dataKey] == condition.value) {
						isDisabled = true;
					}
				});
				return isDisabled;
			} else {
				return false;
			}
		},
		readonlyCondition() {
			if (this.myBindingData && this.item.readonlyCondition) {
				let isReadonly = false;
				this.item.readonlyCondition.forEach(condition => {
					if (this.myBindingData[condition.dataKey] == condition.value) {
						isReadonly = true;
					}
				});
				return isReadonly;
			} else {
				return false;
			}
		},
		selectValue: {
			get() {
				if (!this.item) {
					return this.textFieldData;
				}
				// else if(this.item.disableContent){
				//   return "NONE";
				// }
				else {
					return this.myBindingData
						? this.myBindingData[this.item.valueNm]
						: this.textFieldData;
				}
			},
			set(value) {
				// if(this.item && this.item.disableContent){
				//   return "NONE";
				// }
				return value;
			},
		},
	},
	watch: {
		async dialog(val) {
			if (val) {
				await this.getGridData();
			}
		},
	},

	beforeCreate() {
		this.$store.commit('setPageData', {
			modalData3: { FtnPlcFormPop },
		});
	},
	created() {
		this.init();
	},
	mounted() {},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setModalGridData: 'setModalGridData',
			setModalGridColumn: 'setModalGridColumn',
			setModalGridOption: 'setModalGridOption',
		}),
		...mapActions({
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
		}),
		init() {
			this.gridInit();
			this.filteredData = this.data;
		},
		search() {
			this.getGridData();
		},
		initSearch() {
			this.searchWord = '';
			this.getGridData();
		},
		gridInit() {
			let myOptions = {
				treeColumnOptions: {
					name: 'eccNm',
					useIcon: true,
				},
				scrollX: false,
			};
			this.setModalGridOption({
				modalKey: this.myModalKey,
				gridKey: this.grid_01,
				modalDataKey: this.modalDataKey,
				value: Object.assign(
					// Utility.defaultGridOption(this.$refs.modalGridParent.offsetHeight - 60, myOptions),
					Utility.defaultGridOption(390, myOptions),
					myOptions,
				),
			});

			this.setModalGridColumn({
				modalKey: this.myModalKey,
				gridKey: this.grid_01,
				modalDataKey: this.modalDataKey,
				value: [{ header: '위치정보', name: 'eccNm' }],
			});
		},
		async getGridData() {
			this.loadGrid = false;

			const res = await this.postApiReturn({
				apiKey: 'selectEccBaseInfo',
				resKey: 'eccBaseInfoData',
				sendParam: {
					blocId: this.myBindingData.blocId,
					eqpmYn: '0',
					search: this.searchWord,
				},
			});

			const setTreeData = await this.setTree({
				gridKey: this.gridNameTree,
				treeKey: 'ECC_ID',
				value: res.map(item => ({
					...item,
					eccNm: item.eccNm,
				})),
			});

			this.setModalGridData({
				modalKey: this.myModalKey,
				gridKey: this.grid_01,
				modalDataKey: this.modalDataKey,
				value: setTreeData.ROOT,
			});

			this.loadGrid = true;
		},
		getRowData(data) {
			this.selectedData = { ...data };
		},
		setUpdate(v) {
			this.dialog = false;

			const dt = {
				columnName: this.item.valueNm,
				value: this.selectedData['eccId'],
			};

			const dt2 = {
				columnName: this.item.valueNm2,
				value: this.selectedData['eccNm'],
			};
			if (!this.item.eccFgYn) {
				this.myBindingData.upEccNm = this.selectedData.eccNm;
				this.myBindingData.upEccId = this.selectedData.eccId;
				this.$emit('gridEditingFinish', dt);
				this.$emit('gridEditingFinish', dt2);
			} else {
				if (this.selectedData.eccFg == '1') {
					this.myBindingData.upEccNm = this.selectedData.eccNm;
					this.myBindingData.upEccId = this.selectedData.eccId;
					this.$emit('gridEditingFinish', dt);
					this.$emit('gridEditingFinish', dt2);
				} else {
					alert('공정(ECC)을 선택해주세요.');
					return false;
				}
			}
		},
		dialogOpenCloseEvent(val) {
			this.dialog = !val;
		},
		modifyValue(v, n) {
			// console.log(this.newValue(v));

			const dt = {
				columnName: n,
				// value: v.trim()
				value: this.newValue(v),
			};
			this.$emit('gridEditingFinish', dt);
		},
		newValue(value) {
			let returnVal = value.trim();
			if (this.item.decimalPlaces) {
				const x = returnVal.replace('.', '');
				const y = 10 ** -this.item.decimalPlaces;
				let z = x * y;
				// console.log(x * y);
				if (z === 0) {
					z = 10 ** -(this.item.decimalPlaces + 1);
				}
				// console.log(Utility.setFormatDecimal(z, this.item.decimalPlaces));
				returnVal = Utility.setFormatDecimal(z, this.item.decimalPlaces);
			}
			return returnVal;
		},
		onClick(event, item, valueNm) {
			this.$emit('inputClick', event, item, valueNm);
		},
	},
};

var FtnPlcFormPop = {
	grid_01: {
		data: [],
		column: [],
		option: {},
	},
};
</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;
	}

	.tui-grid-tree-icon {
		margin-left: -21px !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>
