<template>
	<div ref="mainDiv" class="l-layout">
		<PageTitle/>
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="end" no-gutters>
						<v-col :cols="5">
							<InputText :parentPrgmId="myPrgmId" label="설비종류명" valueNm="eqpmKindNm" :searchOption="true"
								:textCols="12" :labelCols="12" customClass="input-large" />
						</v-col>
						<v-col :cols="7" class="text-right">
							<BtnSearch @click="search" size="large" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="5" class="h100">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-4" style="padding-bottom: 30px !important;">
						<v-card-title class="pa-0">설비종류</v-card-title>
						<Buttons :parentPrgmId="myPrgmId" :bindingData="gridName" :btnActionsFnc="btnActions" />
					</div>
					<div class="h100 px-5" style="height:calc(100% - 70px)">
						<div ref="gridParent" class="w100 h100">
							<component :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName"
								:parentPrgmId="myPrgmId" @getRowsData="getRowData"
								:preventFocusChangeEventFlag="false" />
						</div>
					</div>
				</v-card>
			</v-col>
			<v-col :cols="7" class="h100">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-4" style="padding-bottom: 30px !important;">
						<v-card-title class="pa-0">설비종류 상세</v-card-title>
					</div>
					<div class="px-5" style="height:calc(100% - 76px)">
						<component :is="'Form'" :parentPrgmId="myPrgmId" :detailList="detailList"
							@gridEditingFinish="gridEditingFinish" />
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import { resize } from '@/mixin/resize.js';
import mixinGlobal from '@/mixin/global.js';
import BtnSearch from '~/components/common/button/BtnSearch';
import Buttons from '~/components/common/button/Buttons';
import selectCodeList from '@/components/common/select/selectCodeList';
import InputText from '@/components/common/input/InputText';
import Form from '~/components/common/form/Form';
import Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import SelectBox from '@/components/common/select/SelectBox';
import PageTitle from "~/components/common/PageTitle";

let myTitle;
// const myPrgmId = "PRG0013";
let myPrgmId;

export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		// context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
		// myTitle = myState.activeMenuInfo.menuNm;
		myPrgmId = context.route.query.prgmId;
		await context.store.commit('setActiveMenuInfo', myState.menuData[myPrgmId]);
		myTitle = await myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		BtnSearch,
		Buttons,
		selectCodeList,
		InputText,
		Form,
		Grid,
		Utility,
		SelectBox,
		PageTitle,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'eqpmKindGrid',
			loadGrid: false,
			tab: null,
			detailList: myDetail,
			selectValueList01: [],
			selectValue01: null,
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.useFg;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() { },
	mounted() {
		this.gridInit();
		// this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapActions({}),
		init() {
			// this.gridInit();
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			const gridWidth = this.$refs.gridParent.offsetWidth;

			const myOptions = {
				columnOptions: {
					resizable: true,
				}, header: {
					height: 38,
				},
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			const _this = this;
			const myColumns = [
				{
					header: '설비종류ID',
					name: 'eqpmKindId',
					width: gridWidth * 0.5,
					align: 'center',
				},
				{
					header: '설비종류명',
					name: 'eqpmKindNm',
					width: gridWidth * 0.5,
					align: 'left',
				},
				{ header: '등록자NO', name: 'regUserNo', hidden: true },
				{ header: '등록일시', name: 'regDttm', hidden: true },
				{ header: '수정자NO', name: 'procUserNo', hidden: true },
				{ header: '수정일시', name: 'procDttm', hidden: true },
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			this.loadGrid = true;

			this.getRowGridData();
		},
		async search() {
			this.loadGrid = false;
			await this.getRowGridData();
			await this.setPageData({
				isFind: false,
			});
		},
		async getRowGridData() {
			const res = await this.postApiReturn({
				apiKey: 'selectEqpmKind',
				resKey: 'eqpmKindData',
				sendParam: {
					eqpmKindNm: this.pageData.eqpmKindNm,
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
				};
				return newObj;
			});

			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});
			this.loadGrid = true;

			this.$nextTick(() => {
				if (newRes.length > 0) {
					this.$refs[this.gridName].focus({
						//rowKey: 0,
						rowKey:
							this.pageData.rowGridSelectKey == '' ||
								this.pageData.rowGridSelectKey == null
								? 0
								: this.pageData.rowGridSelectKey ==
									this.$refs[this.gridName].getData().length - 1
									? this.pageData.rowGridSelectKey
									: 0,
						setScroll: true,
					});
				}
			});
		},
		async getRowData(data) {
			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},

		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					var defaultRow = {
						eqpmKindId: '',
						eqpmKindNm: '',
						rowStat: null,
					};
					this.$refs[this.gridName].addRow(defaultRow);
					break;

				case 'remove':
					this.$refs[this.gridName].removeRow();
					break;

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						var validCheck = true;
						dataArr.filter(item => {
							if (item.rowStat != 'D') {
								// 	if (confirm('삭제하시겠습니까?')) {
								// 		validCheck = true;
								// 	} else {
								// 		validCheck = false;
								// 	}
								// } else {
								dataArr.forEach(item => {
									if (
										// if(item.eqpmGrpId == null || item.eqpmGrpId == ""||
										item.eqpmKindNm == '' ||
										item.eqpmKindNm == null
									) {
										validCheck = false;
										alert('필수 입력값을 입력해주세요');
									} else {
										validCheck = true;
									}
								});
							}
						});

						if (validCheck) {
							const sendParam = {
								datas: {
									dsEqpmKind: dataArr.map(item => ({
										...item,
									})),
								},
								params: {},
							};
							var result = await this.postUpdateApi({
								apiKey: 'saveEqpmKind',
								sendParam: sendParam,
							});

							if (result.data.dataset.deleteYn != '') {
								alert(result.data.dataset.deleteYn);
							} else {
								this.$nextTick(() => {
									this.setPageData({ isFind: true });
								});
							}
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	eqpmKindId: '',
	eqpmKindNm: '',

	// 선택된 그룹코드 상세 데이터
	rowGridSelectKey: 0,
	rowGridSelectData: null,

	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정
	/* data 세팅 */
	// 로컬 gridName 값과 동일한 이름으로 세팅
	eqpmKindGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			eqpmKindId: '',
			eqpmKindNm: null,
			rowStat: null,
		},
		buttonAuth: {
			add: true,
			remove: true,
			save: true,
			excel: false,
		},
	},
};

const myDetail = [
	{
		type: 'InputText',
		label: '설비종류 ID',
		valueNm: 'eqpmKindId',
		cols: 6,
		class: 'py-2 pr-4',
		iconShow: true,
		required: false,
		readonly: true,
		placeholder: '시스템 자동입력',
		labelCols: 12,
		textCols: 12,
	},
	{
		type: 'InputText',
		label: '설비종류명',
		valueNm: 'eqpmKindNm',
		disabled: false,
		cols: 6,
		class: 'py-2 pl-4',
		iconShow: true,
		required: true,
		labelCols: 12,
		textCols: 12,
	},
	{
		type: 'InputText',
		label: '등록자NO',
		valueNm: 'regUserNo',
		disabled: true,
		iconShow: true,
		cols: 6,
		class: 'py-2 pr-4 pt-5',
		placeholder: '시스템 자동입력',
		labelCols: 12,
		textCols: 12,
	},
	{
		type: 'InputText',
		label: '등록일시',
		valueNm: 'regDttm',
		iconShow: true,
		disabled: true,
		cols: 6,
		class: 'py-2 pl-4 pt-5',
		placeholder: '시스템 자동입력',
		labelCols: 12,
		textCols: 12,
	},
	{
		type: 'InputText',
		label: '수정자NO',
		valueNm: 'procUserNo',
		disabled: true,
		iconShow: true,
		cols: 6,
		class: 'py-2 pr-4 pt-5',
		placeholder: '시스템 자동입력',
		labelCols: 12,
		textCols: 12,
	},
	{
		type: 'InputText',
		label: '수정일시',
		valueNm: 'procDttm',
		disabled: true,
		iconShow: true,
		cols: 6,
		class: 'py-2 pl-4 pt-5',
		placeholder: '시스템 자동입력',
		labelCols: 12,
		textCols: 12,
	},
];
</script>